问:
Error in `[.data.frame`(m.data, , treat) : undefined columns selected when doing Mediation Analysis in R
I have the following dataset and I'm trying to run the mediate function on it:

```<code>> str(df)
tibble [33 × 7] (S3: tbl_df/tbl/data.frame)
 $ BoroughName         : chr [1:33] "City of London" "Barking and Dagenham" "Barnet" "Bexley" ...
 $ BoroughPopulation   : num [1:33] 5.2 98.3 208.3 142.3 171.3 ...
 $ PM25PWACugm3        : num [1:33] 17.9 13.2 13.2 13 13.7 12.9 15.1 13.2 13.5 13 ...
 $ Baselinedeaths      : num [1:33] 40 1247 2353 1814 1477 ...
 $ Attributablefraction: num [1:33] 9.9 7.4 7.4 7.3 7.7 7.2 8.4 7.4 7.6 7.3 ...
 $ Attributabledeaths  : num [1:33] 4 92 174 132 112 182 91 173 142 138 ...
 $ Lifeyearslost       : num [1:33] 60 1268 2360 1772 1855 ...
</code>```

I'm trying to run the mediate function with the following models for linear regression:

```<code> # fit a linear regression model to predict PM2.5 PWAC from borough BoroughPopulation
 model1 <- lm(df$PM25PWACugm3 ~ df$BoroughPopulation)

 # fit a linear regression model to predict baseline deaths from PM2.5 PWAC
 model2 <- lm(df$Baselinedeaths ~ df$PM25PWACugm3)

 # fit a linear regression model to predict baseline deaths from borough BoroughPopulation and PM2.5 PWAC
 model3 <- lm(df$Baselinedeaths ~ df$BoroughPopulation + df$PM25PWACugm3)

 # install and load the 'mediation' package
 library(mediation)

 mediate_result <- mediate(model1, model2, model3, treat = "BoroughPopulation", mediator = "PM25PWACugm3", data = df)
</code>```

But I keep getting this error:

```<code>Error in `[.data.frame`(m.data, , treat) : undefined columns selected
</code>```

I have checked the names of the columns multiple times and whether they contain any spaces or special characters, but they don't. The types of the variables also seem correct and I genuinely don't know what else could be the problem. Any help to make the mediate function work would be appreciated!

This is the dput(df) output:

dput(df)
structure(list(BoroughName = c("City of London", "Barking and Dagenham",
"Barnet", "Bexley", "Brent", "Bromley", "Camden", "Croydon",
"Ealing", "Enfield", "Greenwich", "Hackney", "Hammersmith and Fulham",
"Haringey", "Harrow", "Havering", "Hillingdon", "Hounslow", "Islington",
"Kensington and Chelsea", "Kingston upon Thames", "Lambeth",
"Lewisham", "Merton", "Newham", "Redbridge", "Richmond upon Thames",
"Southwark", "Sutton", "Tower Hamlets", "Waltham Forest", "Wandsworth",
"Westminster"), BoroughPopulation = c(5.2, 98.3, 208.3, 142.3,
171.3, 199.8, 125.1, 212, 194, 177.3, 141.2, 126.1, 102.5, 142.9,
142.4, 150.1, 157, 143.3, 111.9, 101.5, 95.3, 165.4, 157, 119.9,
144.5, 157.6, 120.7, 157.7, 118.7, 118.6, 141.6, 173.4, 133.6
), PM25PWACugm3 = c(17.9, 13.2, 13.2, 13, 13.7, 12.9, 15.1, 13.2,
13.5, 13, 13.6, 14.5, 14.5, 13.7, 12.8, 12.6, 12.7, 13.4, 15.3,
15.1, 13.1, 14.4, 13.9, 13.5, 14, 13.3, 13.3, 14.9, 13.1, 15.5,
13.5, 14.1, 15.5), Baselinedeaths = c(40, 1247, 2353, 1814, 1477,
2524, 1085, 2349, 1867, 1897, 1584, 1015, 882, 1106, 1386, 2126,
1754, 1362, 1035, 803, 1000, 1360, 1552, 1143, 1221, 1716, 1131,
1338, 1391, 983, 1356, 1513, 1071), Attributablefraction = c(9.9,
7.4, 7.4, 7.3, 7.7, 7.2, 8.4, 7.4, 7.6, 7.3, 7.6, 8.1, 8.1, 7.7,
7.2, 7.1, 7.1, 7.5, 8.5, 8.4, 7.4, 8.1, 7.8, 7.6, 7.9, 7.4, 7.4,
8.3, 7.3, 8.7, 7.6, 7.9, 8.6), Attributabledeaths = c(4, 92,
174, 132, 112, 182, 91, 173, 142, 138, 120, 82, 71, 85, 100,
150, 125, 102, 88, 67, 74, 109, 120, 86, 96, 128, 84, 111, 102,
85, 102, 119, 92), Lifeyearslost = c(60, 1268, 2360, 1772, 1855,
2379, 1568, 2423, 2175, 1944, 1659, 1429, 1166, 1472, 1544, 1968,
1788, 1564, 1394, 1119, 1008, 1797, 1773, 1259, 1572, 1799, 1238,
1793, 1367, 1314, 1546, 1686, 1570)), row.names = c(NA, -33L), class = c("tbl_df",
"tbl", "data.frame"))

Body:
I have the following dataset and I'm trying to run the mediate function on it:

> str(df)
tibble [33 × 7] (S3: tbl_df/tbl/data.frame)
 $ BoroughName         : chr [1:33] "City of London" "Barking and Dagenham" "Barnet" "Bexley" ...
 $ BoroughPopulation   : num [1:33] 5.2 98.3 208.3 142.3 171.3 ...
 $ PM25PWACugm3        : num [1:33] 17.9 13.2 13.2 13 13.7 12.9 15.1 13.2 13.5 13 ...
 $ Baselinedeaths      : num [1:33] 40 1247 2353 1814 1477 ...
 $ Attributablefraction: num [1:33] 9.9 7.4 7.4 7.3 7.7 7.2 8.4 7.4 7.6 7.3 ...
 $ Attributabledeaths  : num [1:33] 4 92 174 132 112 182 91 173 142 138 ...
 $ Lifeyearslost       : num [1:33] 60 1268 2360 1772 1855 ...

I'm trying to run the mediate function with the following models for linear regression:

 # fit a linear regression model to predict PM2.5 PWAC from borough BoroughPopulation
 model1 <- lm(df$PM25PWACugm3 ~ df$BoroughPopulation)

 # fit a linear regression model to predict baseline deaths from PM2.5 PWAC
 model2 <- lm(df$Baselinedeaths ~ df$PM25PWACugm3)

 # fit a linear regression model to predict baseline deaths from borough BoroughPopulation and PM2.5 PWAC
 model3 <- lm(df$Baselinedeaths ~ df$BoroughPopulation + df$PM25PWACugm3)

 # install and load the 'mediation' package
 library(mediation)

 mediate_result <- mediate(model1, model2, model3, treat = "BoroughPopulation", mediator = "PM25PWACugm3", data = df)

But I keep getting this error:

Error in `[.data.frame`(m.data, , treat) : undefined columns selected

I have checked the names of the columns multiple times and whether they contain any spaces or special characters, but they don't. The types of the variables also seem correct and I genuinely don't know what else could be the problem. Any help to make the mediate function work would be appreciated!

This is the dput(df) output:

dput(df)
structure(list(BoroughName = c("City of London", "Barking and Dagenham",
"Barnet", "Bexley", "Brent", "Bromley", "Camden", "Croydon",
"Ealing", "Enfield", "Greenwich", "Hackney", "Hammersmith and Fulham",
"Haringey", "Harrow", "Havering", "Hillingdon", "Hounslow", "Islington",
"Kensington and Chelsea", "Kingston upon Thames", "Lambeth",
"Lewisham", "Merton", "Newham", "Redbridge", "Richmond upon Thames",
"Southwark", "Sutton", "Tower Hamlets", "Waltham Forest", "Wandsworth",
"Westminster"), BoroughPopulation = c(5.2, 98.3, 208.3, 142.3,
171.3, 199.8, 125.1, 212, 194, 177.3, 141.2, 126.1, 102.5, 142.9,
142.4, 150.1, 157, 143.3, 111.9, 101.5, 95.3, 165.4, 157, 119.9,
144.5, 157.6, 120.7, 157.7, 118.7, 118.6, 141.6, 173.4, 133.6
), PM25PWACugm3 = c(17.9, 13.2, 13.2, 13, 13.7, 12.9, 15.1, 13.2,
13.5, 13, 13.6, 14.5, 14.5, 13.7, 12.8, 12.6, 12.7, 13.4, 15.3,
15.1, 13.1, 14.4, 13.9, 13.5, 14, 13.3, 13.3, 14.9, 13.1, 15.5,
13.5, 14.1, 15.5), Baselinedeaths = c(40, 1247, 2353, 1814, 1477,
2524, 1085, 2349, 1867, 1897, 1584, 1015, 882, 1106, 1386, 2126,
1754, 1362, 1035, 803, 1000, 1360, 1552, 1143, 1221, 1716, 1131,
1338, 1391, 983, 1356, 1513, 1071), Attributablefraction = c(9.9,
7.4, 7.4, 7.3, 7.7, 7.2, 8.4, 7.4, 7.6, 7.3, 7.6, 8.1, 8.1, 7.7,
7.2, 7.1, 7.1, 7.5, 8.5, 8.4, 7.4, 8.1, 7.8, 7.6, 7.9, 7.4, 7.4,
8.3, 7.3, 8.7, 7.6, 7.9, 8.6), Attributabledeaths = c(4, 92,
174, 132, 112, 182, 91, 173, 142, 138, 120, 82, 71, 85, 100,
150, 125, 102, 88, 67, 74, 109, 120, 86, 96, 128, 84, 111, 102,
85, 102, 119, 92), Lifeyearslost = c(60, 1268, 2360, 1772, 1855,
2379, 1568, 2423, 2175, 1944, 1659, 1429, 1166, 1472, 1544, 1968,
1788, 1564, 1394, 1119, 1008, 1797, 1773, 1259, 1572, 1799, 1238,
1793, 1367, 1314, 1546, 1686, 1570)), row.names = c(NA, -33L), class = c("tbl_df",
"tbl", "data.frame"))


来源: stackexchange

问:
PWA (Workbox) When User get Online, network error (failed) apis not getting call on iphones
I'm building web app which is pwa which is cached the data to serve offline as well as it also cached the network error api requests and whenever user get online it run those apis to up to date the DB.

Application is Progressive Web App (PWA), Its built with Javascript framework Vuejs. Additional we used the workbox for recall the network failed apis functionality, these workbox functionality working on all devices except on iPhone.

I've attached the vue.config.js file which has the config of workbox, Please let me know what I can do to fix the error on iPhone.

Your help will be very appreciated!

```<code>Filename: Vue.config.js

configureWebpack: {
entry: ['babel-polyfill', './src/main.js'],
},
pwa: {
workboxPluginMode: 'GenerateSW',
workboxOptions: {
navigateFallback: '/index.html',
skipWaiting: true,
runtimeCaching: [
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
handler: 'networkOnly',
options: {
cacheName: 'api',
},
},
{
^https:\/\/api\.dev\.firststep\.zinpro\.cn\/apiPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'POST',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'new-tasks-queue-0',
options: {
maxRetentionTime: 24 * 60, // 24 hr
},
},
},
},
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'DELETE',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'delete-tasks-queue-1',
options: {
maxRetentionTime: 24 * 60, // minutes
},
},
},
},
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'GET',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'new-tasks-queue-2',
options: {
maxRetentionTime: 24 * 60, // minutes
},
},
},
},
],
},
themeColor: '#000000',
iconPaths: {
favicon32: 'icons/ZinproFavicon32x32.png',
favicon16: 'icons/ZinproFavicon32x32.png',
appleTouchIcon: 'icons/Zinpro_App_Icon_192x192.png',
maskIcon: 'icons/safari-pinned-tab.svg',
msTileImage: 'icons/Zinpro_App_Icon_192x192.png',
},
},
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm building web app which is pwa which is cached the data to serve offline as well as it also cached the network error api requests and whenever user get online it run those apis to up to date the DB.

Application is Progressive Web App (PWA), Its built with Javascript framework Vuejs. Additional we used the workbox for recall the network failed apis functionality, these workbox functionality working on all devices except on iPhone.

I've attached the vue.config.js file which has the config of workbox, Please let me know what I can do to fix the error on iPhone.

Your help will be very appreciated!

Filename: Vue.config.js

configureWebpack: {
entry: ['babel-polyfill', './src/main.js'],
},
pwa: {
workboxPluginMode: 'GenerateSW',
workboxOptions: {
navigateFallback: '/index.html',
skipWaiting: true,
runtimeCaching: [
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
handler: 'networkOnly',
options: {
cacheName: 'api',
},
},
{
^https:\/\/api\.dev\.firststep\.zinpro\.cn\/apiPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'POST',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'new-tasks-queue-0',
options: {
maxRetentionTime: 24 * 60, // 24 hr
},
},
},
},
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'DELETE',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'delete-tasks-queue-1',
options: {
maxRetentionTime: 24 * 60, // minutes
},
},
},
},
{
urlPattern: ^https:\/\/api\.dev\.firststep\.zinpro\.cn\/api,
method: 'GET',
handler: 'networkOnly',
options: {
backgroundSync: {
name: 'new-tasks-queue-2',
options: {
maxRetentionTime: 24 * 60, // minutes
},
},
},
},
],
},
themeColor: '#000000',
iconPaths: {
favicon32: 'icons/ZinproFavicon32x32.png',
favicon16: 'icons/ZinproFavicon32x32.png',
appleTouchIcon: 'icons/Zinpro_App_Icon_192x192.png',
maskIcon: 'icons/safari-pinned-tab.svg',
msTileImage: 'icons/Zinpro_App_Icon_192x192.png',
},
},
}


问:
Why won't my rectangle move on screen in pygame?
I'm kinda new to Pygame and I'm looking to start a new small project, I've only really done one before but I'm stuck on it. There's a small rectangle at the bottom of the screen and the idea is to have it move. I don't have any syntax errors showing but nothing is happening. the code is below:

```<code>import pygame

pygame.init()
x = 190
vel = 5
screen = pygame.display.set_mode((400, 400))
while True:

    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT]:
        x -= vel

    if keys[pygame.K_RIGHT]:
        x += vel

    bg = (50,50,50)
    white = (255,255,255)
    screen.fill(bg)
    pygame.draw.rect(screen, white, pygame.Rect(x, 390, 20, 10))
    pygame.display.update()
