问:
Using Fluster to cluster a list of firebase documents
[I have a list of location documents in Firebase and Algolia that are displayed on my Flutter app's google map page as markers. There are over 50 location documents currently in my Firebase, but at a time only 20 markers are displayed on the map no matter what. There are no limitations set anywhere, but there is a maximum of 20 markers. In order for there to be more than 20 markers, I need to implement clusters in my map page but I am not able to. With this code being the code for my map page, how would I implement clusters?

```<code>import '../auth/auth_util.dart';
import '../backend/backend.dart';
import '../flutter_flow/flutter_flow_ad_banner.dart';
import '../flutter_flow/flutter_flow_google_map.dart';
import '../flutter_flow/flutter_flow_theme.dart';
import '../flutter_flow/flutter_flow_util.dart';
import '../flutter_flow/flutter_flow_widgets.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';

class FindCourtWidget extends StatefulWidget {
  const FindCourtWidget({
    Key? key,
    this.searchTerm,
  }) : super(key: key);

  final String? searchTerm;

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

class _FindCourtWidgetState extends State<FindCourtWidget> {
  LatLng? currentUserLocationValue;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  LatLng? googleMapsCenter;
  final googleMapsController = Completer<GoogleMapController>();

  @override
  void initState() {
    super.initState();
    // On page load action.
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      currentUserLocationValue =
          await getCurrentUserLocation(defaultLocation: LatLng(0.0, 0.0));

      final usersUpdateData = createUsersRecordData(
        latLngLocation: currentUserLocationValue,
      );
      await currentUserReference!.update(usersUpdateData);
    });

    getCurrentUserLocation(defaultLocation: LatLng(0.0, 0.0), cached: true)
        .then((loc) => setState(() => currentUserLocationValue = loc));
    WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    if (currentUserLocationValue == null) {
      return Container(
        color: FlutterFlowTheme.of(context).primaryBackground,
        child: Center(
          child: SizedBox(
            width: 50,
            height: 50,
            child: SpinKitRotatingCircle(
              color: Color(0xFFF25454),
              size: 50,
            ),
          ),
        ),
      );
    }

    return FutureBuilder<List<CourtsRecord>>(
      future: CourtsRecord.search(
        term: '*',
        location: getCurrentUserLocation(
            defaultLocation: LatLng(37.4298229, -122.1735655)),
      ),
      builder: (context, snapshot) {
        // Customize what your widget looks like when it's loading.
        if (!snapshot.hasData) {
          return Center(
            child: SizedBox(
              width: 50,
              height: 50,
              child: SpinKitRotatingCircle(
                color: Color(0xFFF25454),
                size: 50,
              ),
            ),
          );
        }
        List<CourtsRecord> findCourtCourtsRecordList = snapshot.data!;
        return Title(
            title: 'findCourt',
            color: FlutterFlowTheme.of(context).primaryColor,
            child: Scaffold(
              key: scaffoldKey,
              resizeToAvoidBottomInset: false,
              body: Stack(
                children: [
                  Stack(
                    children: [
                      Stack(
                        alignment: AlignmentDirectional(0, 0),
                        children: [
                          Align(
                            alignment: AlignmentDirectional(0, 0),
                            child: FlutterFlowGoogleMap(
                              controller: googleMapsController,
                              onCameraIdle: (latLng) =>
                                  setState(() => googleMapsCenter = latLng),
                              initialLocation: googleMapsCenter ??=
                                  currentUserLocationValue!,
                              markers: findCourtCourtsRecordList
                                  .map(
                                    (findCourtCourtsRecord) =>
                                        FlutterFlowMarker(
                                      findCourtCourtsRecord.reference.path,
                                      findCourtCourtsRecord.location!,
                                      () async {
                                        context.pushNamed(
                                          'courtDetailsCopy',
                                          params: {
                                            'court2': serializeParam(
                                              findCourtCourtsRecord,
                                              ParamType.Document,
                                            ),
                                          }.withoutNulls,
                                          extra: <String, dynamic>{
                                            'court2': findCourtCourtsRecord,
                                          },
                                        );
                                      },
                                    ),
                                  )
                                  .toList(),
                              markerColor: GoogleMarkerColor.red,
                              mapType: MapType.normal,
                              style: GoogleMapStyle.standard,
                              initialZoom: 14,
                              allowInteraction: true,
                              allowZoom: true,
                              showZoomControls: false,
                              showLocation: true,
                              showCompass: false,
                              showMapToolbar: false,
                              showTraffic: false,
                              centerMapOnMarkerTap: true,
                            ),
                          ),
                        ],
                      ),
                      Align(
                        alignment: AlignmentDirectional(0, 0.8),
                        child: FFButtonWidget(
                          onPressed: () async {
                            context.pushNamed(
                              'addCourt',
                              extra: <String, dynamic>{
                                kTransitionInfoKey: TransitionInfo(
                                  hasTransition: true,
                                  transitionType:
                                      PageTransitionType.bottomToTop,
                                ),
                              },
                            );
                          },
                          text: 'Create Location',
                          icon: Icon(
                            Icons.add_circle,
                            color: FlutterFlowTheme.of(context).white,
                            size: 30,
                          ),
                          options: FFButtonOptions(
                            width: 200,
                            height: 60,
                            color: FlutterFlowTheme.of(context).primaryColor,
                            textStyle:
                                FlutterFlowTheme.of(context).subtitle2.override(
                                      fontFamily: 'Overpass',
                                      color: FlutterFlowTheme.of(context).white,
                                      fontSize: 18,
                                    ),
                            borderSide: BorderSide(
                              color: Colors.transparent,
                              width: 1,
                            ),
                            borderRadius: BorderRadius.circular(50),
                          ),
                        ),
                      ),
                      Align(
                        alignment: AlignmentDirectional(-1, -1),
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          height: 262,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                FlutterFlowTheme.of(context).white,
                                Color(0x00FFFFFF)
                              ],
                              stops: [0, 1],
                              begin: AlignmentDirectional(0, -1),
                              end: AlignmentDirectional(0, 1),
                            ),
                          ),
                          alignment: AlignmentDirectional(0, 0),
                          child: Padding(
                            padding:
                                EdgeInsetsDirectional.fromSTEB(0, 20, 0, 0),
                            child: Column(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Align(
                                  alignment: AlignmentDirectional(0, 0),
                                  child: Padding(
                                    padding: EdgeInsetsDirectional.fromSTEB(
                                        30, 30, 30, 0),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Align(
                                          alignment: AlignmentDirectional(
                                              -0.68, -0.75),
                                          child: Text(
                                            'Hello ',
                                            textAlign: TextAlign.start,
                                            style: FlutterFlowTheme.of(context)
                                                .title2
                                                .override(
                                                  fontFamily: 'Overpass',
                                                  fontSize: 30,
                                                ),
                                          ),
                                        ),
                                        Align(
                                          alignment:
                                              AlignmentDirectional(0.63, -0.75),
                                          child: AuthUserStreamWidget(
                                            builder: (context) => Text(
                                              currentUserDisplayName
                                                  .maybeHandleOverflow(
                                                maxChars: 13,
                                                replacement: '…',
                                              ),
                                              textAlign: TextAlign.start,
                                              style:
                                                  FlutterFlowTheme.of(context)
                                                      .title2
                                                      .override(
                                                        fontFamily: 'Overpass',
                                                        fontSize: 30,
                                                      ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Row(
                                  mainAxisSize: MainAxisSize.max,
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: [
                                    Align(
                                      alignment:
                                          AlignmentDirectional(-0.05, -0.85),
                                      child: Text(
                                        'Find a great sport near you in 2 minutes',
                                        style: FlutterFlowTheme.of(context)
                                            .bodyText1
                                            .override(
                                              fontFamily: 'Overpass',
                                              color: Color(0xFF504848),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w300,
                                            ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      Align(
                        alignment: AlignmentDirectional(0, 1),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Align(
                              alignment: AlignmentDirectional(0, 1),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Expanded(
                                    child: Align(
                                      alignment: AlignmentDirectional(0, 1),
                                      child: FlutterFlowAdBanner(
                                        width:
                                            MediaQuery.of(context).size.width,
                                        height: 50,
                                        showsTestAd: true,
                                        iOSAdUnitID:
                                            'ca-app-pub-4806655917667448/9288549735',
                                        androidAdUnitID:
                                            'ca-app-pub-4806655917667448/4144034269',
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ));
      },
    );
  }
}

</code>```

I have tried using the Fluster package to implement clusters but my current knowledge in flutter/dart is not allowing me to go further in my implementation.

Body:
[I have a list of location documents in Firebase and Algolia that are displayed on my Flutter app's google map page as markers. There are over 50 location documents currently in my Firebase, but at a time only 20 markers are displayed on the map no matter what. There are no limitations set anywhere, but there is a maximum of 20 markers. In order for there to be more than 20 markers, I need to implement clusters in my map page but I am not able to. With this code being the code for my map page, how would I implement clusters?

import '../auth/auth_util.dart';
import '../backend/backend.dart';
import '../flutter_flow/flutter_flow_ad_banner.dart';
import '../flutter_flow/flutter_flow_google_map.dart';
import '../flutter_flow/flutter_flow_theme.dart';
import '../flutter_flow/flutter_flow_util.dart';
import '../flutter_flow/flutter_flow_widgets.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';

class FindCourtWidget extends StatefulWidget {
  const FindCourtWidget({
    Key? key,
    this.searchTerm,
  }) : super(key: key);

  final String? searchTerm;

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

class _FindCourtWidgetState extends State<FindCourtWidget> {
  LatLng? currentUserLocationValue;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  LatLng? googleMapsCenter;
  final googleMapsController = Completer<GoogleMapController>();

  @override
  void initState() {
    super.initState();
    // On page load action.
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      currentUserLocationValue =
          await getCurrentUserLocation(defaultLocation: LatLng(0.0, 0.0));

      final usersUpdateData = createUsersRecordData(
        latLngLocation: currentUserLocationValue,
      );
      await currentUserReference!.update(usersUpdateData);
    });

    getCurrentUserLocation(defaultLocation: LatLng(0.0, 0.0), cached: true)
        .then((loc) => setState(() => currentUserLocationValue = loc));
    WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    if (currentUserLocationValue == null) {
      return Container(
        color: FlutterFlowTheme.of(context).primaryBackground,
        child: Center(
          child: SizedBox(
            width: 50,
            height: 50,
            child: SpinKitRotatingCircle(
              color: Color(0xFFF25454),
              size: 50,
            ),
          ),
        ),
      );
    }

    return FutureBuilder<List<CourtsRecord>>(
      future: CourtsRecord.search(
        term: '*',
        location: getCurrentUserLocation(
            defaultLocation: LatLng(37.4298229, -122.1735655)),
      ),
      builder: (context, snapshot) {
        // Customize what your widget looks like when it's loading.
        if (!snapshot.hasData) {
          return Center(
            child: SizedBox(
              width: 50,
              height: 50,
              child: SpinKitRotatingCircle(
                color: Color(0xFFF25454),
                size: 50,
              ),
            ),
          );
        }
        List<CourtsRecord> findCourtCourtsRecordList = snapshot.data!;
        return Title(
            title: 'findCourt',
            color: FlutterFlowTheme.of(context).primaryColor,
            child: Scaffold(
              key: scaffoldKey,
              resizeToAvoidBottomInset: false,
              body: Stack(
                children: [
                  Stack(
                    children: [
                      Stack(
                        alignment: AlignmentDirectional(0, 0),
                        children: [
                          Align(
                            alignment: AlignmentDirectional(0, 0),
                            child: FlutterFlowGoogleMap(
                              controller: googleMapsController,
                              onCameraIdle: (latLng) =>
                                  setState(() => googleMapsCenter = latLng),
                              initialLocation: googleMapsCenter ??=
                                  currentUserLocationValue!,
                              markers: findCourtCourtsRecordList
                                  .map(
                                    (findCourtCourtsRecord) =>
                                        FlutterFlowMarker(
                                      findCourtCourtsRecord.reference.path,
                                      findCourtCourtsRecord.location!,
                                      () async {
                                        context.pushNamed(
                                          'courtDetailsCopy',
                                          params: {
                                            'court2': serializeParam(
                                              findCourtCourtsRecord,
                                              ParamType.Document,
                                            ),
                                          }.withoutNulls,
                                          extra: <String, dynamic>{
                                            'court2': findCourtCourtsRecord,
                                          },
                                        );
                                      },
                                    ),
                                  )
                                  .toList(),
                              markerColor: GoogleMarkerColor.red,
                              mapType: MapType.normal,
                              style: GoogleMapStyle.standard,
                              initialZoom: 14,
                              allowInteraction: true,
                              allowZoom: true,
                              showZoomControls: false,
                              showLocation: true,
                              showCompass: false,
                              showMapToolbar: false,
                              showTraffic: false,
                              centerMapOnMarkerTap: true,
                            ),
                          ),
                        ],
                      ),
                      Align(
                        alignment: AlignmentDirectional(0, 0.8),
                        child: FFButtonWidget(
                          onPressed: () async {
                            context.pushNamed(
                              'addCourt',
                              extra: <String, dynamic>{
                                kTransitionInfoKey: TransitionInfo(
                                  hasTransition: true,
                                  transitionType:
                                      PageTransitionType.bottomToTop,
                                ),
                              },
                            );
                          },
                          text: 'Create Location',
                          icon: Icon(
                            Icons.add_circle,
                            color: FlutterFlowTheme.of(context).white,
                            size: 30,
                          ),
                          options: FFButtonOptions(
                            width: 200,
                            height: 60,
                            color: FlutterFlowTheme.of(context).primaryColor,
                            textStyle:
                                FlutterFlowTheme.of(context).subtitle2.override(
                                      fontFamily: 'Overpass',
                                      color: FlutterFlowTheme.of(context).white,
                                      fontSize: 18,
                                    ),
                            borderSide: BorderSide(
                              color: Colors.transparent,
                              width: 1,
                            ),
                            borderRadius: BorderRadius.circular(50),
                          ),
                        ),
                      ),
                      Align(
                        alignment: AlignmentDirectional(-1, -1),
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          height: 262,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                FlutterFlowTheme.of(context).white,
                                Color(0x00FFFFFF)
                              ],
                              stops: [0, 1],
                              begin: AlignmentDirectional(0, -1),
                              end: AlignmentDirectional(0, 1),
                            ),
                          ),
                          alignment: AlignmentDirectional(0, 0),
                          child: Padding(
                            padding:
                                EdgeInsetsDirectional.fromSTEB(0, 20, 0, 0),
                            child: Column(
                              mainAxisSize: MainAxisSize.max,
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Align(
                                  alignment: AlignmentDirectional(0, 0),
                                  child: Padding(
                                    padding: EdgeInsetsDirectional.fromSTEB(
                                        30, 30, 30, 0),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Align(
                                          alignment: AlignmentDirectional(
                                              -0.68, -0.75),
                                          child: Text(
                                            'Hello ',
                                            textAlign: TextAlign.start,
                                            style: FlutterFlowTheme.of(context)
                                                .title2
                                                .override(
                                                  fontFamily: 'Overpass',
                                                  fontSize: 30,
                                                ),
                                          ),
                                        ),
                                        Align(
                                          alignment:
                                              AlignmentDirectional(0.63, -0.75),
                                          child: AuthUserStreamWidget(
                                            builder: (context) => Text(
                                              currentUserDisplayName
                                                  .maybeHandleOverflow(
                                                maxChars: 13,
                                                replacement: '…',
                                              ),
                                              textAlign: TextAlign.start,
                                              style:
                                                  FlutterFlowTheme.of(context)
                                                      .title2
                                                      .override(
                                                        fontFamily: 'Overpass',
                                                        fontSize: 30,
                                                      ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Row(
                                  mainAxisSize: MainAxisSize.max,
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: [
                                    Align(
                                      alignment:
                                          AlignmentDirectional(-0.05, -0.85),
                                      child: Text(
                                        'Find a great sport near you in 2 minutes',
                                        style: FlutterFlowTheme.of(context)
                                            .bodyText1
                                            .override(
                                              fontFamily: 'Overpass',
                                              color: Color(0xFF504848),
                                              fontSize: 16,
                                              fontWeight: FontWeight.w300,
                                            ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      Align(
                        alignment: AlignmentDirectional(0, 1),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Align(
                              alignment: AlignmentDirectional(0, 1),
                              child: Row(
                                mainAxisSize: MainAxisSize.max,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Expanded(
                                    child: Align(
                                      alignment: AlignmentDirectional(0, 1),
                                      child: FlutterFlowAdBanner(
                                        width:
                                            MediaQuery.of(context).size.width,
                                        height: 50,
                                        showsTestAd: true,
                                        iOSAdUnitID:
                                            'ca-app-pub-4806655917667448/9288549735',
                                        androidAdUnitID:
                                            'ca-app-pub-4806655917667448/4144034269',
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ));
      },
    );
  }
}

I have tried using the Fluster package to implement clusters but my current knowledge in flutter/dart is not allowing me to go further in my implementation.


来源: stackexchange

问:
How can I define collapsible regions?
Intellisense automatically adds these little '+' / '-' symbols in the editor that allow me to show/hide a section of code. I'm having trouble ascertaining the logical rules it uses to define these sections. I would like to add them to certain parts of my script, but I don't know how they get added. Anyone know if there is a way to manually add these?

ContentLicense: CC BY-SA 4.0

Title: How can I define collapsible regions?


问:
what is migrations in SQL and how to use in Node.js + postgreSQL?
what is migrations in databases? is like a git versioning?

and how can i use them in Node.js + postgreSQL using SQL (not using typeORMs please).

Here is an example of how to create a basic CRUD using Node.js and PostgreSQL without using TypeORM.

```<code>const express = require('express');
const { Pool } = require('pg');

const app = express();
const port = 3000;

// Crie uma pool de conexão com o banco de dados
const pool = new Pool({
  user: 'seu_usuario',
  host: 'localhost',
  database: 'sua_database',
  password: 'sua_senha',
  port: 5432,
});

// Crie uma rota para adicionar um novo usuário
app.post('/users', (req, res) => {
  const { name, email } = req.body;

  pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
    if (error) {
      throw error;
    }
    res.status(201).send(`User added with ID: ${results.insertId}`);
  });
});

// Crie uma rota para excluir um usuário existente
app.delete('/users/:id', (req, res) => {
  const id = parseInt(req.params.id);

  pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
    if (error) {
      throw error;
    }
    res.status(200).send(`User deleted with ID: ${id}`);
  });
});

app.listen(port, () => {
  console.log(`App running on port ${port}.`);
});
</code>```

Body:
what is migrations in databases? is like a git versioning?

and how can i use them in Node.js + postgreSQL using SQL (not using typeORMs please).

Here is an example of how to create a basic CRUD using Node.js and PostgreSQL without using TypeORM.

const express = require('express');
const { Pool } = require('pg');

const app = express();
const port = 3000;

// Crie uma pool de conexão com o banco de dados
const pool = new Pool({
  user: 'seu_usuario',
  host: 'localhost',
  database: 'sua_database',
  password: 'sua_senha',
  port: 5432,
});

// Crie uma rota para adicionar um novo usuário
app.post('/users', (req, res) => {
  const { name, email } = req.body;

  pool.query('INSERT INTO users (name, email) VALUES ($1, $2)', [name, email], (error, results) => {
    if (error) {
      throw error;
    }
    res.status(201).send(`User added with ID: ${results.insertId}`);
  });
});

// Crie uma rota para excluir um usuário existente
app.delete('/users/:id', (req, res) => {
  const id = parseInt(req.params.id);

  pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
    if (error) {
      throw error;
    }
    res.status(200).send(`User deleted with ID: ${id}`);
  });
});

app.listen(port, () => {
  console.log(`App running on port ${port}.`);
});


问:
How to change the background of a table cell if it meets a requirement with a button

Write a program that dynamically creates a 100x100 table. Each element
in the table will have a unique number, starting at 1 and increasing
by 1.

This page will also have a button that will be "Calculate almost prime
numbers." This button will cause all the cells in the table that have
“Almost Prime” numbers to have a yellow background.

Almost prime number: it is a number that is only divisible by itself,
the unit and by a single number that is neither the unit nor itself.

Hello, I am relatively new to the world of JavaScript and I am trying to solve this JavaScript exercise and as you can see the first part is to make a 100x100 table, which I have been able to do, the problem is the second part in which I have to change the background of the cells to the "almost prime numbers"

Here I leave my code, probably many things can be improved apart from finding a solution to putting the background color of the cells, anyway thanks if you can help me.

window.addEventListener("DOMContentLoaded", main);

function main() {
  var body = document.getElementsByTagName("body")[0];

  var tabla = document.createElement("table");
  var tblBody = document.createElement("tbody");

  for (var i = 0; i < 100; i++) {

    var fila = document.createElement("tr");

    for (var j = 0; j <= 100; j++) {
      var columna = document.createElement("td");
      var numero = document.createTextNode(j + i * 100);
      columna.appendChild(numero);
      fila.appendChild(columna);
    }
    tblBody.appendChild(fila);
  }

  tabla.appendChild(tblBody);
  body.appendChild(tabla);
  tabla.setAttribute("border", "2");
}

function casiprimos() {

  let contador = 0;

  for (var i = 0; i < 100; i++) {

    for (var j = 0; j <= 100; j++) {
      let num = (j + i * 100)
      for (var z = 1; z <= num; z++) {
        let resultado = num % z;
        if (resultado == 0) {
          contador = contador + 1;
        }
      }
      if (contador == 3) {
        // num.setAttribute("style","background-color: yellow;"); ? Idk
        contador = 0;
      } else {
        contador = 0;
      }
    }
  }
}```


问:
How to create a macOS SwiftUI Droplet/App? ...with SPM?
If possible, how does one create a SwiftUI-based (not Cocoa-based) droplet app for macOS? ... and, as an extra step towards the newer Swift ecosystem, can this be done with the Swift Package Manger (SPM) instead of as an Xcode project?

An example use case, that I'm trying to figure out, is the Swift analog to the AppleScript Droplet/App which can launch multiple VLC instances.  This VLC AS Droplet/App can be also used with the Finder Get Info "Open with:" setting.

```<code>on run
    do shell script "open -n /Applications/VLC.app"
    tell application "VLC" to activate
end run

on open theFiles
    repeat with theFile in theFiles
        do shell script "open -na /Applications/VLC.app " & quote & (POSIX path of theFile) & quote
    end repeat
    tell application "VLC" to activate
end open
</code>```

The StackOverflow search "swift macos droplet" returns zero items at this time.

A general internet search ended up with "A Swift 4 ‘droplet’ scripting prototype, Dropsy" which is Cocoa based.

Body:
If possible, how does one create a SwiftUI-based (not Cocoa-based) droplet app for macOS? ... and, as an extra step towards the newer Swift ecosystem, can this be done with the Swift Package Manger (SPM) instead of as an Xcode project?

An example use case, that I'm trying to figure out, is the Swift analog to the AppleScript Droplet/App which can launch multiple VLC instances.  This VLC AS Droplet/App can be also used with the Finder Get Info "Open with:" setting.

on run
    do shell script "open -n /Applications/VLC.app"
    tell application "VLC" to activate
end run

on open theFiles
    repeat with theFile in theFiles
        do shell script "open -na /Applications/VLC.app " & quote & (POSIX path of theFile) & quote
    end repeat
    tell application "VLC" to activate
end open

The StackOverflow search "swift macos droplet" returns zero items at this time.

A general internet search ended up with "A Swift 4 ‘droplet’ scripting prototype, Dropsy" which is Cocoa based.


问:
Negative lag in cross-correlation
I recorded a signal from a microphone. The recorded signal will have some reflections from the surrounding walls. I would like to locate these reflections. To do this I will use pulse compression. Pulse compression is acquired by estimating the direct wave of the recorded signal and correlating it with the entire signal. The reflections will be very similar to the direct wave, so the pulse compression will give peaks or valleys where there might be a reflection. The problem I am having is that the correlation ends up with a negative lag, which means that the reflections have arrived before the direct wave which does not make sense. So there has to be an error someplace. Here is an image of the entire signal. My main problem (and question) is what causes this change in lag, and how can it be negative in this situation.

Here is the image of the cut-out direct wave that is windowed to go toward 0.

The correlated result

I have tested both with only the cut-out direct signal which gives the result above and with the cut-out direct wave in a zeros array of the same length as the signal, which gives a correlation peak in 0 which is also not the wanted result.
The expected result should be starting around the same time as the signal (possibly a bit before)

Here are some of the codes providing the images (there is some manual cutting of the signal)

```<code>start_index = get_first_index_above_threshold(sig, threshold) #this just gives a start index above a threshold
end_index = start_index + n_sampl #n_sampl is just a chosen value by max value before expected reflections
#direct_signal = np.zeros(len(sig)) #for zero correlation peak
#direct_signal[start_index:end_index] = sig[start_index:end_index]#for zero correlation peak
direct_signal = sig[start_index:end_index].to_numpy()
sig_copy = sig.copy()
sig_copy[:start_index] = 0
compressed = signal.correlate(sig_copy,direct_signal, mode='same')
</code>```

the signal is a 3-channel data frame
I can provide data, but usually not popular to share data links here.

Here is an image of the correlation when I use a zeros array and place the cut signal in it before correlating.

Title: Negative lag in cross-correlation

Body:
I recorded a signal from a microphone. The recorded signal will have some reflections from the surrounding walls. I would like to locate these reflections. To do this I will use pulse compression. Pulse compression is acquired by estimating the direct wave of the recorded signal and correlating it with the entire signal. The reflections will be very similar to the direct wave, so the pulse compression will give peaks or valleys where there might be a reflection. The problem I am having is that the correlation ends up with a negative lag, which means that the reflections have arrived before the direct wave which does not make sense. So there has to be an error someplace. Here is an image of the entire signal. My main problem (and question) is what causes this change in lag, and how can it be negative in this situation.

Here is the image of the cut-out direct wave that is windowed to go toward 0.

The correlated result

I have tested both with only the cut-out direct signal which gives the result above and with the cut-out direct wave in a zeros array of the same length as the signal, which gives a correlation peak in 0 which is also not the wanted result.
The expected result should be starting around the same time as the signal (possibly a bit before)

Here are some of the codes providing the images (there is some manual cutting of the signal)

start_index = get_first_index_above_threshold(sig, threshold) #this just gives a start index above a threshold
end_index = start_index + n_sampl #n_sampl is just a chosen value by max value before expected reflections
#direct_signal = np.zeros(len(sig)) #for zero correlation peak
#direct_signal[start_index:end_index] = sig[start_index:end_index]#for zero correlation peak
direct_signal = sig[start_index:end_index].to_numpy()
sig_copy = sig.copy()
sig_copy[:start_index] = 0
compressed = signal.correlate(sig_copy,direct_signal, mode='same')

the signal is a 3-channel data frame
I can provide data, but usually not popular to share data links here.

Here is an image of the correlation when I use a zeros array and place the cut signal in it before correlating.


问:
Error Expected the string but got null, and location module not found dart
[[enter image description here](enter image description here)](https://i.stack.imgur.com/ZltWy.jpg)

The Flutter firebase issue raise while login the in flutter application by firebase authentication. I try to login flutter web application but the got the error in the terminal Error :- Expected the String value ,but got null and Debug mode also try but got "Error :- Expected the String value ,but got null" and "Error Location module not find dart.sdk" above two link given of problem have look.
To fix this I have try to cart provider.dart file provide the condition of if(userDoc !=null )  instead if(userDoc ==null ) .It Work for the login but after while use the add to cart procedure it show issue addtocart procedure for product fetch form the firebase in the cartscreen.

```<code>final userCollection = FirebaseFirestore.instance.collection('users');
  Future<void> fetchCart() async {
    final User? user = authInstance.currentUser;
    final DocumentSnapshot userDoc = await userCollection.doc(user!.uid).get();

    if (userDoc != null) // Major error part
    {
      return;
    }
    final leng = userDoc.get('userCart').length;
    for (int i = 0; i < leng; i++) {
      _cartItems.putIfAbsent(
          userDoc.get('userCart')[i]['productId'],
          () => CartModel(
                id: userDoc.get('userCart')[i]['cartId'],
                productId: userDoc.get('userCart')[i]['productId'],
                quantity: userDoc.get('userCart')[i]['quantity'],
              ));
    }
    notifyListeners();
  }
</code>```

Body:
[[enter image description here](enter image description here)](https://i.stack.imgur.com/ZltWy.jpg)

The Flutter firebase issue raise while login the in flutter application by firebase authentication. I try to login flutter web application but the got the error in the terminal Error :- Expected the String value ,but got null and Debug mode also try but got "Error :- Expected the String value ,but got null" and "Error Location module not find dart.sdk" above two link given of problem have look.
To fix this I have try to cart provider.dart file provide the condition of if(userDoc !=null )  instead if(userDoc ==null ) .It Work for the login but after while use the add to cart procedure it show issue addtocart procedure for product fetch form the firebase in the cartscreen.

final userCollection = FirebaseFirestore.instance.collection('users');
  Future<void> fetchCart() async {
    final User? user = authInstance.currentUser;
    final DocumentSnapshot userDoc = await userCollection.doc(user!.uid).get();

    if (userDoc != null) // Major error part
    {
      return;
    }
    final leng = userDoc.get('userCart').length;
    for (int i = 0; i < leng; i++) {
      _cartItems.putIfAbsent(
          userDoc.get('userCart')[i]['productId'],
          () => CartModel(
                id: userDoc.get('userCart')[i]['cartId'],
                productId: userDoc.get('userCart')[i]['productId'],
                quantity: userDoc.get('userCart')[i]['quantity'],
              ));
    }
    notifyListeners();
  }


问:
Is it safe to use server socket(java) to create a webserver to host a basic webpage
I am a student and would like to webscrap a school site to get my assignments that aren't done yet. I already figured out how to webscrap the site, but I want to be able to see the information on my phone, so I used the java server socket docs to create  webserver but I don't know if it's safe to even do that. The information is not sensitive so I don't care if anyone online can see it but I am worried that I might be unwillingly setting myself up to getting hacked. I would like to know if this is stupid idea, and a better and safer alternative exist. Also if someone could give me tips on how to making if safe if that is possible.

PS. I chose to try to create a webserver instead of just buying hosting because I don't have money, so buying hosting isn't an option. thx

I have googled a lot in the past few days, including how to create a secure webserver with java etc. and also if serversockets are safe but the results are inconclusive. Most say it's better not to even attempt as security is super hard, and others say serversockts are safe.


问:
PHP / HTML File Upload Not Recognizing Screenshot Images
I am building a file upload tool for my website and am running into a strange issue. The html input is set up to accept image/png, image/jpg, image/jpeg, .pdf files and it works fine when I am using it to upload PDFs or images that came from a camera or a design software.

However, when I upload an image (png) that was a screenshot taken on my Mac, the $_FILES has a value for the name attribute, but has no values for the tmp_name, type, error, size attributes. I've tried renaming the file to see if that was the issue, and that doesn't appear to be the problem either.

This is the output I get when I run print_r($_FILES):

```<code>Array ( [fileupload] => Array ( [name] => Array ( [0] => Screen Shot 2020-12-23 at 2.10.06 PM.png ) [type] => Array ( [0] => ) [tmp_name] => Array ( [0] => ) [error] => Array ( [0] => 1 ) [size] => Array ( [0] => 0 ) ) )

Warning: mime_content_type(): Empty filename or path in pro_testupload.php on line 87
Warning: getimagesize(): Filename cannot be empty in pro_testupload.php on line 91
Warning: mime_content_type(): Empty filename or path in pro_testupload.php on line 103
</code>```

Does anyone have any idea about what is going on here? Below is my code:

HTML Code

```<code><form method="POST" action="_process/pro_testupload.php" enctype="multipart/form-data">
    <input type="file" id="fileupload" name="fileupload[]" accept="image/png, image/jpg, image/jpeg, .pdf" multiple required>
    <button class="btn waves-effect black waves-light" type="submit">Upload</button>
</form>
</code>```

PHP Code

```<code>  // -----------------------------------------------------------------
  //  FILE FORMAT CHECKING FUNCTIONS
  // -----------------------------------------------------------------

  function check_image($filename) {
    // Check mime type using PHPs own built in functions (as client side mime type is vulnerable to exploitation)
    $mime_type = mime_content_type($filename);
    $allowed_file_types = ['image/png', 'image/jpeg', 'image/jpg'];

    // Check the file is actually an image
    $check = getimagesize($filename);

    // Perform all checks
    if (in_array($mime_type, $allowed_file_types) && is_array($check) !== False) {
      return True;
    } else {
      return False;
    }
  }

  function check_pdf($filename) {
    // Check mime type using PHPs own built in functions (as client side mime type is vulnerable to exploitation)
    $mime_type = mime_content_type($filename);
    $allowed_file_types = ['application/pdf'];

    // Perform checks
    if (in_array($mime_type, $allowed_file_types)) {
      return True;
    } else {
      return False;
    }
  }

  // -----------------------------------------------------------------
  // CHECK FILES TO ENSURE THEY MEET REQUIREMENTS
  // -----------------------------------------------------------------

  if(!empty(array_filter($_FILES['fileupload']['name']))) {
    foreach ($_FILES['fileupload']['tmp_name'] as $key => $value) {
      if (!(check_image($_FILES['fileupload']['tmp_name'][$key]) || check_pdf($_FILES['fileupload']['tmp_name'][$key]))) {
        echo ("The files do not meet the uploaded file requirements");
        exit;
      }
    }
  } else {
    echo ("There were no files requested to be uploaded.");
    exit;
  }
</code>```

Body:
I am building a file upload tool for my website and am running into a strange issue. The html input is set up to accept image/png, image/jpg, image/jpeg, .pdf files and it works fine when I am using it to upload PDFs or images that came from a camera or a design software.

However, when I upload an image (png) that was a screenshot taken on my Mac, the $_FILES has a value for the name attribute, but has no values for the tmp_name, type, error, size attributes. I've tried renaming the file to see if that was the issue, and that doesn't appear to be the problem either.

This is the output I get when I run print_r($_FILES):

Array ( [fileupload] => Array ( [name] => Array ( [0] => Screen Shot 2020-12-23 at 2.10.06 PM.png ) [type] => Array ( [0] => ) [tmp_name] => Array ( [0] => ) [error] => Array ( [0] => 1 ) [size] => Array ( [0] => 0 ) ) )

Warning: mime_content_type(): Empty filename or path in pro_testupload.php on line 87
Warning: getimagesize(): Filename cannot be empty in pro_testupload.php on line 91
Warning: mime_content_type(): Empty filename or path in pro_testupload.php on line 103

Does anyone have any idea about what is going on here? Below is my code:

HTML Code

<form method="POST" action="_process/pro_testupload.php" enctype="multipart/form-data">
    <input type="file" id="fileupload" name="fileupload[]" accept="image/png, image/jpg, image/jpeg, .pdf" multiple required>
    <button class="btn waves-effect black waves-light" type="submit">Upload</button>
</form>

PHP Code

  // -----------------------------------------------------------------
  //  FILE FORMAT CHECKING FUNCTIONS
  // -----------------------------------------------------------------

  function check_image($filename) {
    // Check mime type using PHPs own built in functions (as client side mime type is vulnerable to exploitation)
    $mime_type = mime_content_type($filename);
    $allowed_file_types = ['image/png', 'image/jpeg', 'image/jpg'];

    // Check the file is actually an image
    $check = getimagesize($filename);

    // Perform all checks
    if (in_array($mime_type, $allowed_file_types) && is_array($check) !== False) {
      return True;
    } else {
      return False;
    }
  }

  function check_pdf($filename) {
    // Check mime type using PHPs own built in functions (as client side mime type is vulnerable to exploitation)
    $mime_type = mime_content_type($filename);
    $allowed_file_types = ['application/pdf'];

    // Perform checks
    if (in_array($mime_type, $allowed_file_types)) {
      return True;
    } else {
      return False;
    }
  }

  // -----------------------------------------------------------------
  // CHECK FILES TO ENSURE THEY MEET REQUIREMENTS
  // -----------------------------------------------------------------

  if(!empty(array_filter($_FILES['fileupload']['name']))) {
    foreach ($_FILES['fileupload']['tmp_name'] as $key => $value) {
      if (!(check_image($_FILES['fileupload']['tmp_name'][$key]) || check_pdf($_FILES['fileupload']['tmp_name'][$key]))) {
        echo ("The files do not meet the uploaded file requirements");
        exit;
      }
    }
  } else {
    echo ("There were no files requested to be uploaded.");
    exit;
  }


问:
How to allow X-Frame-Options in R app (server.R) to communicate with angular app using iframe and window.postmessage()
I'm new in R and I need hellp with server.R file.
I want to render in angular universal app shinyapp with iframe and then communicate with it using
window.postMessage().Both apps are using different domains.This is an error I got:

shiny-app.component.ts:41 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('index') does not match the recipient window's origin ('http://localhost:4200').

How to specify 'X-Frame-Options' in server:

server.R:

```<code>library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinyWidgets)
library(data.table)
library(jsonlite)
library(zoo)
library(mlogit)
library(ggplot2)
library(kableExtra)
library(tidyr)
library(dplyr)
library(stringi)
library(stringr)
library(gridExtra)
library(scales)
options(scipen = 999)

server <-shinyServer( function(input, output, session) {

shinyjs::runjs(
"
window.addEventListener('message', (event) => {

  console.log(event);
})
"
 )
}
)
</code>```

I'm using RStudio IDE
And in Angular I have this:

```<code> import {AfterViewInit, Component, ElementRef, Inject, OnInit, PLATFORM_ID, ViewChild} from '@angular/core';
import {CommonModule, isPlatformBrowser} from '@angular/common';
import {CrudService} from "../../../utils/crud/crud.service";

@Component({
  selector: 'app-shiny-app',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './shiny-app.component.html',
  styleUrls: ['./shiny-app.component.scss']
})
export class ShinyAppComponent implements  AfterViewInit{

constructor(
  private srvCrud: CrudService,
  @Inject(PLATFORM_ID) private platformId: any,

  ) {}

  @ViewChild('shinyFrame') shinyFrame: ElementRef | undefined;

 onFrameLoad() {
  const iframe = this.shinyFrame?.nativeElement;
   iframe?.contentWindow.postMessage({
     type: 'hello'
   }, 'http://127.0.0.1:4153');

 }

  ngAfterViewInit(): void {
    if(isPlatformBrowser(this.platformId)){
     sessionStorage.setItem('data', 'test');
      this.onFrameLoad()
    }

  }

}

</code>```

I can reach to parent(angular universal app) with 'window.top.postMeassage()' from iframe, but I need to send postMessage to child (iframe)

I tried different options with js, and R, but as I mentioned I'm new and couldn't find the solutions.
I need to send postMessage to child (iframe) from parent (angular app)

Body:
I'm new in R and I need hellp with server.R file.
I want to render in angular universal app shinyapp with iframe and then communicate with it using
window.postMessage().Both apps are using different domains.This is an error I got:

shiny-app.component.ts:41 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('index') does not match the recipient window's origin ('http://localhost:4200').

How to specify 'X-Frame-Options' in server:

server.R:

library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinyWidgets)
library(data.table)
library(jsonlite)
library(zoo)
library(mlogit)
library(ggplot2)
library(kableExtra)
library(tidyr)
library(dplyr)
library(stringi)
library(stringr)
library(gridExtra)
library(scales)
options(scipen = 999)

server <-shinyServer( function(input, output, session) {

shinyjs::runjs(
"
window.addEventListener('message', (event) => {

  console.log(event);
})
"
 )
}
)

I'm using RStudio IDE
And in Angular I have this:

 import {AfterViewInit, Component, ElementRef, Inject, OnInit, PLATFORM_ID, ViewChild} from '@angular/core';
import {CommonModule, isPlatformBrowser} from '@angular/common';
import {CrudService} from "../../../utils/crud/crud.service";

@Component({
  selector: 'app-shiny-app',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './shiny-app.component.html',
  styleUrls: ['./shiny-app.component.scss']
})
export class ShinyAppComponent implements  AfterViewInit{

constructor(
  private srvCrud: CrudService,
  @Inject(PLATFORM_ID) private platformId: any,

  ) {}

  @ViewChild('shinyFrame') shinyFrame: ElementRef | undefined;

 onFrameLoad() {
  const iframe = this.shinyFrame?.nativeElement;
   iframe?.contentWindow.postMessage({
     type: 'hello'
   }, 'http://127.0.0.1:4153');

 }

  ngAfterViewInit(): void {
    if(isPlatformBrowser(this.platformId)){
     sessionStorage.setItem('data', 'test');
      this.onFrameLoad()
    }

  }

}

I can reach to parent(angular universal app) with 'window.top.postMeassage()' from iframe, but I need to send postMessage to child (iframe)

I tried different options with js, and R, but as I mentioned I'm new and couldn't find the solutions.
I need to send postMessage to child (iframe) from parent (angular app)


问:
I got this when I tried to change the default user to Abstractuser?
```<code>┌──(venv)─(neo㉿neo)-[~/…/Software Development/DjangoReact/-Blog/backend]
└─$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blogapp, contenttypes, forumapp, sessions, token_blacklist, useraccount
Running migrations:
  Applying useraccount.0001_initial...Traceback (most recent call last):
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 22, in <module>
    main()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute
    output = self.handle(*args, **options)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle
    post_migrate_state = executor.migrate(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate
    state = self._migrate_all_forwards(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards
    state = self.apply_migration(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply
    operation.database_forwards(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards
    schema_editor.create_model(model)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 442, in create_model
    sql, params = self.table_sql(model)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 216, in table_sql
    definition, extra_params = self.column_sql(model, field)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 346, in column_sql
    field_db_params = field.db_parameters(connection=self.connection)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1183, in db_parameters
    target_db_parameters = self.target_field.db_parameters(connection)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1060, in target_field
    return self.foreign_related_fields[0]
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 747, in foreign_related_fields
    rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 734, in related_fields
    return self.resolve_related_fields()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1103, in resolve_related_fields
    related_fields = super().resolve_related_fields()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 712, in resolve_related_fields
    raise ValueError(
ValueError: Related model 'useraccount.user' cannot be resolved

┌──(venv)─(neo㉿neo)-[~/…/Software Development/DjangoReact/-Blog/backend]
└─$
</code>```

I added AUTH_USER_MODEL in setting and my new User has nothing. just a pass

Body:
┌──(venv)─(neo㉿neo)-[~/…/Software Development/DjangoReact/-Blog/backend]
└─$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blogapp, contenttypes, forumapp, sessions, token_blacklist, useraccount
Running migrations:
  Applying useraccount.0001_initial...Traceback (most recent call last):
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 22, in <module>
    main()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute
    output = self.handle(*args, **options)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle
    post_migrate_state = executor.migrate(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate
    state = self._migrate_all_forwards(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards
    state = self.apply_migration(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply
    operation.database_forwards(
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards
    schema_editor.create_model(model)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 442, in create_model
    sql, params = self.table_sql(model)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 216, in table_sql
    definition, extra_params = self.column_sql(model, field)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 346, in column_sql
    field_db_params = field.db_parameters(connection=self.connection)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1183, in db_parameters
    target_db_parameters = self.target_field.db_parameters(connection)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1060, in target_field
    return self.foreign_related_fields[0]
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 747, in foreign_related_fields
    rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 734, in related_fields
    return self.resolve_related_fields()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1103, in resolve_related_fields
    related_fields = super().resolve_related_fields()
  File "/home/neo/Documents/Software Development/DjangoReact/-Blog/backend/venv/lib/python3.10/site-packages/django/db/models/fields/related.py", line 712, in resolve_related_fields
    raise ValueError(
ValueError: Related model 'useraccount.user' cannot be resolved

┌──(venv)─(neo㉿neo)-[~/…/Software Development/DjangoReact/-Blog/backend]
└─$

I added AUTH_USER_MODEL in setting and my new User has nothing. just a pass


问:
Unable to reverse last 2 elements in the list
I'm trying to use the following query to reverse elements in a list using for loop and without built-in function but for some reason last 2 elements are not getting added. Any idea what I'm doing wrong here?

```<code>l = [5,7,9,1,8]
output = []
for i,v in enumerate(l):
  output.append(l[len(l)-1])
  l.remove(l[len(l)-1])
output
</code>```

result: [8,1,9]
expected: [8,1,9,7,5]

Body:
I'm trying to use the following query to reverse elements in a list using for loop and without built-in function but for some reason last 2 elements are not getting added. Any idea what I'm doing wrong here?

l = [5,7,9,1,8]
output = []
for i,v in enumerate(l):
  output.append(l[len(l)-1])
  l.remove(l[len(l)-1])
output

result: [8,1,9]
expected: [8,1,9,7,5]


问:
How can I find the exact coordinates of a moving element in a canvas?
I'm building a snake game with 2 snakes, so typically, when one snake touches the other, the game should restart. However, what I have right now only checks for the entire x/y line that snake 2 is on. For example, if snake 2 were to be moving to the right/horizontally (they move infinitely because the walls are only portals that return the snake to the side they started on) and snake 2 moved up, it would eventually intercept the y line that snake 1 was moving on.Even though the snake on the left(1) isn't going to directly hit the snake on the right(2), it is about to die because it is going to cross the line that snake 2 is moving on
This is how the snake was made:

```<code>var grid = 16;
var grid2 = 16;
var count = 0;
var count2= 0;

var snake2 = {
  x: 160,
  y: 160,

  dx: grid2,
  dy: 0,

  cells: [],

  maxCells: 4,

};

var apple2 = {
  x: 32,
  y: 320
};

var snake = {
  x: 160,
  y: 160,

  // snake velocity. moves one grid length every frame in either the x or y direction
  dx: grid,
  dy: 0,

  // keep track of all grids the snake body occupies
  cells: [],

  // length of the snake. grows when eating an apple
  maxCells: 4
};
//In this case the apple does not matter
var apple = {
  x: 32,
  y: 320
};

// get random whole numbers in a specific range
// @see https://stackoverflow.com/a/1527820/2124254
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

// game loop
function loop() {
  requestAnimationFrame(loop);

  // slow game loop to 15 fps instead of 60 (60/15 = 4)
  if (++count < 4) {
    return;
  }

  count = 0;
  context.clearRect(0,0,canvas.width,canvas.height);

  // move snake by it's velocity
  snake.x += snake.dx;
  snake.y += snake.dy;
  snake2.x += snake2.dx;
  snake2.y += snake2.dy;

  // wrap snake position horizontally on edge of screen
  if (snake.x < 0) {
    snake.x = canvas.width - grid;
  }
  else if (snake.x >= canvas.width) {
    snake.x = 0;
  }

  // wrap snake position vertically on edge of screen
  if (snake.y < 0) {
    snake.y = canvas.height - grid;
  }
  else if (snake.y >= canvas.height) {
    snake.y = 0;
  }

  if (snake2.x < 0) {
    snake2.x = canvas.width - grid;
  }
  else if (snake2.x >= canvas.width) {
    snake2.x = 0;
  }

  // wrap snake position vertically on edge of screen
  if (snake2.y < 0) {
    snake2.y = canvas.height - grid;
  }
  else if (snake2.y >= canvas.height) {
    snake2.y = 0;
  }

  // keep track of where snake has been. front of the array is always the head
  snake.cells.unshift({x: snake.x, y: snake.y});
  snake2.cells.unshift({x: snake2.x, y: snake2.y});

  // remove cells as we move away from them
  if (snake.cells.length > snake.maxCells) {
    snake.cells.pop();
  }
  if (snake2.cells.length > snake2.maxCells) {
    snake2.cells.pop();
  }
//Here the snake checks for collision with itself and with the 2nd snake
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y || cell.x === snake.cells[i].x && cell.y === snake2.cells[i].y)
</code>```

The beginning of the code is just to check if snake 1 crossed paths with itself/ran into itself. After the OR statement is where it checks for snake 1 intercepting snake 2.

I attempted to tweak my code so it would look for the exact coordinate the snake is moving on, like this:

```<code>if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y || cell.xy === snake.cells[i].xy && cell.xy === snake2.cells[i].xy)
</code>```

I put xy to check for both coordinates to try to create one coordinate point to look for. However, this only resulted in immediate death.
Does anyone have an idea of how to fix this? EDIT What else is needed?

Body:
I'm building a snake game with 2 snakes, so typically, when one snake touches the other, the game should restart. However, what I have right now only checks for the entire x/y line that snake 2 is on. For example, if snake 2 were to be moving to the right/horizontally (they move infinitely because the walls are only portals that return the snake to the side they started on) and snake 2 moved up, it would eventually intercept the y line that snake 1 was moving on.Even though the snake on the left(1) isn't going to directly hit the snake on the right(2), it is about to die because it is going to cross the line that snake 2 is moving on
This is how the snake was made:

var grid = 16;
var grid2 = 16;
var count = 0;
var count2= 0;

var snake2 = {
  x: 160,
  y: 160,

  dx: grid2,
  dy: 0,

  cells: [],

  maxCells: 4,

};

var apple2 = {
  x: 32,
  y: 320
};

var snake = {
  x: 160,
  y: 160,

  // snake velocity. moves one grid length every frame in either the x or y direction
  dx: grid,
  dy: 0,

  // keep track of all grids the snake body occupies
  cells: [],

  // length of the snake. grows when eating an apple
  maxCells: 4
};
//In this case the apple does not matter
var apple = {
  x: 32,
  y: 320
};

// get random whole numbers in a specific range
// @see https://stackoverflow.com/a/1527820/2124254
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

// game loop
function loop() {
  requestAnimationFrame(loop);

  // slow game loop to 15 fps instead of 60 (60/15 = 4)
  if (++count < 4) {
    return;
  }

  count = 0;
  context.clearRect(0,0,canvas.width,canvas.height);

  // move snake by it's velocity
  snake.x += snake.dx;
  snake.y += snake.dy;
  snake2.x += snake2.dx;
  snake2.y += snake2.dy;

  // wrap snake position horizontally on edge of screen
  if (snake.x < 0) {
    snake.x = canvas.width - grid;
  }
  else if (snake.x >= canvas.width) {
    snake.x = 0;
  }

  // wrap snake position vertically on edge of screen
  if (snake.y < 0) {
    snake.y = canvas.height - grid;
  }
  else if (snake.y >= canvas.height) {
    snake.y = 0;
  }

  if (snake2.x < 0) {
    snake2.x = canvas.width - grid;
  }
  else if (snake2.x >= canvas.width) {
    snake2.x = 0;
  }

  // wrap snake position vertically on edge of screen
  if (snake2.y < 0) {
    snake2.y = canvas.height - grid;
  }
  else if (snake2.y >= canvas.height) {
    snake2.y = 0;
  }

  // keep track of where snake has been. front of the array is always the head
  snake.cells.unshift({x: snake.x, y: snake.y});
  snake2.cells.unshift({x: snake2.x, y: snake2.y});

  // remove cells as we move away from them
  if (snake.cells.length > snake.maxCells) {
    snake.cells.pop();
  }
  if (snake2.cells.length > snake2.maxCells) {
    snake2.cells.pop();
  }
//Here the snake checks for collision with itself and with the 2nd snake
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y || cell.x === snake.cells[i].x && cell.y === snake2.cells[i].y)

The beginning of the code is just to check if snake 1 crossed paths with itself/ran into itself. After the OR statement is where it checks for snake 1 intercepting snake 2.

I attempted to tweak my code so it would look for the exact coordinate the snake is moving on, like this:

if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y || cell.xy === snake.cells[i].xy && cell.xy === snake2.cells[i].xy)

I put xy to check for both coordinates to try to create one coordinate point to look for. However, this only resulted in immediate death.
Does anyone have an idea of how to fix this? EDIT What else is needed?


问:
How to change `whitelist` to `safelist` in Jsoup 1.15.+ when using `Overzealous` at same time
In my project, I update Jsoup version from 1.14.3 to 1.15.3. Due to whitelist is discard and now use safelist, I found whitelist in Overzealous:Remark is still being used.

Here is my code

```<code>return remark.get().convertFragment(safe)
    .replaceAll("\r\n", "\n")
    .replaceAll("\n\n```\n", "\n\n```java\n");
</code>```

And here is Jsoup update note on Github.

```<code>  * Improvement: renamed the Whitelist class to Safelist, with the goal of more inclusive language. A shim is provided
    for backwards compatibility (source and binary). This shim is marked as deprecated and will be removed in the
    jsoup 1.15.1 release.
    <https://github.com/jhy/jsoup/pull/1464>
</code>```

Due to I used overzealous at the same time, I meet this issue by accident.

```<code>public Remark(Options options) {
        this.converterLock = new ReentrantLock();
        this.cleanedHtmlEchoed = false;
        this.options = options.getCopy();
        Whitelist whitelist = Whitelist.basicWithImages().addTags(new String[]{"div", "h1", "h2", "h3", "h4", "h5", "h6", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "hr", "span", "font", "del", "strike", "s"}).addAttributes("th", new String[]{"colspan", "align", "style"}).addAttributes("td", new String[]{"colspan", "align", "style"}).addAttributes(":all", new String[]{"title", "style"});
        if (options.preserveRelativeLinks) {
            whitelist.preserveRelativeLinks(true);
        }
    ...
}
</code>```

This message shows what I see after update jsoup version to 1.15.3

```<code>java.lang.NoClassDefFoundError: org/jsoup/safety/Whitelist
</code>```

Everything seems good until I upgrade Jsoup version to 1.15.3, I just want to build succeed.

By the way, The highest overzealous version in mvn repository is 1.1.0.

Body:
In my project, I update Jsoup version from 1.14.3 to 1.15.3. Due to whitelist is discard and now use safelist, I found whitelist in Overzealous:Remark is still being used.

Here is my code

return remark.get().convertFragment(safe)
    .replaceAll("\r\n", "\n")
    .replaceAll("\n\n```\n", "\n\n```java\n");

And here is Jsoup update note on Github.

  * Improvement: renamed the Whitelist class to Safelist, with the goal of more inclusive language. A shim is provided
    for backwards compatibility (source and binary). This shim is marked as deprecated and will be removed in the
    jsoup 1.15.1 release.
    <https://github.com/jhy/jsoup/pull/1464>

Due to I used overzealous at the same time, I meet this issue by accident.

public Remark(Options options) {
        this.converterLock = new ReentrantLock();
        this.cleanedHtmlEchoed = false;
        this.options = options.getCopy();
        Whitelist whitelist = Whitelist.basicWithImages().addTags(new String[]{"div", "h1", "h2", "h3", "h4", "h5", "h6", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "hr", "span", "font", "del", "strike", "s"}).addAttributes("th", new String[]{"colspan", "align", "style"}).addAttributes("td", new String[]{"colspan", "align", "style"}).addAttributes(":all", new String[]{"title", "style"});
        if (options.preserveRelativeLinks) {
            whitelist.preserveRelativeLinks(true);
        }
    ...
}

This message shows what I see after update jsoup version to 1.15.3

java.lang.NoClassDefFoundError: org/jsoup/safety/Whitelist

Everything seems good until I upgrade Jsoup version to 1.15.3, I just want to build succeed.

By the way, The highest overzealous version in mvn repository is 1.1.0.


问:
Karma. SyntaxError: Expected an identifier but found ... instead - my version
I've read Karma. SyntaxError: Expected an identifier but found ... instead, and my issue seems the same. But please humor me, it's weirder in my case.

I have 2 Jenkins jobs that runs grunt karma on the same directory, but on 2 different branches, and the only diffs between the two branches is a *.js file that is in a different directory that I'm running grunt karma on. IOW, for all practical purposes on the directory I'm testing, the 2 branches are identical.

On my sandbox job that checks out my master branch, I can issue grunt karma and get

$ grunt karma
Running "karma:unit" (karma) task
08 01 2023 21:12:16.404:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
08 01 2023 21:12:16.406:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
08 01 2023 21:12:16.412:INFO [launcher]: Starting browser PhantomJS
08 01 2023 21:12:16.713:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket Ceegz0CmpJmQjl0uAAAA with id 84751163
PhantomJS 2.1.1 (Linux 0.0.0): Executed 51 of 51 SUCCESS (0.191 secs / 0.2 secs)

Done, without errors.

```
<p>But on a job that runs <code>grunt karma</code> on a <code>release/*</code> branch I get</p>
<pre class="lang-bash prettyprint-override"><code>$ grunt karma
Running "karma:unit" (karma) task
08 01 2023 21:34:55.619:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
08 01 2023 21:34:55.621:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
08 01 2023 21:34:55.625:INFO [launcher]: Starting browser PhantomJS
08 01 2023 21:34:55.937:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket PeYT79bHxmpbsAj2AAAA with id 65885438
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  SyntaxError: Expected an identifier but found 'jasmineRequire' instead
  at src/desktop/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:25

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  ReferenceError: Can't find variable: jasmineRequire
  at src/desktop/node_modules/karma-jasmine/lib/boot.js:14

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  ReferenceError: Can't find variable: jasmine
  at src/desktop/node_modules/karma-jasmine/lib/adapter.js:405

Warning: Task "karma:unit" failed. Use --force to continue.
</code>```

On BOTH branches, this is the line in above file

```<code>var getJasmineRequireObj = (function(jasmineGlobal) {
  let jasmineRequire;   // This is the offending line
</code>```

Here's my karma.conf.js file, also the same on BOTH branches

```<code>// karma.conf.js
module.exports = function(config) {
    config.set({
        frameworks: ['jasmine'],
        singleRun: true,
        browsers: ['PhantomJS'],
        browserConsoleLogOptions: {
            terminal: true,
            level: ""
        },
        files: [
            'src/common/lib/jquery/jquery-1.9.0.js',
            'src/common/lib/jquery/jquery.cookie.js',
            'src/common/lib/angular/1.8.2/angular.min.js',
            'src/common/lib/angular/1.8.2/*.js',
            'src/common/lib/angular-scrollable-table/angular-scrollable-table.js',
            'src/desktop/lib/bootstrap/bootstrap.js',
            'src/desktop/lib/bootstrap/angular-strap.js',
            'src/desktop/node_modules/angular-mocks/angular-mocks.js',
            'src/common/lib/hicharts/highcharts.js',
            'src/common/lib/localization/sprintf.js',
            'src/common/lib/localization/localization.js',
            'src/common/js/directives/ZiftDirectives.js',
            'src/common/js/modules/*.js',
            'src/common/js/controllers/agencyorder/*.js',
            'src/common/js/controllers/CampaignActivateController.js',
            'src/common/js/services/agencyorder/agencyOrderAssetOrderService.js',
            'src/common/js/services/agencyorder/quoteAgencySelectService.js',
            'src/common/js/constants.js',
            'src/common/js/services.js',
            'src/common/js/downloads/*.js',
            'src/common/js/services/export/ExportService.js',
            'src/common/js/services/leads/*.js',
            'test/**/*.js'
        ]
    });

</code>```

I delete the workspace when I run the jobs. What is my issue? TIA!

Body:
I've read Karma. SyntaxError: Expected an identifier but found ... instead, and my issue seems the same. But please humor me, it's weirder in my case.

I have 2 Jenkins jobs that runs grunt karma on the same directory, but on 2 different branches, and the only diffs between the two branches is a *.js file that is in a different directory that I'm running grunt karma on. IOW, for all practical purposes on the directory I'm testing, the 2 branches are identical.

On my sandbox job that checks out my master branch, I can issue grunt karma and get

$ grunt karma
Running "karma:unit" (karma) task
08 01 2023 21:12:16.404:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
08 01 2023 21:12:16.406:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
08 01 2023 21:12:16.412:INFO [launcher]: Starting browser PhantomJS
08 01 2023 21:12:16.713:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket Ceegz0CmpJmQjl0uAAAA with id 84751163
PhantomJS 2.1.1 (Linux 0.0.0): Executed 51 of 51 SUCCESS (0.191 secs / 0.2 secs)

Done, without errors.

But on a job that runs grunt karma on a release/* branch I get

$ grunt karma
Running "karma:unit" (karma) task
08 01 2023 21:34:55.619:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
08 01 2023 21:34:55.621:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
08 01 2023 21:34:55.625:INFO [launcher]: Starting browser PhantomJS
08 01 2023 21:34:55.937:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket PeYT79bHxmpbsAj2AAAA with id 65885438
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  SyntaxError: Expected an identifier but found 'jasmineRequire' instead
  at src/desktop/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:25

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  ReferenceError: Can't find variable: jasmineRequire
  at src/desktop/node_modules/karma-jasmine/lib/boot.js:14

PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  ReferenceError: Can't find variable: jasmine
  at src/desktop/node_modules/karma-jasmine/lib/adapter.js:405

Warning: Task "karma:unit" failed. Use --force to continue.

On BOTH branches, this is the line in above file

var getJasmineRequireObj = (function(jasmineGlobal) {
  let jasmineRequire;   // This is the offending line

Here's my karma.conf.js file, also the same on BOTH branches

// karma.conf.js
module.exports = function(config) {
    config.set({
        frameworks: ['jasmine'],
        singleRun: true,
        browsers: ['PhantomJS'],
        browserConsoleLogOptions: {
            terminal: true,
            level: ""
        },
        files: [
            'src/common/lib/jquery/jquery-1.9.0.js',
            'src/common/lib/jquery/jquery.cookie.js',
            'src/common/lib/angular/1.8.2/angular.min.js',
            'src/common/lib/angular/1.8.2/*.js',
            'src/common/lib/angular-scrollable-table/angular-scrollable-table.js',
            'src/desktop/lib/bootstrap/bootstrap.js',
            'src/desktop/lib/bootstrap/angular-strap.js',
            'src/desktop/node_modules/angular-mocks/angular-mocks.js',
            'src/common/lib/hicharts/highcharts.js',
            'src/common/lib/localization/sprintf.js',
            'src/common/lib/localization/localization.js',
            'src/common/js/directives/ZiftDirectives.js',
            'src/common/js/modules/*.js',
            'src/common/js/controllers/agencyorder/*.js',
            'src/common/js/controllers/CampaignActivateController.js',
            'src/common/js/services/agencyorder/agencyOrderAssetOrderService.js',
            'src/common/js/services/agencyorder/quoteAgencySelectService.js',
            'src/common/js/constants.js',
            'src/common/js/services.js',
            'src/common/js/downloads/*.js',
            'src/common/js/services/export/ExportService.js',
            'src/common/js/services/leads/*.js',
            'test/**/*.js'
        ]
    });

I delete the workspace when I run the jobs. What is my issue? TIA!


问:
Call All User API with angular
I have problem calling API to HTML. The log is show up but the data is not show up on the html. How to call this type API properly? I'm using fuse Angular for the layout and data stuff

This is the HTML and Component

export class UserGroupTeamComponent implements OnInit
{
    members: any;

    constructor(private _CloudUserServer:CloudUserService)
    {
    }

    ngOnInit(): void
    {
       this.getMembers();

    }
    async getMembers(): Promise<any> {
        this.members = await this._CloudUserServer.getUsers();
        console.log('abc',this.members)
      }

    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular.min.js"></script>
<div class="flex flex-col mt-8 divide-y border-t">
        <ng-container *ngFor="let member of members">
            <div class="flex flex-col sm:flex-row sm:items-center py-6">
                <div class="flex items-center">
                    <div class="ml-4">
                        <div class="font-medium" *ngIf="members">{{member.name}}</div>
                        <div class="text-secondary">{{member.email}}</div>
                    </div>
                </div>
            </div>
        </ng-container>
    </div></code>```

this is CloudUserService

async getUsers(limit?: number, lastKey?: string, filter?: string): Promise<any> {
        const headers = {
            // eslint-disable-next-line @typescript-eslint/naming-convention
            Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}`
        };
        const body = {};
        const options = {headers: headers, body: body};
        const limitParam = limit ? '&limit=' + limit.toString() : '';
        const idParam = lastKey ? '&id=' + lastKey : '';
        const filterParam = filter ? '&filter=%25' + filter + '%25' : '';

        const path = `${this._userUrl}/users?${limitParam}${idParam}${filterParam}`;

        const promise = API.get(this._apiName, path, options).then(
            (result) => {
              console.log('getUsers result', result);
              return result.message;
            },
            (err) => {
              console.log('getUsers err', err.response);
              throw(err.response);
            }
        );

        return promise;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular.min.js"></script></code>```

The result should be all user name and user show up.

Title: Call All User API with angular

Body:
I have problem calling API to HTML. The log is show up but the data is not show up on the html. How to call this type API properly? I'm using fuse Angular for the layout and data stuff

This is the HTML and Component

export class UserGroupTeamComponent implements OnInit
{
    members: any;

    constructor(private _CloudUserServer:CloudUserService)
    {
    }

    ngOnInit(): void
    {
       this.getMembers();

    }
    async getMembers(): Promise<any> {
        this.members = await this._CloudUserServer.getUsers();
        console.log('abc',this.members)
      }

    }
}

        <ng-container *ngFor="let member of members">

{{member.name}}

{{member.email}}

        </ng-container>

this is CloudUserService

async getUsers(limit?: number, lastKey?: string, filter?: string): Promise<any> {
        const headers = {
            // eslint-disable-next-line @typescript-eslint/naming-convention
            Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}`
        };
        const body = {};
        const options = {headers: headers, body: body};
        const limitParam = limit ? '&limit=' + limit.toString() : '';
        const idParam = lastKey ? '&id=' + lastKey : '';
        const filterParam = filter ? '&filter=%25' + filter + '%25' : '';

        const path = `${this._userUrl}/users?${limitParam}${idParam}${filterParam}`;

        const promise = API.get(this._apiName, path, options).then(
            (result) => {
              console.log('getUsers result', result);
              return result.message;
            },
            (err) => {
              console.log('getUsers err', err.response);
              throw(err.response);
            }
        );

        return promise;
    }

The result should be all user name and user show up.


问:
How to tackle the following error in NetworkX?
I gotta add the nodes and edges from two different lists that I created. Although the nodes are being processed but the edges aren't and thus, the error.

Here's a li'l snippet of my code:
#list3 is the list of the whole dataset

```<code>
listOfRelations = []
listOfNodes = []

for index in range(0, len(list3)):

  #if list3[index].isalpha():

  if list3[index].isdigit():

    listOfNodes.append(list3[index])

  else:
    listOfRelations.append(list3[index])

#testing purposes
print(listOfNodes[3])
print(listOfRelations[2])

G.add_nodes_from((listOfNodes))
G.add_edges_from((TupleOfEdges))

</code>```

I also tried to convert the list into a tuple, but that didn't work either :(

Error: NetworkXError: Edge tuple _hypernym must be a 2-tuple or 3-tuple.

Body:
I gotta add the nodes and edges from two different lists that I created. Although the nodes are being processed but the edges aren't and thus, the error.

Here's a li'l snippet of my code:
#list3 is the list of the whole dataset

listOfRelations = []
listOfNodes = []

for index in range(0, len(list3)):

  #if list3[index].isalpha():

  if list3[index].isdigit():

    listOfNodes.append(list3[index])

  else:
    listOfRelations.append(list3[index])

#testing purposes
print(listOfNodes[3])
print(listOfRelations[2])

G.add_nodes_from((listOfNodes))
G.add_edges_from((TupleOfEdges))

I also tried to convert the list into a tuple, but that didn't work either :(

Error: NetworkXError: Edge tuple _hypernym must be a 2-tuple or 3-tuple.


问:
How is this raster image animation accomplished? Magic?
I have been wondered about this for several years now. And it comes up increasingly regularly for me (I do mostly product and design some web dev) and now I have some thoughts on how it could be used very powerfully for some new projects but I need to understand it technically. There are some cases where I see still raster images that have had animation added to them on the web, yet they are not video so they can be used with much more versatility and as I understand it with lower performance impact. Riot games uses it frequently, here's is and example on one of their sites. (scroll down to the Agents section with the red background): https://playvalorant.com/en-us/?gclid=CjwKCAiA8OmdBhAgEiwAShr403pomRb6Wqu1mwgbgfR8AbeuJs1FROTT6E_rSZw5QjXu8zNnS61hvRoCvq4QAvD_BwE&gclsrc=aw.ds .
screenshot
I need to understand how the art here was authored and implemented. Can anyone help me learn this?

I inspected it and there seem to be several components that make it up but I can't make any sense of it all. Are people doing this onto something too sophisticated to be common use? I have looked at some animation tools and searched everywhere for info and I'm not finding any clues.


问:
How to load Field from torchtext.data?
I have installed torchtext v 0.14.1. I am on Windows. I tried to load Field but I got the following error. Can anybody help me fix it?</p>
```<code>from torchtext.data import Field

ImportError: cannot import name 'Field' from 'torchtext.data' (C:\Users\X\anaconda3\envs\torch-env\lib\site-packages\torchtext\data\__init__.py)
</code>```

Title: How to load Field from torchtext.data?

Body:
I have installed torchtext v 0.14.1. I am on Windows. I tried to load Field but I got the following error. Can anybody help me fix it?

from torchtext.data import Field

ImportError: cannot import name 'Field' from 'torchtext.data' (C:\Users\X\anaconda3\envs\torch-env\lib\site-packages\torchtext\data\__init__.py)