</code>```

When I run the code it should have it so that the rectangle moves left and right in increments of 5 pixels, but nothing happens.

Body:
I'm kinda new to Pygame and I'm looking to start a new small project, I've only really done one before but I'm stuck on it. There's a small rectangle at the bottom of the screen and the idea is to have it move. I don't have any syntax errors showing but nothing is happening. the code is below:

import pygame

pygame.init()
x = 190
vel = 5
screen = pygame.display.set_mode((400, 400))
while True:

    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT]:
        x -= vel

    if keys[pygame.K_RIGHT]:
        x += vel

    bg = (50,50,50)
    white = (255,255,255)
    screen.fill(bg)
    pygame.draw.rect(screen, white, pygame.Rect(x, 390, 20, 10))
    pygame.display.update()

When I run the code it should have it so that the rectangle moves left and right in increments of 5 pixels, but nothing happens.


问:
want to unite attached spatial lines onto single line
I've created lines from unite spatial points. I want to unite attached lines into a single line and then number the lines based on their spatial position. Is the a way to do this in R? Follows the lines result.

Expect to get attached lines


问:
Firebase rules: still not safe after implementing auth
I have these rules in my Firebase Real-time Database:

```<code>{
  "rules": {
      ".read":"auth !== null && auth.uid === 'my_uid'",
      ".write": false
  }
}
</code>```

When I try to read the data without authentication, access is denied. So far, only my app can read it successfully.

Still, I'm getting an email from time to time, from Firebase, that my rules are not secure and that everyone can read the data.

What am I missing here?

Body:
I have these rules in my Firebase Real-time Database:

{
  "rules": {
      ".read":"auth !== null && auth.uid === 'my_uid'",
      ".write": false
  }
}

When I try to read the data without authentication, access is denied. So far, only my app can read it successfully.

Still, I'm getting an email from time to time, from Firebase, that my rules are not secure and that everyone can read the data.

What am I missing here?


问:
how to connect esp32 with a mac address that i have using blutooth?
i'm trying to connect my e-scooter to blutooth using esp32 i got the scooter's mac address so is it possible to only connect them with each other

I searched everywhere on how to connect any device with mac address but couldn't find


问:
How to store files in azure table using form from react?
I want to store user files like pdf, doc, and image from user interface using React. How can i store these types of files in azure table?

Can anyone help?


问:
The named parameter 'dataSource' is required, but there's no corresponding argument. Try adding the required argument
I'm using syncfusion package; in this case, it is an exponential moving average (EMA).

An EMA indicator is a simple, arithmetic moving average that is calculated by adding the closing price for the number of time periods and dividing the total value by the number of periods.

This is my code:

```<code>
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class EMA extends StatefulWidget {
  const EMA({super.key});

  @override
  State<EMA> createState() => _EMAState();
}

class _EMAState extends State<EMA> {
 @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: Center(
          child: SfCartesianChart(
            primaryXAxis: DateTimeAxis(),
            legend: Legend(isVisible: true),
            indicators: <TechnicalIndicators<dynamic, dynamic>>[
        EmaIndicator<dynamic, dynamic>(
            seriesName: 'HiloOpenClose',
            valueField: 'high',)],
            series: <ChartSeries<ChartData, DateTime>>[
        HiloOpenCloseSeries<ChartData, DateTime>( //hhere throws the error
            name: 'HiloOpenClose')
            ]
          )
        )
      );
    }

}

class ChartData {
  ChartData(this.x, this.low, this.high, this.open, this.close, );
  final DateTime x;
  final double? low;
  final double? high;
  final double? open;
  final double? close;
}
</code>```

My data:

```<code>  import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class CartesianChart extends StatefulWidget {
  CartesianChart({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _CartesianChartState createState() => _CartesianChartState();
}

class _CartesianChartState extends State<CartesianChart> {
  late List<ExpenseData> _chartData;
  late TooltipBehavior _tooltipBehavior;

  @override
  void initState() {
    _chartData = getChartData();
    _tooltipBehavior = TooltipBehavior(enable: true);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: SfCartesianChart(
        title: ChartTitle(
            text: 'Hours focused \n Main activities'),
        legend: Legend(isVisible: true),
        tooltipBehavior: _tooltipBehavior,
        series: <ChartSeries>[
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.father,
              name: 'Node.js',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.mother,
              name: 'Flutter',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.son,
              name: 'Learn from youtube',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.daughter,
              name: 'MongoDB',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
        ],
        primaryXAxis: CategoryAxis(),
      ),
    ));
  }

  List<ExpenseData> getChartData() {
    final List<ExpenseData> chartData = [
      ExpenseData('Monday', 55, 40, 45, 48),
      ExpenseData('Tuesday', 33, 45, 54, 28),
      ExpenseData('Wednesday', 43, 23, 20, 34),
      ExpenseData('Thursday', 32, 54, 23, 54),
      ExpenseData('Friday', 56, 18, 43, 55),
      ExpenseData('Saturday', 23, 54, 33, 56),
    ];
    return chartData;
  }
}

class ExpenseData {
  ExpenseData(
      this.expenseCategory, this.father, this.mother, this.son, this.daughter);
  final String expenseCategory;
  final num father;
  final num mother;
  final num son;
  final num daughter;
}
</code>```

What should I do in order to solve this problem?

Thanks for any help you can provide.

Body:
I'm using syncfusion package; in this case, it is an exponential moving average (EMA).

An EMA indicator is a simple, arithmetic moving average that is calculated by adding the closing price for the number of time periods and dividing the total value by the number of periods.

This is my code:

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class EMA extends StatefulWidget {
  const EMA({super.key});

  @override
  State<EMA> createState() => _EMAState();
}

class _EMAState extends State<EMA> {
 @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: Center(
          child: SfCartesianChart(
            primaryXAxis: DateTimeAxis(),
            legend: Legend(isVisible: true),
            indicators: <TechnicalIndicators<dynamic, dynamic>>[
        EmaIndicator<dynamic, dynamic>(
            seriesName: 'HiloOpenClose',
            valueField: 'high',)],
            series: <ChartSeries<ChartData, DateTime>>[
        HiloOpenCloseSeries<ChartData, DateTime>( //hhere throws the error
            name: 'HiloOpenClose')
            ]
          )
        )
      );
    }

}

class ChartData {
  ChartData(this.x, this.low, this.high, this.open, this.close, );
  final DateTime x;
  final double? low;
  final double? high;
  final double? open;
  final double? close;
}

My data:

  import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class CartesianChart extends StatefulWidget {
  CartesianChart({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _CartesianChartState createState() => _CartesianChartState();
}

class _CartesianChartState extends State<CartesianChart> {
  late List<ExpenseData> _chartData;
  late TooltipBehavior _tooltipBehavior;

  @override
  void initState() {
    _chartData = getChartData();
    _tooltipBehavior = TooltipBehavior(enable: true);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: SfCartesianChart(
        title: ChartTitle(
            text: 'Hours focused \n Main activities'),
        legend: Legend(isVisible: true),
        tooltipBehavior: _tooltipBehavior,
        series: <ChartSeries>[
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.father,
              name: 'Node.js',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.mother,
              name: 'Flutter',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.son,
              name: 'Learn from youtube',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
          StackedColumnSeries<ExpenseData, String>(
              dataSource: _chartData,
              xValueMapper: (ExpenseData exp, _) => exp.expenseCategory,
              yValueMapper: (ExpenseData exp, _) => exp.daughter,
              name: 'MongoDB',
              markerSettings: MarkerSettings(
                isVisible: true,
              )),
        ],
        primaryXAxis: CategoryAxis(),
      ),
    ));
  }

  List<ExpenseData> getChartData() {
    final List<ExpenseData> chartData = [
      ExpenseData('Monday', 55, 40, 45, 48),
      ExpenseData('Tuesday', 33, 45, 54, 28),
      ExpenseData('Wednesday', 43, 23, 20, 34),
      ExpenseData('Thursday', 32, 54, 23, 54),
      ExpenseData('Friday', 56, 18, 43, 55),
      ExpenseData('Saturday', 23, 54, 33, 56),
    ];
    return chartData;
  }
}

class ExpenseData {
  ExpenseData(
      this.expenseCategory, this.father, this.mother, this.son, this.daughter);
  final String expenseCategory;
  final num father;
  final num mother;
  final num son;
  final num daughter;
}

What should I do in order to solve this problem?

Thanks for any help you can provide.


问:
Three variables as a heatmap
I'm a beginner at programming, and I want to plot my data as a heatmap which has the following structure for a paper I'm currently writing

```<code>X = [20,21,21,21,21,21,21,20,20,17,17,16.75,16.5,18,16,16,16,16,22,17.75,19.75,19.75,18.5,17,20.25,18]

Y = [35,24.5,25,32.5,32.5,32.5,25.5,25,25,4.5,4.5,4.5,5,5,2.25,3,5,4.5,12.5,1,6,6,5.25,8.5,6.5,3]

Z = [0,0.215,0,0,0,0,0.1,0.15,0.2,0.25,0.25,0.175,0.14,0.25,0.225,0.175,0.125,0.175,0.1,0.35,0.375,0.375,0.19,0.13,0.275,0.1]
</code>```

The x and y-axis shall be represented by X and Y, while the 'heat' is represented by the values of Z.

E.g. at coordinate (x,y) = (20,35) the intensity shall be 0. How can this be achieved by using matplotlib? Looking at posts which relate to the keyword heatmap or even to those related to the term contour map, I could not transfer it to this problem yet.

When I try to plot with this code that i found on the net (matlab fit a HeatMap into a subplot) , because theaxes when i import from my csv file it gave me an error:

the error was: ValueError: Index contains duplicate entries, cannot reshape

if someone can help me i will be grateful.

Title: Three variables as a heatmap

Body:
I'm a beginner at programming, and I want to plot my data as a heatmap which has the following structure for a paper I'm currently writing

X = [20,21,21,21,21,21,21,20,20,17,17,16.75,16.5,18,16,16,16,16,22,17.75,19.75,19.75,18.5,17,20.25,18]

Y = [35,24.5,25,32.5,32.5,32.5,25.5,25,25,4.5,4.5,4.5,5,5,2.25,3,5,4.5,12.5,1,6,6,5.25,8.5,6.5,3]

Z = [0,0.215,0,0,0,0,0.1,0.15,0.2,0.25,0.25,0.175,0.14,0.25,0.225,0.175,0.125,0.175,0.1,0.35,0.375,0.375,0.19,0.13,0.275,0.1]

The x and y-axis shall be represented by X and Y, while the 'heat' is represented by the values of Z.

E.g. at coordinate (x,y) = (20,35) the intensity shall be 0. How can this be achieved by using matplotlib? Looking at posts which relate to the keyword heatmap or even to those related to the term contour map, I could not transfer it to this problem yet.

When I try to plot with this code that i found on the net (matlab fit a HeatMap into a subplot) , because theaxes when i import from my csv file it gave me an error:

the error was: ValueError: Index contains duplicate entries, cannot reshape

if someone can help me i will be grateful.


问:
scrollIntoView() not working after first render
/routes/[symbol]/+page.ts:

afterUpdate(() => {
    console.log(
        "from calendar view: symbol:",
        data.symbol,
        data.calendar.months[data.symbol],
        `${new Date().getFullYear()}-${new Date().getMonth() + 1}`
    )

    if (data.calendar.months[data.symbol] != null) {
        let el = document.getElementById(`${new Date().getFullYear()}-${new Date().getMonth() + 1}`)
        console.log("element: ", el)

        el!.scrollIntoView()
    }
})
```

In the initial render, there is a data load that takes place in +layout.ts.  When this happens, the scrollIntoView works fine.  However, if I navigate back to this link, and no data load is necessary, it does not work.  The element is found, and the console.logs happen as expected, but it does not scroll.  Any suggestions?

Body:
/routes/[symbol]/+page.ts:

afterUpdate(() => {
    console.log(
        "from calendar view: symbol:",
        data.symbol,
        data.calendar.months[data.symbol],
        `${new Date().getFullYear()}-${new Date().getMonth() + 1}`
    )

    if (data.calendar.months[data.symbol] != null) {
        let el = document.getElementById(`${new Date().getFullYear()}-${new Date().getMonth() + 1}`)
        console.log("element: ", el)

        el!.scrollIntoView()
    }
})

In the initial render, there is a data load that takes place in +layout.ts.  When this happens, the scrollIntoView works fine.  However, if I navigate back to this link, and no data load is necessary, it does not work.  The element is found, and the console.logs happen as expected, but it does not scroll.  Any suggestions?


问:
Is there a quick (equation) way to calculate the solar zenith angle if the solar azimuth angle is known?
I'm reviewing solar geometry calculations regarding to shading problems and, in the basic case, one wants to know whether a point will be shaded by another point at certain distance, height, azimuth angle made by both points regardint the N-S line and date.

The problem essentially reduces to calculate the solar zenith angle for that specified day when the solar azimuth angle is equal to the azimuth angle made by the points and compare it to the altitude angle made by both points (if the altitude angle is greater than the zenith angle, the point is shaded).

My issue is that equations in literature calculate the zenith first according to location and datetime, and then the solar azimuth as a function of the zenith. Both are correlated, but trying to solve the equations as functions of the solar azimuth seems to be analytically intractable (online equation solvers don't give answers).

I either want to know whether is a equation of the zenith as a function of the solar azimuth or if there is an analytical solution for the equation:

a sin(x) + b cos(x) = c

I tried solving the solar azimuth equation as a function of the zenith, and ran into a equation of the basic form a sin(x) + b cos(x) = c, which apparently has no analytical answer.


问:
XGBoost prediction input dimensionality error
I have the following model:

```<code>X_train_xgb, X_test_xgb, y_train_xgb, y_test_xgb = X_train.values, X_test.values, y_train.values, y_test.values
xgb_model = xgboost.XGBRegressor()
xgb_model.fit(X_train_xgb, y_train_xgb)
</code>```

X_train and X_test have the same count of columns. However, running

```<code>test_point = X_test_xgb[42]
original_model_prediction = xgb_model.predict(test_point)
</code>```

returns

C:/buildkite-agent/builds/buildkite-windows-cpu-autoscaling-group-i-08de971ced8a8cdc6-1/xgboost/xgboost-ci-windows/src/predictor/cpu_predictor.cc:377: Check failed: m->NumColumns() == model.learner_model_param->num_feature (1 vs. 170) : Number of columns in data must equal to trained model.

test_point.shape returns (170,0). I have 170 columns, so this should be ok.

This has to be some kind of dimensionality issue, as test_point = X_test_xgb[42:43] returns a result when used in xgb_model.predict(test_point) (albeit just exactly one result). Does .predict() expect a header row? even though I trained using an np.array?

Also, neither X_test_xgb.T[42] nor test_point.T solve the problem (as expected). Where is my mistake?

Thanks already!

Body:
I have the following model:

X_train_xgb, X_test_xgb, y_train_xgb, y_test_xgb = X_train.values, X_test.values, y_train.values, y_test.values
xgb_model = xgboost.XGBRegressor()
xgb_model.fit(X_train_xgb, y_train_xgb)

X_train and X_test have the same count of columns. However, running

test_point = X_test_xgb[42]
original_model_prediction = xgb_model.predict(test_point)

returns

C:/buildkite-agent/builds/buildkite-windows-cpu-autoscaling-group-i-08de971ced8a8cdc6-1/xgboost/xgboost-ci-windows/src/predictor/cpu_predictor.cc:377: Check failed: m->NumColumns() == model.learner_model_param->num_feature (1 vs. 170) : Number of columns in data must equal to trained model.

test_point.shape returns (170,0). I have 170 columns, so this should be ok.

This has to be some kind of dimensionality issue, as test_point = X_test_xgb[42:43] returns a result when used in xgb_model.predict(test_point) (albeit just exactly one result). Does .predict() expect a header row? even though I trained using an np.array?

Also, neither X_test_xgb.T[42] nor test_point.T solve the problem (as expected). Where is my mistake?

Thanks already!


问:
Firestore setting collection based on users value
I'm not sure how to properly integrate this. I'm using bare react native with firebase 8.2.3. I'm trying to add a memo function into my app where users can check there memos on there home screen when first opening up the app. I have a separate collection called 'users' In that collection are stored values for each user with an "Agency" value. I want to separate memos based on agency. For example there are multiple collections called "HR,Finance,Managment....etccc" I set up a function to pull the user data first to determine which agency they are from and then another function to fetch there memos. When I run this in the simulator it does not set the agency in the collection.. it just hangs.. here is what I wrote.

```<code>

const HomeScreen = ({navigation}) => {
  const {user} = useContext(AuthContext);
  const [posts, setPosts] = useState(null);
  const [loading, setLoading] = useState(true);
  const [deleted, setDeleted] = useState(false);
  const [userData, setUserData] = useState(null);

  const getUser = async() => {
    await firestore()
    .collection('users')
    .doc(user.email)
    .get()
    .then((documentSnapshot) => {
      if( documentSnapshot.exists ) {
        console.log('User Data', documentSnapshot.data());
        setUserData(documentSnapshot.data());
      }
    })
  }

  useEffect(() => {
    getUser();
  }, []);

  const fetchPosts = async () => {
    try {
      const list = [];

      await firestore()
        .collection(userData.agency)
        .orderBy('postTime', 'desc')
        .get()
        .then((querySnapshot) => {
          // console.log('Total Posts: ', querySnapshot.size);

          querySnapshot.forEach((doc) => {
            const {
              userId,
              post,
              postImg,
              postTime,
              likes,
              comments,
            } = doc.data();
            list.push({
              id: doc.id,
              userId,
              userName: 'Test Name',
              userImg:
                'omitted',
              postTime: postTime,
              post,
              postImg,
              liked: false,
              likes,
              comments,
            });
          });
        });

      setPosts(list);

      if (loading) {
        setLoading(false);
      }

      console.log('Posts: ', posts);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, []);

</code>```

Any help would be greatly appreciated :)
I'm still very new at this :)

Body:
I'm not sure how to properly integrate this. I'm using bare react native with firebase 8.2.3. I'm trying to add a memo function into my app where users can check there memos on there home screen when first opening up the app. I have a separate collection called 'users' In that collection are stored values for each user with an "Agency" value. I want to separate memos based on agency. For example there are multiple collections called "HR,Finance,Managment....etccc" I set up a function to pull the user data first to determine which agency they are from and then another function to fetch there memos. When I run this in the simulator it does not set the agency in the collection.. it just hangs.. here is what I wrote.

const HomeScreen = ({navigation}) => {
  const {user} = useContext(AuthContext);
  const [posts, setPosts] = useState(null);
  const [loading, setLoading] = useState(true);
  const [deleted, setDeleted] = useState(false);
  const [userData, setUserData] = useState(null);

  const getUser = async() => {
    await firestore()
    .collection('users')
    .doc(user.email)
    .get()
    .then((documentSnapshot) => {
      if( documentSnapshot.exists ) {
        console.log('User Data', documentSnapshot.data());
        setUserData(documentSnapshot.data());
      }
    })
  }

  useEffect(() => {
    getUser();
  }, []);

  const fetchPosts = async () => {
    try {
      const list = [];

      await firestore()
        .collection(userData.agency)
        .orderBy('postTime', 'desc')
        .get()
        .then((querySnapshot) => {
          // console.log('Total Posts: ', querySnapshot.size);

          querySnapshot.forEach((doc) => {
            const {
              userId,
              post,
              postImg,
              postTime,
              likes,
              comments,
            } = doc.data();
            list.push({
              id: doc.id,
              userId,
              userName: 'Test Name',
              userImg:
                'omitted',
              postTime: postTime,
              post,
              postImg,
              liked: false,
              likes,
              comments,
            });
          });
        });

      setPosts(list);

      if (loading) {
        setLoading(false);
      }

      console.log('Posts: ', posts);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, []);

Any help would be greatly appreciated :)
I'm still very new at this :)


问:
Download source code of my app at Google Play
I've got a problem. I deleted all my programmed mobile apps in my computer. It's my fault, yes, but I know that they've got all my original source code on Google Play. Can I download it? When I'm logged of course. I need files for Android studio. Do you know if it can be downloaded somewhere?

I searched on Google Play. There is some download of source but Android studio can't load it without broken code.


问:
Why Java Predicate contains implementation methods like not, or, and?
While looking into the source code of Predicate interface in java I found, it contains few implemented methods like or, and, isEqual. But how a interface can contain non abstract methods?

```<code>@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> **and**(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate<T> **negate**() {
        return (t) -> !test(t);
    }

    default Predicate<T> **or**(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static <T> Predicate<T> **isEqual**(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

    @SuppressWarnings("unchecked")
    static <T> Predicate<T> **not**(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
    }
</code>```

Could anyone please explain how an interface can contain implemented methods in it?

Thanks

Body:
While looking into the source code of Predicate interface in java I found, it contains few implemented methods like or, and, isEqual. But how a interface can contain non abstract methods?

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> **and**(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate<T> **negate**() {
        return (t) -> !test(t);
    }

    default Predicate<T> **or**(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static <T> Predicate<T> **isEqual**(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

    @SuppressWarnings("unchecked")
    static <T> Predicate<T> **not**(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
    }

Could anyone please explain how an interface can contain implemented methods in it?

Thanks


问:
Add logo to SankeyNetwork chart?
I am trying to add a logo to a sankey chart created using the code below but all attempts did not work:

```<code>library(networkD3)

p <- sankeyNetwork(Links = links, Nodes = nodes, Source = "IDsource", Target = "IDtarget",
              Value = "value", NodeID = "name")
p
</code>```

Any idea?

Title: Add logo to SankeyNetwork chart?

Body:
I am trying to add a logo to a sankey chart created using the code below but all attempts did not work:

library(networkD3)

p <- sankeyNetwork(Links = links, Nodes = nodes, Source = "IDsource", Target = "IDtarget",
              Value = "value", NodeID = "name")
p

Any idea?


问:
A lot action (including "Reformat Code") are disabled in rider
Somehow (only in Rider 2022.3.1, not in Intellij Idea Ultimate) some actions are disabled. This includes the CTRL-Alt-L action "Reformat Code". This action also is disabled when accessed over Main text menu toolbar.

Other actions are enabled but do not have an effect, like the "Extend Selection" action.

Any idea what is wrong?

The project is a Unity 3D (Game engine) project with C# code. No .editorconfig is present. Support for .editorconfig is disabled.

Same project does work fine when opened on another computer with the same Rider version.


问:
Tendermint error-BigchainDB network: "Connection refused"
I'm trying to set up a local BigchainDB network with three Raspberry Pis using this repository as a reference: BigchainDB Ansible deployment recipes

However, all my nodes encounter a connection refused problem on tendermint.service. Tendermint is on v0.31.5 and BigchainDB on v2.0.0.

I checked if the port is blocked, but it seems to be fine. The error that I am getting is:

Jan 09 14:52:41 ubuntu tendermint[807]: E[2023-01-09|14:52:41.985] abci.socketClient failed to connect to tcp://0.0.0.0:26658.  Retrying... module=abci-client connnt failed to connect to tcp://0.0.0.0:26658.  Retrying... module=abci-client connection=query err="dial tcp 0.0.0.0:26658: connect: connection refused"

I am running Tendermint using a unit file.

[Unit]
Description=Tendermint. Byzantine-fault tolerant state machine replication.
Documentation=https://tendermint.readthedocs.io/en/master/

[Service]
ExecStart=/usr/local/bin/tendermint node \
                   --p2p.laddr "tcp://0.0.0.0:26656" \
                   --proxy_app="tcp://0.0.0.0:26658" \
                   --consensus.create_empty_blocks=false \
                   --p2p.pex=false
WorkingDirectory=/home/ubuntu
User=tendermint
Group=bigchaindb

[Install]
WantedBy=multi-user.target
```
<p>I've also configured the <em>genesis.json</em> file on every node:</p>
<pre class="lang-json prettyprint-override"><code>{
 "genesis_time": "2022-12-19T11:03:38.312591884Z",
 "chain_id": "test-chain-sveGDu",
 "consensus_params": {
  "block": {
   "max_bytes": "22020096",
   "max_gas": "-1",
   "time_iota_ms": "1000"
  },
  "evidence": {
   "max_age": "100000"
  },
  "validator": {
   "pub_key_types": [
    "ed25519"
   ]
  }
 },
 "validators": [
  {
   "address": "87498C9693362176BFC2A4122133568297865193",
   "pub_key": {
    "type": "tendermint/PubKeyEd25519",
    "value": "dIy8HUovVJatppDrmJieSGW26jWSJrNhzwHMJetysqA="
   },
   "power": "10",
   "name": ""
  },
  {
   "address": "B59216978AB15F31171E8AB482F62D768721DA13",
   "pub_key": {
    "type": "tendermint/PubKeyEd25519",
    "value": "64BTBlnCPSe26HJfpnCkV8A6BS5w//rAqVu/C01sOqA="
   },
   "power": "10",
   "name": ""
  },
  {
   "address": "6067D6D53CD82EBF9C1F4704AC9F27BAE7CB8F9F",
   "pub_key": {
    "type": "tendermint/PubKeyEd25519",
    "value": "QGNyJpLgqjlRanNgtRdAsLTnpylmSo9FymkPFXSnZbI="
   },
   "power": "10",
   "name": ""
  }
 ],
 "app_hash": ""
}
</code>```

Body:
I'm trying to set up a local BigchainDB network with three Raspberry Pis using this repository as a reference: BigchainDB Ansible deployment recipes

However, all my nodes encounter a connection refused problem on tendermint.service. Tendermint is on v0.31.5 and BigchainDB on v2.0.0.

I checked if the port is blocked, but it seems to be fine. The error that I am getting is:

Jan 09 14:52:41 ubuntu tendermint[807]: E[2023-01-09|14:52:41.985] abci.socketClient failed to connect to tcp://0.0.0.0:26658.  Retrying... module=abci-client connnt failed to connect to tcp://0.0.0.0:26658.  Retrying... module=abci-client connection=query err="dial tcp 0.0.0.0:26658: connect: connection refused"

I am running Tendermint using a unit file.

[Unit]
Description=Tendermint. Byzantine-fault tolerant state machine replication.
Documentation=https://tendermint.readthedocs.io/en/master/

[Service]
ExecStart=/usr/local/bin/tendermint node \
                   --p2p.laddr "tcp://0.0.0.0:26656" \
                   --proxy_app="tcp://0.0.0.0:26658" \
                   --consensus.create_empty_blocks=false \
                   --p2p.pex=false
WorkingDirectory=/home/ubuntu
User=tendermint
Group=bigchaindb

[Install]
WantedBy=multi-user.target

I've also configured the genesis.json file on every node:

{
 "genesis_time": "2022-12-19T11:03:38.312591884Z",
 "chain_id": "test-chain-sveGDu",
 "consensus_params": {
  "block": {
   "max_bytes": "22020096",
   "max_gas": "-1",
   "time_iota_ms": "1000"
  },
  "evidence": {
   "max_age": "100000"
  },
  "validator": {
   "pub_key_types": [
    "ed25519"
   ]
  }
 },
 "validators": [
  {
   "address": "87498C9693362176BFC2A4122133568297865193",
   "pub_key": {
    "type": "tendermint/PubKeyEd25519",
    "value": "dIy8HUovVJatppDrmJieSGW26jWSJrNhzwHMJetysqA="
   },
   "power": "10",
   "name": ""
  },
  {
   "address": "B59216978AB15F31171E8AB482F62D768721DA13",
   "pub_key": {
    "type": "tendermint/PubKeyEd25519",
    "value": "64BTBlnCPSe26HJfpnCkV8A6BS5w//rAqVu/C01sOqA="
   },
   "power": "10",
   "name": ""
  },
  {
   "address": "6067D6D53CD82EBF9C1F4704AC9F27BAE7CB8F9F",
   "pub_key": {
    "type": "tendermint/PubKeyEd25519",
    "value": "QGNyJpLgqjlRanNgtRdAsLTnpylmSo9FymkPFXSnZbI="
   },
   "power": "10",
   "name": ""
  }
 ],
 "app_hash": ""
}


问:
Using data from URL Request in Python
I am getting data back from a URL request and the response seems to be headers and data in the form of csv.  How do I make this data into something useable inside of Python?

#pulls weather data from visual crossing
#https://www.visualcrossing.com/weather/weather-data-services

```<code>#pulls weather data from visual crossing
#https://www.visualcrossing.com/weather/weather-data-services

import requests

#create URL
url = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Edmonton?unitGroup=metric&include=current&key=[API CREDENTIALS]&contentType=csv"

#request Instance, returns data as a string ISO-8859-1
html = requests.get(url).text
print(html)
</code>```

The response I get is below....

```<code>name,datetime,temp,feelslike,dew,humidity,precip,precipprob,preciptype,snow,snowdepth,windgust,windspeed,winddir,sealevelpressure,cloudcover,visibility,solarradiation,solarenergy,uvindex,severerisk,conditions,icon,stations
"Edmonton, AB, Canada",2023-01-07T23:31:02,-9.6,-9.6,-11.4,86.7,0,0,,0,0,,7.9,167.8,1014,44.8,,0,,0,,Partially cloudy,partly-cloudy-night,"CZOL,CXEC,AU867"
</code>```

I am pretty new to Python so I assume this is something simple, I did some searches but I think I am missing the proper terminology of what I am trying to accomplish.

Title: Using data from URL Request in Python

Body:
I am getting data back from a URL request and the response seems to be headers and data in the form of csv.  How do I make this data into something useable inside of Python?

#pulls weather data from visual crossing
#https://www.visualcrossing.com/weather/weather-data-services

#pulls weather data from visual crossing
#https://www.visualcrossing.com/weather/weather-data-services

import requests

#create URL
url = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/Edmonton?unitGroup=metric&include=current&key=[API CREDENTIALS]&contentType=csv"

#request Instance, returns data as a string ISO-8859-1
html = requests.get(url).text
print(html)

The response I get is below....

name,datetime,temp,feelslike,dew,humidity,precip,precipprob,preciptype,snow,snowdepth,windgust,windspeed,winddir,sealevelpressure,cloudcover,visibility,solarradiation,solarenergy,uvindex,severerisk,conditions,icon,stations
"Edmonton, AB, Canada",2023-01-07T23:31:02,-9.6,-9.6,-11.4,86.7,0,0,,0,0,,7.9,167.8,1014,44.8,,0,,0,,Partially cloudy,partly-cloudy-night,"CZOL,CXEC,AU867"

I am pretty new to Python so I assume this is something simple, I did some searches but I think I am missing the proper terminology of what I am trying to accomplish.


问:
How to change representation while keeping field editable in DRF?
I have two classes:

class ClassA(models.Model):
    name = models.Charfield(...)
    tags = models.ManyToManyField("TagClass", blank=True)

class TagClass(models.Model):
    tag_name = models.Charfield(...)

    def __str__(self):
        return f"{self.tag_name}"
```
<p>And then I serialize like so:</p>
<pre class="lang-py prettyprint-override"><code># serializers.py

class ClassASerializer(serializers.ModelSerializer):
    class Meta:
        model = ClassA
        fields = "__all__"

class TagClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = TagClass
        fields = "__all__"
</code>```

So when I create a tag say "red", it has ID=1, and I link it to a ClassA object, in the ClassA's object representation it shows this :

{
    "id": 1,
    "name": "Some name",
    "tags": [
        1
    ],
}
```
<p>Instead I'd like it to display like so :</p>
<pre class="lang-json prettyprint-override"><code>{
    "id": 1,
    "name": "Some name",
    "tags": [
        "red",
    ],
}
</code>```

I've seen the StringRelatedField but it makes editing the tags field disabled (read-only).
Is there a way to proceed to have the String repr but staying editable?

Body:
I have two classes:

class ClassA(models.Model):
    name = models.Charfield(...)
    tags = models.ManyToManyField("TagClass", blank=True)

class TagClass(models.Model):
    tag_name = models.Charfield(...)

    def __str__(self):
        return f"{self.tag_name}"

And then I serialize like so:

# serializers.py

class ClassASerializer(serializers.ModelSerializer):
    class Meta:
        model = ClassA
        fields = "__all__"

class TagClassSerializer(serializers.ModelSerializer):
    class Meta:
        model = TagClass
        fields = "__all__"

So when I create a tag say "red", it has ID=1, and I link it to a ClassA object, in the ClassA's object representation it shows this :

{
    "id": 1,
    "name": "Some name",
    "tags": [
        1
    ],
}

Instead I'd like it to display like so :

{
    "id": 1,
    "name": "Some name",
    "tags": [
        "red",
    ],
}

I've seen the StringRelatedField but it makes editing the tags field disabled (read-only).
Is there a way to proceed to have the String repr but staying editable?


问:
Tailwind CSS / nativewind: overflow scroll not working?
The overflow-scroll does not seem to be working with TailWind CSS (now nativewind) / React Native. I want to be able to scroll down the tweets.

I will eventually not list the tweets like this, I'll get from backend and then map over. I'm just trying to get the functionality right first.

import React from "react";
import { View } from "react-native";
import HomeHeader from "../components/HomeHeader";
import Tweet from "../components/Tweet";

const HomeScreen = () => {
  return (
    <>
      <HomeHeader />
      <View className="max-h-screen overflow-scroll border-x">
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
      </View>
    </>
  );
};

export default HomeScreen;

```
<pre class="lang-js prettyprint-override"><code>const Tab = createBottomTabNavigator();

const TabNavigator = () => {
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    });
  }, []);

  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        headerShown: route.name === "Home" ? false : true,
        tabBarActiveTintColor: "green",
        tabBarInactiveTintColor: "gray",
      })}
    >
      <Tab.Screen name="Home" component={HomeScreen} />
    </Tab.Navigator>
  );
};

export default TabNavigator;
</code>```

Body:
The overflow-scroll does not seem to be working with TailWind CSS (now nativewind) / React Native. I want to be able to scroll down the tweets.

I will eventually not list the tweets like this, I'll get from backend and then map over. I'm just trying to get the functionality right first.

import React from "react";
import { View } from "react-native";
import HomeHeader from "../components/HomeHeader";
import Tweet from "../components/Tweet";

const HomeScreen = () => {
  return (
    <>
      <HomeHeader />
      <View className="max-h-screen overflow-scroll border-x">
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
        <Tweet />
      </View>
    </>
  );
};

export default HomeScreen;

const Tab = createBottomTabNavigator();

const TabNavigator = () => {
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    });
  }, []);

  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        headerShown: route.name === "Home" ? false : true,
        tabBarActiveTintColor: "green",
        tabBarInactiveTintColor: "gray",
      })}
    >
      <Tab.Screen name="Home" component={HomeScreen} />
    </Tab.Navigator>
  );
};

export default TabNavigator;


问:
How do I remove the block-stream error so that create-react-app will run
I am getting this error when trying to start a new project (reddit clone) on react.

npx create-react-app reddit

```<code>matt@Matthews-MacBook-Pro reddit % npx create-react-app reddit
node:internal/modules/cjs/loader:1042
  throw err;
  ^
</code>```
```<code>Error: Cannot find module 'block-stream'
Require stack:
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/pack.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/tar.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/index.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/createReactApp.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js:7:19)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/pack.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/tar.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/index.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/createReactApp.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/index.js'
  ]
}

Node.js v18.13.0
</code>```

I have uninstalled node through the terminal and also in the folders including lib and bin. I have reinstalled Node. All of the stack references 'npm' which I made sure to check was removed and reinstalled.

The current versions are:

node v18.13.0

npm 9.2.0

I found this website in a previous questions, but it relates to Bitcoin Is this needed?:

https://help.blockstream.com/hc/en-us/articles/900001610743-Install-the-Blockstream-Satellite-node-software#:%7E:text=Blockstream%20Satellite%20Kit%20Setup,-Set%20up%20a&text=Blockstream%20maintains%20a%20customized%20version,normal%20Bitcoin%20Core%20node%20does.

"Error: Cannot find module 'block-stream'"
I cannot find any files within directories relating to Block Stream.

I have another error when running "npm install create-react-app reddit"

```<code>npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.

added 42 packages, changed 1 package, and audited 91 packages in 4s

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

3 high severity vulnerabilities

To address all issues, run:
  npm audit fix

Run `npm audit` for details.
matt@Matthews-MacBook-Pro reddit % npm start
npm ERR! Missing script: "start"
npm ERR!
npm ERR! Did you mean one of these?
npm ERR!     npm star # Mark your favorite packages
npm ERR!     npm stars # View packages marked as favorites
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR!   npm run

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/matt/.npm/_logs/2023-01-08T17_48_52_057Z-debug-0.log
</code>```

Body:
I am getting this error when trying to start a new project (reddit clone) on react.

npx create-react-app reddit

matt@Matthews-MacBook-Pro reddit % npx create-react-app reddit
node:internal/modules/cjs/loader:1042
  throw err;
  ^

Error: Cannot find module 'block-stream'
Require stack:
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/pack.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/tar.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/index.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/createReactApp.js
- /Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/index.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js:7:19)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at Module.require (node:internal/modules/cjs/loader:1105:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/entry-writer.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/lib/pack.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/node_modules/tar/tar.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/tar-pack/index.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/createReactApp.js',
    '/Users/matt/.npm/_npx/c67e74de0542c87c/node_modules/create-react-app/index.js'
  ]
}

Node.js v18.13.0

I have uninstalled node through the terminal and also in the folders including lib and bin. I have reinstalled Node. All of the stack references 'npm' which I made sure to check was removed and reinstalled.

The current versions are:

node v18.13.0

npm 9.2.0

I found this website in a previous questions, but it relates to Bitcoin Is this needed?:

https://help.blockstream.com/hc/en-us/articles/900001610743-Install-the-Blockstream-Satellite-node-software#:%7E:text=Blockstream%20Satellite%20Kit%20Setup,-Set%20up%20a&text=Blockstream%20maintains%20a%20customized%20version,normal%20Bitcoin%20Core%20node%20does.

"Error: Cannot find module 'block-stream'"
I cannot find any files within directories relating to Block Stream.

I have another error when running "npm install create-react-app reddit"

npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.

added 42 packages, changed 1 package, and audited 91 packages in 4s

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

3 high severity vulnerabilities

To address all issues, run:
  npm audit fix

Run `npm audit` for details.
matt@Matthews-MacBook-Pro reddit % npm start
npm ERR! Missing script: "start"
npm ERR!
npm ERR! Did you mean one of these?
npm ERR!     npm star # Mark your favorite packages
npm ERR!     npm stars # View packages marked as favorites
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR!   npm run

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/matt/.npm/_logs/2023-01-08T17_48_52_057Z-debug-0.log


问:
Test that value contained in MutableState is updated correctly
I have a viewModel that looks like this

```<code>class PhotoViewModel(
    private val getPhotoUseCase: GetPhotoUseCase
) : ViewModel() {

    val photo: MutableState<PhotoItem?> =
        mutableStateOf(null)

    fun getPhotoDetail(photoId: Int) {
        viewModelScope.launch {
            val photo = getPhotoUseCase(photoId)
            photoDetail.value = photo
        }
    }
}
</code>```

and I am trying that the state is updated by doing as following

```<code>@Test
    fun `state is updated correctly`() = runTest {
        coEvery {
            getPhotoDetail(id = 0)
        } returns PhotoItem(
            ...
        )

        systemUnderTest.getPhotoDetail(id = 0)
        val actualState = systemUnderTest.photoDetail.value

        assertEquals(mockedPhotoItemUiModel, actualState)
    }
</code>```

But unfortunately the test fails because the objects in memory are compared, so I get

```<code>Expected :com.package.PhotoItem@3791f50e
Actual   :com.package.PhotoItem@574b7f4a
</code>```

Should I use another method for asserting the equality?
Am I using a completely wrong approach by testing mutableState like this?

I couldn't find any official resources about testing MutableState except for this SO post

Body:
I have a viewModel that looks like this

class PhotoViewModel(
    private val getPhotoUseCase: GetPhotoUseCase
) : ViewModel() {

    val photo: MutableState<PhotoItem?> =
        mutableStateOf(null)

    fun getPhotoDetail(photoId: Int) {
        viewModelScope.launch {
            val photo = getPhotoUseCase(photoId)
            photoDetail.value = photo
        }
    }
}

and I am trying that the state is updated by doing as following

@Test
    fun `state is updated correctly`() = runTest {
        coEvery {
            getPhotoDetail(id = 0)
        } returns PhotoItem(
            ...
        )

        systemUnderTest.getPhotoDetail(id = 0)
        val actualState = systemUnderTest.photoDetail.value

        assertEquals(mockedPhotoItemUiModel, actualState)
    }

But unfortunately the test fails because the objects in memory are compared, so I get

Expected :com.package.PhotoItem@3791f50e
Actual   :com.package.PhotoItem@574b7f4a

Should I use another method for asserting the equality?
Am I using a completely wrong approach by testing mutableState like this?

I couldn't find any official resources about testing MutableState except for this SO post


问:
jopendocument error in Eclipse - Unable to derive module descriptor
When executing a simple programm that aims to write a string into an ods-File, i get an error in eclipse.

Here's the error:

java.lang.module.FindException: Unable to derive module descriptor for /home/benutzer/Documents/Java/Eclipse/FNetParser/src/jOpenDocument.jar
Caused by: java.lang.module.InvalidModuleDescriptorException: JDOMAbout$Info.class found in top-level directory (unnamed package not allowed in module)

Now here's how I got there: I wrote a class that uses the jopendocument-1.5.rar library to write a string into a cell in an .ods-file. I downloaded the jar here: https://jopendocument.org/download.html (I downloaded version 1.5) and the code looks like this:

```<code>import java.io.File;
import java.io.IOException;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;

public class SpreadSheetHandler {

    public static void main() {

        SpreadSheetHandler ssh = new SpreadSheetHandler();
        ssh.writeStringToCell("L1", "Test");

    }

    public void writeStringToCell (String str_cell, String str_value) {

        File odc_WpDaten = new File("/home/benutzer/Desktop/Aktien/20230103_Aktienliste.ods");

        //odc_WpDaten.loadFrom("/home/benutzer/Desktop/Aktien/20230103_Aktienliste.ods");

        Sheet sht_WpDaten;
        try {
            sht_WpDaten = SpreadSheet.createFromFile(odc_WpDaten).getSheet("Sheet1");

sht_WpDaten.getCellAt(str_cell).setValue("str_value");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

All the programm is supposed to do is open an .ods file and write "Test" in cell L1. That's it.

I have added the jopendocument library to my project like other libraries before (Add library..., then add to build path...) I have also aligned to names of the jar file (renamed the .jar file "jopendocument.jar") and of the entry in the module-info.java file. I still get the error.

The content of module-info.java looks like this:

```<code>/**
 *
 */
/**
 * @author benutzer
 *
 */
module FNetParser {
    requires jOpenDocument;
}
</code>```

It doesn't look like a coding problem to me. More like some issue with setting this ominous "module descriptor" in eclipse. Does anyone know where i can find the "module descriptor", that is mentioned in the error message?

I the module-info.java, "jopendocument" is underlined, when i hover over it, the tooltip reads: "Name of automatic module "jopendocument" is unstable. It is derived from the module's filename.

Body:
When executing a simple programm that aims to write a string into an ods-File, i get an error in eclipse.

Here's the error:

java.lang.module.FindException: Unable to derive module descriptor for /home/benutzer/Documents/Java/Eclipse/FNetParser/src/jOpenDocument.jar
Caused by: java.lang.module.InvalidModuleDescriptorException: JDOMAbout$Info.class found in top-level directory (unnamed package not allowed in module)

Now here's how I got there: I wrote a class that uses the jopendocument-1.5.rar library to write a string into a cell in an .ods-file. I downloaded the jar here: https://jopendocument.org/download.html (I downloaded version 1.5) and the code looks like this:

import java.io.File;
import java.io.IOException;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;

public class SpreadSheetHandler {

    public static void main() {

        SpreadSheetHandler ssh = new SpreadSheetHandler();
        ssh.writeStringToCell("L1", "Test");

    }

    public void writeStringToCell (String str_cell, String str_value) {

        File odc_WpDaten = new File("/home/benutzer/Desktop/Aktien/20230103_Aktienliste.ods");

        //odc_WpDaten.loadFrom("/home/benutzer/Desktop/Aktien/20230103_Aktienliste.ods");

        Sheet sht_WpDaten;
        try {
            sht_WpDaten = SpreadSheet.createFromFile(odc_WpDaten).getSheet("Sheet1");

sht_WpDaten.getCellAt(str_cell).setValue("str_value");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

All the programm is supposed to do is open an .ods file and write "Test" in cell L1. That's it.

I have added the jopendocument library to my project like other libraries before (Add library..., then add to build path...) I have also aligned to names of the jar file (renamed the .jar file "jopendocument.jar") and of the entry in the module-info.java file. I still get the error.

The content of module-info.java looks like this:

/**
 *
 */
/**
 * @author benutzer
 *
 */
module FNetParser {
    requires jOpenDocument;
}

It doesn't look like a coding problem to me. More like some issue with setting this ominous "module descriptor" in eclipse. Does anyone know where i can find the "module descriptor", that is mentioned in the error message?

I the module-info.java, "jopendocument" is underlined, when i hover over it, the tooltip reads: "Name of automatic module "jopendocument" is unstable. It is derived from the module's filename.


问:
Neo4j Find alle Neighbor Nodes in JAVA
I'm using the embedded Neo4j with Java. I'm trying to get all neighbors of one single node.
I tried the following approach. But im not 100% is it correct ?</p>
```<code>    managementService = new DatabaseManagementServiceBuilder(database).build();
    graphDB = managementService.database(DEFAULT_DATABASE_NAME);

    try (Transaction tx = graphDB.beginTx()) {
        ResourceIterator<Node> nodelist = tx.findNodes(Labels.SINGLE_NODE, "name", "project");

        while (nodelist.hasNext()) {

            Node n1 = nodelist.next();
            String test  =(String) n1.getProperty("name");
            Iterable<Relationship> allRelationships = n1.getRelationships(Direction.OUTGOING);
</code>```

Title: Neo4j Find alle Neighbor Nodes in JAVA

Body:
I'm using the embedded Neo4j with Java. I'm trying to get all neighbors of one single node.
I tried the following approach. But im not 100% is it correct ?

    managementService = new DatabaseManagementServiceBuilder(database).build();
    graphDB = managementService.database(DEFAULT_DATABASE_NAME);

    try (Transaction tx = graphDB.beginTx()) {
        ResourceIterator<Node> nodelist = tx.findNodes(Labels.SINGLE_NODE, "name", "project");

        while (nodelist.hasNext()) {

            Node n1 = nodelist.next();
            String test  =(String) n1.getProperty("name");
            Iterable<Relationship> allRelationships = n1.getRelationships(Direction.OUTGOING);


问:
Android tv Leanback disable HeadersFragment in BrowseFragment without losing RowsFragment?
I'm new to AndroidTv and Leanback. In my app I only want to display the RowsFragment in the BrowseFragment and NOT the HeadersFragment. Android docs state that the HeadersFragment can be disabled using this code, but it also disables the RowsFragment.

```<code>    private void setupUIElements() {
        setTitle(getString(R.string.browse_title));
        setHeadersState(HEADERS_DISABLED);
}
</code>```

How can I only disable the HeadersFragment and have the RowsFragment visible?

Body:
I'm new to AndroidTv and Leanback. In my app I only want to display the RowsFragment in the BrowseFragment and NOT the HeadersFragment. Android docs state that the HeadersFragment can be disabled using this code, but it also disables the RowsFragment.

    private void setupUIElements() {
        setTitle(getString(R.string.browse_title));
        setHeadersState(HEADERS_DISABLED);
}

How can I only disable the HeadersFragment and have the RowsFragment visible?


问:
Image is not showing in pdf with JSPDF in Ionic Angular
I have implemented jsPDF with html2canva but images are not showing it is displaying empty blank spaces
Html page
the above picture is the html page and below picture is of pdf

pdf screenshot

here pictures are not showing

here is the code i am using

```<code>generatePDF() {
    const div: any = document.getElementById('content');
    const options = {
      background: 'white',
      scale: 3,
    };

    html2canvas(div, options)
      .then((canvas) => {
        var img = canvas.toDataURL('image/PNG');
        var doc = new JSPDF();

        // Add image Canvas to PDF
        const bufferX = 5;
        const bufferY = 5;
        const imgProps = (<any>doc).getImageProperties(img);
        const pdfWidth = doc.internal.pageSize.getWidth() - 2 * bufferX;
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        doc.addImage(
          img,
          'JPG',
          bufferX,
          bufferY,
          pdfWidth,
          pdfHeight,
          undefined,
          'FAST'
        );

        return doc;
      })
      .then((doc) => {
        doc.save('postres.pdf');
      });
  }
</code>```

i have tried a lot but haven't found any solution till now

Body:
I have implemented jsPDF with html2canva but images are not showing it is displaying empty blank spaces
Html page
the above picture is the html page and below picture is of pdf

pdf screenshot

here pictures are not showing

here is the code i am using

generatePDF() {
    const div: any = document.getElementById('content');
    const options = {
      background: 'white',
      scale: 3,
    };

    html2canvas(div, options)
      .then((canvas) => {
        var img = canvas.toDataURL('image/PNG');
        var doc = new JSPDF();

        // Add image Canvas to PDF
        const bufferX = 5;
        const bufferY = 5;
        const imgProps = (<any>doc).getImageProperties(img);
        const pdfWidth = doc.internal.pageSize.getWidth() - 2 * bufferX;
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        doc.addImage(
          img,
          'JPG',
          bufferX,
          bufferY,
          pdfWidth,
          pdfHeight,
          undefined,
          'FAST'
        );

        return doc;
      })
      .then((doc) => {
        doc.save('postres.pdf');
      });
  }

i have tried a lot but haven't found any solution till now


问:
Shadow when I put a background image in a Button
My problem is that when I put a Button with an image in the background, a shadow appears. This is the code for the Sound Button

```<code> <androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_atras"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:background="@drawable/atras"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</code>```

PS: When I touch any of these button, the shadow makes like an effect, contracting the shadow.

```<code>[Back Button](https://i.stack.imgur.com/upQmm.png)
[Button](https://i.stack.imgur.com/zo9RT.png)
[Sound Button](https://i.stack.imgur.com/NHtln.png)
</code>```

Button

I tried to change the style and put transparent background, nothing worked.

Body:
My problem is that when I put a Button with an image in the background, a shadow appears. This is the code for the Sound Button

 <androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn_atras"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:background="@drawable/atras"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

PS: When I touch any of these button, the shadow makes like an effect, contracting the shadow.

[Back Button](https://i.stack.imgur.com/upQmm.png)
[Button](https://i.stack.imgur.com/zo9RT.png)
[Sound Button](https://i.stack.imgur.com/NHtln.png)

Button

I tried to change the style and put transparent background, nothing worked.


问:
Deploy CNN keras model on Arduino
I wrote the below **CNN **Keras model on Google Colaboratory to Classify a set of one dimensional signals to 10 classes and its works well, however when I deploy it on Arduino, it doesn't predict any classes;

```<code>model = Sequential()
model.add(tf.keras.layers.Reshape((500, 1), input_shape=(500,),name='reshape'))
model.add(tf.keras.layers.Conv1D(filters=10,kernel_size=5,activation=tf.nn.relu, padding='same'))
model.add(tf.keras.layers.Flatten())
model.add(Dense(10, activation='softmax', name='output'))
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
</code>```

I wrote another dense model using Keras; That works well on Arduino nano BLE 33 sense, however the above CNN model gets zero as probability of all 10 classes.
Anyone can help me how to deploy a one dimensional CNN?

Title: Deploy CNN keras model on Arduino

Body:
I wrote the below **CNN **Keras model on Google Colaboratory to Classify a set of one dimensional signals to 10 classes and its works well, however when I deploy it on Arduino, it doesn't predict any classes;

model = Sequential()
model.add(tf.keras.layers.Reshape((500, 1), input_shape=(500,),name='reshape'))
model.add(tf.keras.layers.Conv1D(filters=10,kernel_size=5,activation=tf.nn.relu, padding='same'))
model.add(tf.keras.layers.Flatten())
model.add(Dense(10, activation='softmax', name='output'))
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])

I wrote another dense model using Keras; That works well on Arduino nano BLE 33 sense, however the above CNN model gets zero as probability of all 10 classes.
Anyone can help me how to deploy a one dimensional CNN?


问:
Is there a way to hook into Next.js build-time execution?
I know that Next.js does some build-time execution for SSG. Is there a way to hook into this build-time execution to run some basic code?

Let's say that these special functions are delimited with $, so:

// build-time only function
const $concat = (...args: string[]) => args.join(" ")

const x = $concat(
    "this",
    "that",
    "and the other"
)
```
<p>would build to the following JS:</p>
<pre class="lang-js prettyprint-override"><code>const x = "this that and the other"
</code>```

This would be super useful for tailwind class name manipulations.

Body:
I know that Next.js does some build-time execution for SSG. Is there a way to hook into this build-time execution to run some basic code?

Let's say that these special functions are delimited with $, so:

// build-time only function
const $concat = (...args: string[]) => args.join(" ")

const x = $concat(
    "this",
    "that",
    "and the other"
)

would build to the following JS:

const x = "this that and the other"

This would be super useful for tailwind class name manipulations.


问:
having problem by sorting duplicates in given array in n log n
so i am trying to make this task :
make a function that recieves an int array and size int n,the function checks for any duplicates and moves the duplicates to the end of the given array(numbers can be between -n to n),and return the number of unique elements.
example:

Array before moving duplications:
7 1 3 7 1 6 5
Array after movingduplications:
7 1 3 6 5 7 1
The number of different elements in array: 5.

so i managed to make this in O(n):

```<code>int moveDuplicatesV1(int* arr, int n) {
    int* aux = (int*)calloc((2 * n) + 1, sizeof(int));
    assert(aux);
    int uniq = 0;
    int i;
    int last = -1;
    for (i = 0; i < n; i++) {
        aux[arr[i] + n]++;
        if (aux[arr[i] + n] == 1)
        {
            if (last != -1)
            {
                swap(arr + i, arr + last);
                i = last;
            }
            last = i + 1;
        }
        else
            uniq--;
        if (aux[arr[i]] != 1)
            uniq++;
    }
    return uniq;
}
</code>```

and now i am trying to make this code in nlogn this is what i did so far:

```<code>int moveDuplicatesV2(int* arr, int n) {
int i = 0, j = 0, k = 0, uniq = 0, dubs = 0;;
int* temp = (int*)calloc(n,sizeof(int));
assert(temp);
for (j = 0; j < n; j++) {
    temp[j]=arr[j];
}
merge_sort(temp, 0, n - 1);
for (i = 0; i < n; i++) {
    int left = bin_search(temp[i], temp, n);
    int right = bin_search_last(temp[i], temp, n);
    if (left == -1 || right == -1) {
        uniq++;
    }
    else {
        dubs = bin_search_last(temp[i], arr, n);
        swap(dubs, arr[n-1]);
        uniq++;
    }

}
    return uniq;
}
</code>```

but something wrong i dont get the output like its should be.
if someone can explain and help it will be appreciated thanks.

here the functions that i used:

```<code>        int bin_search(int key, int* a, int n)
    {
        int* low, * high, * mid;
        low = a;
        high = a + n - 1;
        while (low <= high)
        {
            mid = low + (high - low) / 2;
            if (key == *mid)
                return 1;
            else if (key < *mid)
                high = mid - 1;
            else
                low = mid + 1;
        }
        return 0;
    }

    int bin_search_last(int key, int* a, int n)
    {
        int low, high, mid;
        low = 0;
        high = n - 1;
        while (low <= high)
        {
            mid = (low + high) / 2;
            if (key < a[mid])
                high = mid - 1;
            else
                if (key > a[mid])
                    low = mid + 1;
                else
                    if ((low == high) || (a[mid + 1] > key))
                        return mid;
                    else
                        low = mid + 1;
        }
        return -1;
    }
void swap(int* v, int* u)
{
    int temp;
    temp = *v;
    *v = *u;
    *u = temp;
}

void merge(int* a, int p, int q, int r)
{
    int i = p, j = q + 1, k = 0;
    int* temp = (int*)malloc((r - p + 1) * sizeof(int));
    assert(temp);
    while ((i <= q) && (j <= r))
        if (a[i] < a[j])
            temp[k++] = a[i++];
        else
            temp[k++] = a[j++];
    while (j <= r)
        temp[k++] = a[j++];
    while (i <= q)
        temp[k++] = a[i++];
    for (i = p, k = 0; i <= r; i++, k++)
        a[i] = temp[k];
    free(temp);
}

void merge_sort(int* a, int first, int last)
{
    int middle;
    if (first < last) {
        middle = (first + last) / 2;
        merge_sort(a, first, middle);
        merge_sort(a, middle + 1, last);
        merge(a, first, middle, last);
    }
}
</code>```

Body:
so i am trying to make this task :
make a function that recieves an int array and size int n,the function checks for any duplicates and moves the duplicates to the end of the given array(numbers can be between -n to n),and return the number of unique elements.
example:

Array before moving duplications:
7 1 3 7 1 6 5
Array after movingduplications:
7 1 3 6 5 7 1
The number of different elements in array: 5.

so i managed to make this in O(n):

int moveDuplicatesV1(int* arr, int n) {
    int* aux = (int*)calloc((2 * n) + 1, sizeof(int));
    assert(aux);
    int uniq = 0;
    int i;
    int last = -1;
    for (i = 0; i < n; i++) {
        aux[arr[i] + n]++;
        if (aux[arr[i] + n] == 1)
        {
            if (last != -1)
            {
                swap(arr + i, arr + last);
                i = last;
            }
            last = i + 1;
        }
        else
            uniq--;
        if (aux[arr[i]] != 1)
            uniq++;
    }
    return uniq;
}

and now i am trying to make this code in nlogn this is what i did so far:

int moveDuplicatesV2(int* arr, int n) {
int i = 0, j = 0, k = 0, uniq = 0, dubs = 0;;
int* temp = (int*)calloc(n,sizeof(int));
assert(temp);
for (j = 0; j < n; j++) {
    temp[j]=arr[j];
}
merge_sort(temp, 0, n - 1);
for (i = 0; i < n; i++) {
    int left = bin_search(temp[i], temp, n);
    int right = bin_search_last(temp[i], temp, n);
    if (left == -1 || right == -1) {
        uniq++;
    }
    else {
        dubs = bin_search_last(temp[i], arr, n);
        swap(dubs, arr[n-1]);
        uniq++;
    }

}
    return uniq;
}

but something wrong i dont get the output like its should be.
if someone can explain and help it will be appreciated thanks.

here the functions that i used:

        int bin_search(int key, int* a, int n)
    {
        int* low, * high, * mid;
        low = a;
        high = a + n - 1;
        while (low <= high)
        {
            mid = low + (high - low) / 2;
            if (key == *mid)
                return 1;
            else if (key < *mid)
                high = mid - 1;
            else
                low = mid + 1;
        }
        return 0;
    }

    int bin_search_last(int key, int* a, int n)
    {
        int low, high, mid;
        low = 0;
        high = n - 1;
        while (low <= high)
        {
            mid = (low + high) / 2;
            if (key  a[mid])
                    low = mid + 1;
                else
                    if ((low == high) || (a[mid + 1] > key))
                        return mid;
                    else
                        low = mid + 1;
        }
        return -1;
    }
void swap(int* v, int* u)
{
    int temp;
    temp = *v;
    *v = *u;
    *u = temp;
}

void merge(int* a, int p, int q, int r)
{
    int i = p, j = q + 1, k = 0;
    int* temp = (int*)malloc((r - p + 1) * sizeof(int));
    assert(temp);
    while ((i <= q) && (j <= r))
        if (a[i] < a[j])
            temp[k++] = a[i++];
        else
            temp[k++] = a[j++];
    while (j <= r)
        temp[k++] = a[j++];
    while (i <= q)
        temp[k++] = a[i++];
    for (i = p, k = 0; i <= r; i++, k++)
        a[i] = temp[k];
    free(temp);
}

void merge_sort(int* a, int first, int last)
{
    int middle;
    if (first < last) {
        middle = (first + last) / 2;
        merge_sort(a, first, middle);
        merge_sort(a, middle + 1, last);
        merge(a, first, middle, last);
    }
}


问:
Handling a system menu item of another application
I created a small application that adds an item to the system menu of all windows, and handles clicking on it with a hook (WH_CALLWNDPROC).

The code works when the window receives WM_SYSCOMMAND messages with the existing items (minimize, maximize, etc.) but does not capture clicks on my custom item.

The problem is, apparently, that I'm not getting the correct ID of the item I added, but I don't know why.

How will I do this?

Here is the code to add the item (works):

const
  SC_MYITEM = $020;
  MYITEM_STRING = 'My Item';
...

function AddMyMenuItem(hWnd: HWND): Boolean;
var
  WndMenu: HMENU;
begin
  Result := False;
  if IsWindowVisible(hWnd) then
  begin
    WndMenu := GetSystemMenu(hWnd, False);
    if WndMenu <> 0 then
      Result := AppendMenu(WndMenu, MF_STRING or MF_ENABLED, SC_MYITEM, PChar(MYITEM_STRING));
  end;
end;

```
<p>And this is the code in the dll file that the hook runs:</p>
<pre class="lang-pascal prettyprint-override"><code>const
  SC_MYITEM = $020;

function CallWndProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
  Window: HWND;
begin
  Result := CallNextHookEx(0, nCode, wParam, lParam);
  if nCode < HC_ACTION then Exit;

  if (PCWPStruct(lParam)^.message = WM_SYSCOMMAND) and (PCWPStruct(lParam)^.wParam = SC_MYITEM) then
  begin
    Window := PCWPStruct(lParam)^.hwnd;
    //The procedure that processes the window...
  end;
end;
</code>```

As mentioned, if I check this line PCWPStruct(lParam)^.wParam = SC_MAXIMIZE I will get the correct result when maximize is pressed, and the code will run.

Body:
I created a small application that adds an item to the system menu of all windows, and handles clicking on it with a hook (WH_CALLWNDPROC).

The code works when the window receives WM_SYSCOMMAND messages with the existing items (minimize, maximize, etc.) but does not capture clicks on my custom item.

The problem is, apparently, that I'm not getting the correct ID of the item I added, but I don't know why.

How will I do this?

Here is the code to add the item (works):

const
  SC_MYITEM = $020;
  MYITEM_STRING = 'My Item';
...

function AddMyMenuItem(hWnd: HWND): Boolean;
var
  WndMenu: HMENU;
begin
  Result := False;
  if IsWindowVisible(hWnd) then
  begin
    WndMenu := GetSystemMenu(hWnd, False);
    if WndMenu <> 0 then
      Result := AppendMenu(WndMenu, MF_STRING or MF_ENABLED, SC_MYITEM, PChar(MYITEM_STRING));
  end;
end;

And this is the code in the dll file that the hook runs:

const
  SC_MYITEM = $020;

function CallWndProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
  Window: HWND;
begin
  Result := CallNextHookEx(0, nCode, wParam, lParam);
  if nCode < HC_ACTION then Exit;

  if (PCWPStruct(lParam)^.message = WM_SYSCOMMAND) and (PCWPStruct(lParam)^.wParam = SC_MYITEM) then
  begin
    Window := PCWPStruct(lParam)^.hwnd;
    //The procedure that processes the window...
  end;
end;

As mentioned, if I check this line PCWPStruct(lParam)^.wParam = SC_MAXIMIZE I will get the correct result when maximize is pressed, and the code will run.


问:
Vuex cant read localstorage on page refresh
I store a user token in a vuex state.
When the page of my nuxt app is refreshed, i want this token to persist, to check for eligibility to visit user-related routes.

From a global middleware, i just dispatch an action like so

```<code> context.store.dispatch('authModule/resetToken')
</code>```

triggering the vuex action

```<code>resetToken(context) {
    context.commit('RE_AUTH')
  },
</code>```

which triggers the following mutation

```<code>RE_AUTH: (state, token) => {

    if (!state.token && process.client && localStorage.getItem('auth-token')) {
      token = localStorage.getItem('auth-token')
      state.token = token
    }
  },
</code>```

When i reload the page, the mutation is triggered, but the if condition does not resolve true and execute the code to reappend the token, even though there is the correct named token in localhost.

When i however then navigate to another page, the code does execute and reappends the token. I dont understand why, because global middleware should be executed first in lifecycle and vuex should have access to localstorage

Body:
I store a user token in a vuex state.
When the page of my nuxt app is refreshed, i want this token to persist, to check for eligibility to visit user-related routes.

From a global middleware, i just dispatch an action like so

 context.store.dispatch('authModule/resetToken')

triggering the vuex action

resetToken(context) {
    context.commit('RE_AUTH')
  },

which triggers the following mutation

RE_AUTH: (state, token) => {

    if (!state.token && process.client && localStorage.getItem('auth-token')) {
      token = localStorage.getItem('auth-token')
      state.token = token
    }
  },

When i reload the page, the mutation is triggered, but the if condition does not resolve true and execute the code to reappend the token, even though there is the correct named token in localhost.

When i however then navigate to another page, the code does execute and reappends the token. I dont understand why, because global middleware should be executed first in lifecycle and vuex should have access to localstorage


问:
How do I put more than 2GB file into byte array in C#?
I have an algorithm that finds and replaces some hex values of a bin file. But I can't find out how to bypass that 2 GB limit for files that I load into the byte array.

It works just fine when the file size is smaller than 2 GB, but when it is larger, I get an exception

System.IO.IOException: The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size

So, I store my values in:

```<code>byte[] find = Array.Empty<byte>(); // assume there is some hex
byte[] replace = Array.Empty<byte>(); // assume there is some hex
byte[] bytes = File.ReadAllBytes("example.bin");
</code>```

Where find and replace are hex values to be found and replaced, when bytes is array of bytes for my file. Then, to find and replace those values I use the following algorithm:

```<code>foreach (int index in PatternAt(bytes, find))
{
    for (int i = index, replaceIndex = 0; i < bytes.Length && replaceIndex < replace.Length; i++, replaceIndex++)
    {
        bytes[i] = replace[replaceIndex];
    }

    File.WriteAllBytes("example.bin", bytes);

    Console.WriteLine("Pattern found at offset {0} and replaced.", index);
    continue;
}
</code>```

And the code for PatternAt looks like this:

```<code>private static IEnumerable<int> PatternAt(byte[] source, byte[] pattern)
{
        for (int i = 0; i < source.Length; i++)
        {
            if (source.Skip(i).Take(pattern.Length).SequenceEqual(pattern))
            {
                yield return i;
            }
        }
}
</code>```

Body:
I have an algorithm that finds and replaces some hex values of a bin file. But I can't find out how to bypass that 2 GB limit for files that I load into the byte array.

It works just fine when the file size is smaller than 2 GB, but when it is larger, I get an exception

System.IO.IOException: The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size

So, I store my values in:

byte[] find = Array.Empty<byte>(); // assume there is some hex
byte[] replace = Array.Empty<byte>(); // assume there is some hex
byte[] bytes = File.ReadAllBytes("example.bin");

Where find and replace are hex values to be found and replaced, when bytes is array of bytes for my file. Then, to find and replace those values I use the following algorithm:

foreach (int index in PatternAt(bytes, find))
{
    for (int i = index, replaceIndex = 0; i < bytes.Length && replaceIndex < replace.Length; i++, replaceIndex++)
    {
        bytes[i] = replace[replaceIndex];
    }

    File.WriteAllBytes("example.bin", bytes);

    Console.WriteLine("Pattern found at offset {0} and replaced.", index);
    continue;
}

And the code for PatternAt looks like this:

private static IEnumerable<int> PatternAt(byte[] source, byte[] pattern)
{
        for (int i = 0; i < source.Length; i++)
        {
            if (source.Skip(i).Take(pattern.Length).SequenceEqual(pattern))
            {
                yield return i;
            }
        }
}