问:
How to create a protective routing with next js and firebase
I'm working on an app where a user must be signed in to get access to the available routes. I've in the past used React router with a custom component that checks if there is a current user that is signed in.

Tried to implement the same logic in the next js projects, but wasn't too successful. When I sign in I get redirected to the user page using the push method in `useRouter(). But when I reload while on the home page, the app routes me back to my login page.
How do I apply the same logic as in react for next js?

How I have done it in the past with React,

import { Navigate } from 'react-router-dom';
import { IPrivateRoute } from '../Models/IPrivateRoute';
import { useAuth } from './Contexs/AuthContext';

export const PrivateRoute: React.FC<IPrivateRoute> = ({ component: RouteComponent }) => {
  // importing state from context
  const { currentUser, currentUserLoading } = useAuth();

  return currentUser || currentUserLoading ? <RouteComponent /> : <Navigate replace to='/signin' />;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>import { Routes, Route } from 'react-router-dom';
import { MainContentWrapper } from '../Styles/StyledComponents/Wrapper';
import { PrivateRoute } from '../Utils/PrivateRoute';
import { CreateProfileView } from './CreateProfileView';
import { EditProfileView } from './EditProfileView';
import { ErrorPage } from './ErrorView';
import { MatchesView } from './MatchesView';
import { MessageView } from './MessageView';
import { ProfileView } from './ProfileView';
import { ResetPasswordView } from './ResetPasswordView';
import { SignInView } from './SignInView';
import { SignUpView } from './SignUpView';
import { SwipeView } from './SwipeView';

export const AppWrapper = () => {
  return (
    <div className='appWrapper'>
      <Routes>
        <Route path='/' element={<PrivateRoute component={SwipeView} />} />
        <Route
          path='/signin'
          element={
            <MainContentWrapper className='signInViewWrapper'>
              <SignInView />
            </MainContentWrapper>
          }
        />
        <Route
          path='/signup'
          element={
            <MainContentWrapper className='signUpViewWrapper'>
              <SignUpView />
            </MainContentWrapper>
          }
        />
        <Route
          path='/resetpassword'
          element={
            <MainContentWrapper className='resetPasswordViewWrapper'>
              <ResetPasswordView />
            </MainContentWrapper>
          }
        />
        <Route path='/createprofile' element={<PrivateRoute component={CreateProfileView} />} />
        <Route path='/profile' element={<PrivateRoute component={ProfileView} />} />
        <Route path='/editprofile' element={<PrivateRoute component={EditProfileView} />} />
        <Route path='/matches' element={<PrivateRoute component={MatchesView} />} />
        <Route path='/matches/:id' element={<PrivateRoute component={MessageView} />} />
        <Route
          path='*'
          element={
            <div className='appContent'>
              <ErrorPage />
            </div>
          }
        />
      </Routes>
    </div>
  );
};</code>```

How i have it now in Next.js

ProtectedRoutes - component

  import { useRouter } from 'next/router';
  import React, { useEffect } from 'react';
  import { IChildren } from '../../model/IChildren';
  import { useAuth } from '../../utils/context/AuthContext';
  import { noAuthRequired } from '../../utils/NoAuthRequired';

  const ProtectedRoutes = ({ children }: IChildren) => {
  const { currentUser, currentUserLoading } = useAuth();
  const router = useRouter();

  useEffect(() => {
  if (currentUser && noAuthRequired.includes(router.pathname)) {
  router.push('/');
  }
  if (!currentUser) {
  router.push('/auth/signin');
  }
  }, [router, currentUser]);

 return (
  <>
    {currentUser && children}
    {currentUserLoading &&
Loading...
}
  </>
  );
 };

export default ProtectedRoutes;
```
<p><strong>_app.tsx</strong></p>
<pre class="lang-html prettyprint-override"><code>    import '../styles/globals.css';
    import type { AppProps } from 'next/app';
    import { ThemeProvider } from '@mui/material/styles';
    import { theme } from '../styles/theme/muiTheme';
    import { AuthContexProvider } from '../utils/context/AuthContext';
    import ProtectedRoutes from '../components/ProtectedRoutes/ProtectedRoutes';
    import { useRouter } from 'next/router';

    const noAuthRequired = ['/auth/signin', '/auth/signup', '/auth/resetPassword'];

    function MyApp({ Component, pageProps }: AppProps) {
    const router = useRouter();

     console.log('router.pathname', router.pathname);
     return (
      <AuthContexProvider>
      <ThemeProvider theme={theme}>
        {noAuthRequired.includes(router.pathname) ? (
          <Component {...pageProps} />
        ) : (
          <ProtectedRoutes>
            <Component {...pageProps} />
          </ProtectedRoutes>
        )}
      </ThemeProvider>
    </AuthContexProvider>
  );
 }

 export default MyApp;
</code>```

Body:
I'm working on an app where a user must be signed in to get access to the available routes. I've in the past used React router with a custom component that checks if there is a current user that is signed in.

Tried to implement the same logic in the next js projects, but wasn't too successful. When I sign in I get redirected to the user page using the push method in `useRouter(). But when I reload while on the home page, the app routes me back to my login page.
How do I apply the same logic as in react for next js?

How I have done it in the past with React,

import { Navigate } from 'react-router-dom';
import { IPrivateRoute } from '../Models/IPrivateRoute';
import { useAuth } from './Contexs/AuthContext';

export const PrivateRoute: React.FC<IPrivateRoute> = ({ component: RouteComponent }) => {
  // importing state from context
  const { currentUser, currentUserLoading } = useAuth();

  return currentUser || currentUserLoading ? <RouteComponent /> : <Navigate replace to='/signin' />;
};

import { Routes, Route } from 'react-router-dom';
import { MainContentWrapper } from '../Styles/StyledComponents/Wrapper';
import { PrivateRoute } from '../Utils/PrivateRoute';
import { CreateProfileView } from './CreateProfileView';
import { EditProfileView } from './EditProfileView';
import { ErrorPage } from './ErrorView';
import { MatchesView } from './MatchesView';
import { MessageView } from './MessageView';
import { ProfileView } from './ProfileView';
import { ResetPasswordView } from './ResetPasswordView';
import { SignInView } from './SignInView';
import { SignUpView } from './SignUpView';
import { SwipeView } from './SwipeView';

export const AppWrapper = () => {
  return (

      <Routes>
        <Route path='/' element={<PrivateRoute component={SwipeView} />} />
        <Route
          path='/signin'
          element={
            <MainContentWrapper className='signInViewWrapper'>
              <SignInView />
            </MainContentWrapper>
          }
        />
        <Route
          path='/signup'
          element={
            <MainContentWrapper className='signUpViewWrapper'>
              <SignUpView />
            </MainContentWrapper>
          }
        />
        <Route
          path='/resetpassword'
          element={
            <MainContentWrapper className='resetPasswordViewWrapper'>
              <ResetPasswordView />
            </MainContentWrapper>
          }
        />
        <Route path='/createprofile' element={<PrivateRoute component={CreateProfileView} />} />
        <Route path='/profile' element={<PrivateRoute component={ProfileView} />} />
        <Route path='/editprofile' element={<PrivateRoute component={EditProfileView} />} />
        <Route path='/matches' element={<PrivateRoute component={MatchesView} />} />
        <Route path='/matches/:id' element={<PrivateRoute component={MessageView} />} />
        <Route
          path='*'
          element={

              <ErrorPage />

          }
        />
      </Routes>

  );
};

How i have it now in Next.js

ProtectedRoutes - component

  import { useRouter } from 'next/router';
  import React, { useEffect } from 'react';
  import { IChildren } from '../../model/IChildren';
  import { useAuth } from '../../utils/context/AuthContext';
  import { noAuthRequired } from '../../utils/NoAuthRequired';

  const ProtectedRoutes = ({ children }: IChildren) => {
  const { currentUser, currentUserLoading } = useAuth();
  const router = useRouter();

  useEffect(() => {
  if (currentUser && noAuthRequired.includes(router.pathname)) {
  router.push('/');
  }
  if (!currentUser) {
  router.push('/auth/signin');
  }
  }, [router, currentUser]);

 return (
  <>
    {currentUser && children}
    {currentUserLoading &&
Loading...
}
  </>
  );
 };

export default ProtectedRoutes;

_app.tsx

    import '../styles/globals.css';
    import type { AppProps } from 'next/app';
    import { ThemeProvider } from '@mui/material/styles';
    import { theme } from '../styles/theme/muiTheme';
    import { AuthContexProvider } from '../utils/context/AuthContext';
    import ProtectedRoutes from '../components/ProtectedRoutes/ProtectedRoutes';
    import { useRouter } from 'next/router';

    const noAuthRequired = ['/auth/signin', '/auth/signup', '/auth/resetPassword'];

    function MyApp({ Component, pageProps }: AppProps) {
    const router = useRouter();

     console.log('router.pathname', router.pathname);
     return (
      <AuthContexProvider>
      <ThemeProvider theme={theme}>
        {noAuthRequired.includes(router.pathname) ? (
          <Component {...pageProps} />
        ) : (
          <ProtectedRoutes>
            <Component {...pageProps} />
          </ProtectedRoutes>
        )}
      </ThemeProvider>
    </AuthContexProvider>
  );
 }

 export default MyApp;


来源: stackexchange

问:
How to get DebugDiag to show method names in the stack trace?
I am trying to get to the bottom of a crash in a .NET 4.61 web application running under IIS.  I got Windows to generate memory dump on crash.  I then loaded the .dmp file into DebugDiag and added another SYMBOL folder that contained the entire application including .PDBs for all the DLLs.

However, all I got was DLL names with Unknown for a method name + an offset.  What am I missing or what can I do to make the method names appear?

ContentLicense: CC BY-SA 4.0


问:
is there a marker clustering library that works with Flutter bloc and Google Maps?
I ran into a bit of a wall when i tried to implement marker clustering in a Google Maps based app that i'm developing for work.

I figured i could use circles to represent clusters and swap markers for circles at a certain zoom threshold but that didn't work out, so now I'm using a clustering library.

The main issue is that said library doesn't take into account if the app uses a state management library, so here i am with an empty map once again.

I render my map like this:

```<code>

class MapView extends StatelessWidget {
  final LatLng initialLocation;
  final Set<Marker> markers;
  final CustomInfoWindowController infoWindowController;
  final GoogleMapController? mapController;
  final ClusterManager manager;
  Completer<GoogleMapController> newMapController = Completer();

  MapView(
      {Key? key,
      required this.initialLocation,
      required this.markers,
      required this.manager,
      required this.infoWindowController,
      this.mapController})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final CameraPosition initialCameraPosition =
        CameraPosition(target: initialLocation);

    final renderSize = MediaQuery.of(context).size;

    return SizedBox(
        width: renderSize.width,
        height: renderSize.height,
        child: GoogleMap(
          onTap: (position) {
            infoWindowController.hideInfoWindow!();
            if (context.read<MapBloc>().state.creatingLocation == true) {
              context.read<MapBloc>().add(TurnCreationModeOff());
            }
          },
          onCameraMove: (position) {
            infoWindowController.onCameraMove!();
            manager.onCameraMove(position);
          },
          onCameraIdle: () {
            context.read<MapBloc>().add(HoldZoomLevel());
            manager.updateMap();
            context.read<MapBloc>().printMapID();
          },
          onLongPress: (LatLng location) {
            context
                .read<LocationCreationBloc>()
                .add(LocationAcquired(location: location));
            final Marker newMarker = Marker(
                draggable: true,
                markerId: const MarkerId('new'),
                position: location,
                icon: BitmapDescriptor.defaultMarkerWithHue(
                    BitmapDescriptor.hueViolet),
                infoWindow: InfoWindow(
                  title: 'Pulsame para crear una nueva ubicacion',
                  snippet:
                      'Toca cualquier lado del mapa y reajusta el zoom para destruirme',
                  onTap: () {
                    Navigator.of(context).pushAndRemoveUntil(
                        CreationScreen.route(), (route) => false);
                  },
                ));
            context.read<MapBloc>().add(RenderNewMarker(marker: newMarker));
          },
          initialCameraPosition: initialCameraPosition,
          compassEnabled: true,
          myLocationEnabled: true,
          markers: markers,
          zoomControlsEnabled: false,
          myLocationButtonEnabled: true,
          mapToolbarEnabled: false,
          onMapCreated: (GoogleMapController controller) {
            context.read<MapBloc>().add(MapInitialized(
                controller: controller,
                windowController: infoWindowController,
                clusterManager: manager,
                location:
                    context.read<LocationBloc>().state.lastKnownLocation));
            newMapController.complete(controller);
            manager.setMapId(controller.mapId);
            infoWindowController.googleMapController = controller;
          },
        )
        );
  }
}
</code>```

some stuff is  heavily context dependant and i'd be happy to elaborate and provide more code samples if anyone needs them or has run into a similar issue.

i tried recoupling my business logic with my presentation layer, that being initializing a List of clusterable items and passing it to the Cluster Manager constructor but it crashed at runtime.

Body:
I ran into a bit of a wall when i tried to implement marker clustering in a Google Maps based app that i'm developing for work.

I figured i could use circles to represent clusters and swap markers for circles at a certain zoom threshold but that didn't work out, so now I'm using a clustering library.

The main issue is that said library doesn't take into account if the app uses a state management library, so here i am with an empty map once again.

I render my map like this:

class MapView extends StatelessWidget {
  final LatLng initialLocation;
  final Set<Marker> markers;
  final CustomInfoWindowController infoWindowController;
  final GoogleMapController? mapController;
  final ClusterManager manager;
  Completer<GoogleMapController> newMapController = Completer();

  MapView(
      {Key? key,
      required this.initialLocation,
      required this.markers,
      required this.manager,
      required this.infoWindowController,
      this.mapController})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final CameraPosition initialCameraPosition =
        CameraPosition(target: initialLocation);

    final renderSize = MediaQuery.of(context).size;

    return SizedBox(
        width: renderSize.width,
        height: renderSize.height,
        child: GoogleMap(
          onTap: (position) {
            infoWindowController.hideInfoWindow!();
            if (context.read<MapBloc>().state.creatingLocation == true) {
              context.read<MapBloc>().add(TurnCreationModeOff());
            }
          },
          onCameraMove: (position) {
            infoWindowController.onCameraMove!();
            manager.onCameraMove(position);
          },
          onCameraIdle: () {
            context.read<MapBloc>().add(HoldZoomLevel());
            manager.updateMap();
            context.read<MapBloc>().printMapID();
          },
          onLongPress: (LatLng location) {
            context
                .read<LocationCreationBloc>()
                .add(LocationAcquired(location: location));
            final Marker newMarker = Marker(
                draggable: true,
                markerId: const MarkerId('new'),
                position: location,
                icon: BitmapDescriptor.defaultMarkerWithHue(
                    BitmapDescriptor.hueViolet),
                infoWindow: InfoWindow(
                  title: 'Pulsame para crear una nueva ubicacion',
                  snippet:
                      'Toca cualquier lado del mapa y reajusta el zoom para destruirme',
                  onTap: () {
                    Navigator.of(context).pushAndRemoveUntil(
                        CreationScreen.route(), (route) => false);
                  },
                ));
            context.read<MapBloc>().add(RenderNewMarker(marker: newMarker));
          },
          initialCameraPosition: initialCameraPosition,
          compassEnabled: true,
          myLocationEnabled: true,
          markers: markers,
          zoomControlsEnabled: false,
          myLocationButtonEnabled: true,
          mapToolbarEnabled: false,
          onMapCreated: (GoogleMapController controller) {
            context.read<MapBloc>().add(MapInitialized(
                controller: controller,
                windowController: infoWindowController,
                clusterManager: manager,
                location:
                    context.read<LocationBloc>().state.lastKnownLocation));
            newMapController.complete(controller);
            manager.setMapId(controller.mapId);
            infoWindowController.googleMapController = controller;
          },
        )
        );
  }
}

some stuff is  heavily context dependant and i'd be happy to elaborate and provide more code samples if anyone needs them or has run into a similar issue.

i tried recoupling my business logic with my presentation layer, that being initializing a List of clusterable items and passing it to the Cluster Manager constructor but it crashed at runtime.


问:
Plotly Dash app not getting javascript updated input element value when referenced from callback
I have an application written in python plotly dash. In this application I have a hidden input element specified below.

```<code>dcc.Input(id='output-gcps-to-map', type='hidden')
</code>```

I also have a javascript function that updates the value of this element from a global variable drawnPoints.

```<code>function saveGcps(){
    let gcps = document.getElementById('output-gcps-to-map');
    let gcpsToSave = [];
    for (gcp of drawnPoints){
        gcpsToSave.push([gcp[2],gcp[3]]);
    }
    gcps.value = JSON.stringify(gcpsToSave);
}
</code>```

The element 'output-gcps-to-map' is correctly updated by this function and adds an additional point to the collection.

Then I click my button linked to the plotly dash callback below.

```<code>@app.callback(
Output("georef-image", "value"),
[Input("georef-image", "n_clicks"), Input("output-gcps-to-map", "value")]
)
def georeference_image(n1, gcps):
    #does image exist
    #do 3 gcps exist
    if n1:
        return True
    return False
</code>```

At this point the callback is just a dummy function returning a hardcoded boolean, but the parameter "gcps" should contain the value in the hidden input element 'output-gcps-to-map'.

However, when I examine the parameter for a value it is 'None'.

Why does my callback not contain the value updated by my JavaScript function?

How can I fix this so that the updated value is persisted through to my dash application?

Body:
I have an application written in python plotly dash. In this application I have a hidden input element specified below.

dcc.Input(id='output-gcps-to-map', type='hidden')

I also have a javascript function that updates the value of this element from a global variable drawnPoints.

function saveGcps(){
    let gcps = document.getElementById('output-gcps-to-map');
    let gcpsToSave = [];
    for (gcp of drawnPoints){
        gcpsToSave.push([gcp[2],gcp[3]]);
    }
    gcps.value = JSON.stringify(gcpsToSave);
}

The element 'output-gcps-to-map' is correctly updated by this function and adds an additional point to the collection.

Then I click my button linked to the plotly dash callback below.

@app.callback(
Output("georef-image", "value"),
[Input("georef-image", "n_clicks"), Input("output-gcps-to-map", "value")]
)
def georeference_image(n1, gcps):
    #does image exist
    #do 3 gcps exist
    if n1:
        return True
    return False

At this point the callback is just a dummy function returning a hardcoded boolean, but the parameter "gcps" should contain the value in the hidden input element 'output-gcps-to-map'.

However, when I examine the parameter for a value it is 'None'.

Why does my callback not contain the value updated by my JavaScript function?

How can I fix this so that the updated value is persisted through to my dash application?


问:
Simulink customized block
I want to create a customized block in Simulink where only input and output ports are defined and then add any other block like machine learning (if possible) to process the input and generate the output. I have searched a lot but the examples on MathWorks are very specific. I am looking after a very general solution where a simple and empty block with only input/output ports can be added and output is generated based on the input.

Thanks in advance,

D.

Title: Simulink customized block


问:
How can I add "context" to an ElasticSearch Query e.g. phrase prefix + fuzzy search
At the moment I'm doing a full text search of HTML documents using a multi_match query with phrase_prefix. The problem I'm trying to solve is that the phrases relate to places. E.g. "The Tower" or "Gold Casino". Now, the same place name may exist in several cities/locations. So I'd like to add "context" to the search by specifying a city name for instance. E.g. "Gold Casino New York".

I believe using just phrase_prefix won't work, unless I do something like increasing slop value, but then a search like "The Blue Tower New York" could be valid when I just want "The Tower" specifically.

Is there a way to combine phrase_prefix with a fuzzy search of sorts? Here is my current query for examination:

```<code>{
  "_source": false,
  "fields": [
    {
      "field": "source"
    },
    {
      "field": "title"
    }
  ],
  "from": 0,
  "highlight": {
    "fragment_size": 200,
    "number_of_fragments": 1,
    "fields": {
      "seoDescription": {},
      "paragraphContent": {}
    }
  },
  "query": {
    "multi_match": {
      "fields": [
        "seoDescription^3",
        "paragraphContent"
      ],
      "query": "The Tower New York",
      "type": "phrase_prefix"
    }
  },
  "size": 20,
  "track_total_hits": true
}
</code>```

Body:
At the moment I'm doing a full text search of HTML documents using a multi_match query with phrase_prefix. The problem I'm trying to solve is that the phrases relate to places. E.g. "The Tower" or "Gold Casino". Now, the same place name may exist in several cities/locations. So I'd like to add "context" to the search by specifying a city name for instance. E.g. "Gold Casino New York".

I believe using just phrase_prefix won't work, unless I do something like increasing slop value, but then a search like "The Blue Tower New York" could be valid when I just want "The Tower" specifically.

Is there a way to combine phrase_prefix with a fuzzy search of sorts? Here is my current query for examination:

{
  "_source": false,
  "fields": [
    {
      "field": "source"
    },
    {
      "field": "title"
    }
  ],
  "from": 0,
  "highlight": {
    "fragment_size": 200,
    "number_of_fragments": 1,
    "fields": {
      "seoDescription": {},
      "paragraphContent": {}
    }
  },
  "query": {
    "multi_match": {
      "fields": [
        "seoDescription^3",
        "paragraphContent"
      ],
      "query": "The Tower New York",
      "type": "phrase_prefix"
    }
  },
  "size": 20,
  "track_total_hits": true
}


问:
How i can get poll answer from telegram?
I'm trying to get poll answer from user, how i can do this?
How i can get updates from the pollAnswer if i using webhook?
I need to get answer from non-anonymous poll (i'd like to make poll bot without showing correct answer to user (like in qizz bot)

```<code>let token = "my token";
let wUrl = "web url";

function getMe() {
  let response = UrlFetchApp.fetch("https://api.telegram.org/bot" + token + "/getMe");
  console.log(response.getContentText());
}

function setWebhook() {
  let webAppUrl = wUrl;
  let response = UrlFetchApp.fetch("https://api.telegram.org/bot" + token + "/setWebhook?url=" + webAppUrl);
  console.log(response.getContentText());
}

function getWebhookInfo() {
  let response = UrlFetchApp.fetch("https://api.telegram.org/bot" + token + "/getWebhookInfo");
  console.log(response.getContentText());
}

function sendText(chat_id, text, keyBoard) {
  let data = {
    method: "post",
    muteHttpExceptions: true,
    payload: {
      method: "sendMessage",
      chat_id: String(chat_id),
      text: text,
      parse_mode: "HTML",
      reply_markup: JSON.stringify(keyBoard)
    }
  };
  UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
};

function sendPoll(chat_id, question, answers, time) {
  let data = {
    method: "post",
    muteHttpExceptions: true,
    payload: {
      method: "sendPoll",
      chat_id: String(chat_id),
      question: String(question),
      parse_mode: "HTML",
      options: JSON.stringify(answers),
      is_closed: false,
      is_anonymous: false,
      type: "regular",
      allows_multiply_answers: false,
      open_period: time,
      protect_content: true}
    }
  UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
    Logger.log(data);
  };

function doPost(e) {
  const now = new Date();
  let ssId = "sheet id";//id таблицы
  let ss = SpreadsheetApp.openById(ssId).getSheetByName("qa");// имя страницы
  let qtime = ss.getRange("I1").getValue(); // время на вопрос
  let pid = ss.getRange("K1").getValue(); // id опроса
  let qn = ss.getRange("M1").getValue(); // к-во вопросов

  let lc = ss.getLastColumn();
  //let qr = ss.getRange(2, 9, qn, 5);
  //let values = qr.getValues();
  let q1 = ss.getRange(qn+2-qn,lc-4).getValue();
  let q1a1 = ss.getRange(qn+2-qn,lc-3).getValue();
  let q1a2 = ss.getRange(qn+2-qn,lc-2).getValue();
  let q1a3 = ss.getRange(qn+2-qn,lc-1).getValue();
  let q1a4 = ss.getRange(qn+2-qn,lc).getValue();
  let answers1 = [''+q1a1+'',''+q1a2+'',''+q1a3+'',''+q1a4+''];

  let q2 = ss.getRange(qn+3-qn,lc-4).getValue();
  let q2a1 = ss.getRange(qn+3-qn,lc-3).getValue();
  let q2a2 = ss.getRange(qn+3-qn,lc-2).getValue();
  let q2a3 = ss.getRange(qn+3-qn,lc-1).getValue();
  let q2a4 = ss.getRange(qn+2-qn,lc).getValue();
  let answers2 = [''+q2a1+'',''+q2a2+'',''+q2a3+'',''+q2a4+''];

  let data = JSON.parse(e.postData.contents);
  let chat_id = data.message.chat.id;
  let msg_id = data.message.id;
  let username = data.message.chat.username;
  let text = data.message.text;
  let keyBoard = {
        "inline_keyboard": [
          [{
            "text": "Начать",
            'callback_data': "start",
          }]],
          "resize_keyboard": true};

// if (text == "/start") {
  sendText(chat_id, "Привет "+username+", начнем?", keyBoard);
}

  else if (text == "/start"+"_"+pid){
  sendPoll(chat_id,q1,answers1,qtime);
  Utilities.sleep(6000);
  let update = JSON.parse(e.postData.contents);
  if (update.poll_answer) {
    var pollId = update.poll_answer.poll_id;
    var user = update.poll_answer.user;
    var optionIds = update.poll_answer.option_ids;
 }//cant get poll id and answer

  SpreadsheetApp.openById(ssId).getSheetByName("Messages").appendRow([now, pollId, user, optionIds]); //don't work
  sendPoll(chat_id,q2,answers2,qtime);
  SpreadsheetApp.openById(ssId).getSheetByName("Messages").appendRow([now, chat_id, username]);
  SpreadsheetApp.openById(ssId).getSheetByName("debug").getRange(1, 1).setValue(JSON.stringify(data, null, 10));}

}
</code>```

I need to get poll answer from user and write it to row in sheet

Body:
I'm trying to get poll answer from user, how i can do this?
How i can get updates from the pollAnswer if i using webhook?
I need to get answer from non-anonymous poll (i'd like to make poll bot without showing correct answer to user (like in qizz bot)

let token = "my token";
let wUrl = "web url";

function getMe() {
  let response = UrlFetchApp.fetch("https://api.telegram.org/bot" + token + "/getMe");
  console.log(response.getContentText());
}

function setWebhook() {
  let webAppUrl = wUrl;
  let response = UrlFetchApp.fetch("https://api.telegram.org/bot" + token + "/setWebhook?url=" + webAppUrl);
  console.log(response.getContentText());
}

function getWebhookInfo() {
  let response = UrlFetchApp.fetch("https://api.telegram.org/bot" + token + "/getWebhookInfo");
  console.log(response.getContentText());
}

function sendText(chat_id, text, keyBoard) {
  let data = {
    method: "post",
    muteHttpExceptions: true,
    payload: {
      method: "sendMessage",
      chat_id: String(chat_id),
      text: text,
      parse_mode: "HTML",
      reply_markup: JSON.stringify(keyBoard)
    }
  };
  UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
};

function sendPoll(chat_id, question, answers, time) {
  let data = {
    method: "post",
    muteHttpExceptions: true,
    payload: {
      method: "sendPoll",
      chat_id: String(chat_id),
      question: String(question),
      parse_mode: "HTML",
      options: JSON.stringify(answers),
      is_closed: false,
      is_anonymous: false,
      type: "regular",
      allows_multiply_answers: false,
      open_period: time,
      protect_content: true}
    }
  UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
    Logger.log(data);
  };

function doPost(e) {
  const now = new Date();
  let ssId = "sheet id";//id таблицы
  let ss = SpreadsheetApp.openById(ssId).getSheetByName("qa");// имя страницы
  let qtime = ss.getRange("I1").getValue(); // время на вопрос
  let pid = ss.getRange("K1").getValue(); // id опроса
  let qn = ss.getRange("M1").getValue(); // к-во вопросов

  let lc = ss.getLastColumn();
  //let qr = ss.getRange(2, 9, qn, 5);
  //let values = qr.getValues();
  let q1 = ss.getRange(qn+2-qn,lc-4).getValue();
  let q1a1 = ss.getRange(qn+2-qn,lc-3).getValue();
  let q1a2 = ss.getRange(qn+2-qn,lc-2).getValue();
  let q1a3 = ss.getRange(qn+2-qn,lc-1).getValue();
  let q1a4 = ss.getRange(qn+2-qn,lc).getValue();
  let answers1 = [''+q1a1+'',''+q1a2+'',''+q1a3+'',''+q1a4+''];

  let q2 = ss.getRange(qn+3-qn,lc-4).getValue();
  let q2a1 = ss.getRange(qn+3-qn,lc-3).getValue();
  let q2a2 = ss.getRange(qn+3-qn,lc-2).getValue();
  let q2a3 = ss.getRange(qn+3-qn,lc-1).getValue();
  let q2a4 = ss.getRange(qn+2-qn,lc).getValue();
  let answers2 = [''+q2a1+'',''+q2a2+'',''+q2a3+'',''+q2a4+''];

  let data = JSON.parse(e.postData.contents);
  let chat_id = data.message.chat.id;
  let msg_id = data.message.id;
  let username = data.message.chat.username;
  let text = data.message.text;
  let keyBoard = {
        "inline_keyboard": [
          [{
            "text": "Начать",
            'callback_data': "start",
          }]],
          "resize_keyboard": true};

// if (text == "/start") {
  sendText(chat_id, "Привет "+username+", начнем?", keyBoard);
}

  else if (text == "/start"+"_"+pid){
  sendPoll(chat_id,q1,answers1,qtime);
  Utilities.sleep(6000);
  let update = JSON.parse(e.postData.contents);
  if (update.poll_answer) {
    var pollId = update.poll_answer.poll_id;
    var user = update.poll_answer.user;
    var optionIds = update.poll_answer.option_ids;
 }//cant get poll id and answer

  SpreadsheetApp.openById(ssId).getSheetByName("Messages").appendRow([now, pollId, user, optionIds]); //don't work
  sendPoll(chat_id,q2,answers2,qtime);
  SpreadsheetApp.openById(ssId).getSheetByName("Messages").appendRow([now, chat_id, username]);
  SpreadsheetApp.openById(ssId).getSheetByName("debug").getRange(1, 1).setValue(JSON.stringify(data, null, 10));}

}

I need to get poll answer from user and write it to row in sheet


问:
How do I send an email to a user using SMTP in Django?
I use the SMTP server to send the reset password link to the user, but the problem is when the user enters his or her email ,  the reset password email is not sent to him. Anyone can help me, please?

settings.py :

```<code>EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER  = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS= True
EMAIL_HOST_USER = 'myemail'
EMAIL_HOST_PASSWORD = 'mypassword'
</code>```

urls.py :

```<code>    path('ResetPassword/' , views.ForgetPassword,name = "ResetPassword"),
    path('Test_ChangePass/<token>/', views.Test_ChangePass, name = 'Test_ChangePass'),
</code>```

models.py :

```<code>class Profile(models.Model):
    image = models.ImageField(default='default.png', upload_to='profile_pics')
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    forget_password_token = models.CharField(max_length=100)
    def __str__(self):
        return '{} profile.'.format(self.user.username)
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.width > 300 or img.height > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

def create_profile(sender, **kwarg):
    if kwarg['created']:
        Profile.objects.create(user =kwarg['instance'])
post_save.connect(create_profile, sender=User)

</code>```

views.py :

```<code>
def ForgetPassword(request):
    try:
        if request.method == "POST":
            email = request.POST.get('email')
            if not User.object.filter(email=email).first():
                messages.error(request, 'Email not found ')
                return redirect('ResetPassword')
            user_obj = User.objects.get(email=email)
            token = str(uuid.uuid4())
            profile_obj = Profile.objects.get(user = user_obj)
            profile_obj.forget_password_token = token
            profile_obj.save()
            send_forget_password_mail(user_obj,token)
            messages.error(request, 'The Email Sent')
            return redirect('ResetPassword')
    except Exception as e:
        print(e)
    return render(request, 'user/ResetPassword.html')

def Test_ChangePass(request, token):
    context = {}
    try:
        Profile_obj = Profile.objects.filter(forget_password_token = token).first()
        print(Profile_obj)

        if request.method == "POST":
            new_password = request.POST.get ('new_password')
            confirm_password = request.POST.get('confirm_password')

            user_id = request.POST.get('user_id')

            if user_id is None:
                messages.error(request,'No Email Found')
                return redirect(f'Test_ChangePass/{token}/')

            if new_password != confirm_password:
                messages.error(request,'The passwords must be equal')
                return redirect(f'Test_ChangePass/{token}/')

            user_obj = User.objects.get(id = user_id)
            user_obj.set_password(new_password)
            user_obj.save()
            return redirect('login')

        context = {'user_id' : Profile_obj.user.id}
    except Exception as e:
        print(e)
    return render(request, 'user/Test_ChangePass.html', context)
</code>```

helper.py :

```<code>from django.core.mail import send_mail
import uuid
from django.conf import settings
def send_forget_password_mail(email,token):
    subject = 'You forget password link'
    message = f'Hi, Click on the link to reset your password http://127.0.0.1:8000/Test_ChangePass/{token}/'
    email_from = settings.EMAIL_HOST_USER
    recipient_list = [email]
    send_mail(subject, message, email_from,recipient_list)
    return True

</code>```

ResetPassword.html

```<code>
{% if messages %}
{% for message in messages %}
    <div class="alert alert-{{message.tags}}">
        {{message}}
    </div>
{% endfor %}
{% endif %}

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta name="viewport" content="width=device-width" charset="UTF-8">

    <style>
        body{
            background-color: #7d8f69;
        }
    </style>
</head>
<body>
    <div class="page login-page form">

        <form method="post"  class="login-form" id="form">
            {% csrf_token %}
            <div class="fieldWraber" style="text-align: right;">
               <br/>
                <label for="{{form.username.id_for_label}}">Email </label>
                <input type="text" name="email" id="email"  >
                     {{form.email}}
                    <span class="error">{{form.email.errors}}</span>
            </div>
        <p><input class="submit-button" type="submit" value="Send"></p>
         </form>

        {% endblock %}
</code>```

Test_ChangePass.html:

```<code>

{% if messages %}
{% for message in messages %}
    <div class="alert alert-{{message.tags}}">
        {{message}}
    </div>
{% endfor %}
{% endif %}

<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta name="viewport" content="width=device-width" charset="UTF-8">
    <style>
        body{
            background-color: #7d8f69;
        }
    </style>
</head>
<body>
    <div class="page register-page form" style="text-align: right;" >
        <h1 class="title">Change Password/h1>
        <form method="POST" class="register-form">
            {% csrf_token %}
            <div class="fieldWraber">
                <label for="{{form.password1.id_for_label}}">Password1:

             </label>
                {{form.password1}}
                <span class="error">{{form.password1.errors}}</span>
            </div>

            <div class="fieldWraber">
                <label for="{{form.password2.id_for_label}}">Confirem Password </label>
                {{form.password2}}
                <span class="error">{{form.password2.errors}}</span>
            </div>

            {% if form.non_field_errors %}
            <div class="non_form_errors">
                <span class="error">
                {{form.non_field_errors.as_ul}}
                </span>
            </div>
            {% endif %}

            <input type="hidden" name="user_id" value="{{user_id}}" >

            <input type="submit" value="Reset" class="submit-button">

        </form>

{% endblock %}

</code>```

**No forms.py for the ResetPassword.html and TestChangePass.html
**

Body:
I use the SMTP server to send the reset password link to the user, but the problem is when the user enters his or her email ,  the reset password email is not sent to him. Anyone can help me, please?

settings.py :

EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER  = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS= True
EMAIL_HOST_USER = 'myemail'
EMAIL_HOST_PASSWORD = 'mypassword'

urls.py :

    path('ResetPassword/' , views.ForgetPassword,name = "ResetPassword"),
    path('Test_ChangePass/<token>/', views.Test_ChangePass, name = 'Test_ChangePass'),

models.py :

class Profile(models.Model):
    image = models.ImageField(default='default.png', upload_to='profile_pics')
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    forget_password_token = models.CharField(max_length=100)
    def __str__(self):
        return '{} profile.'.format(self.user.username)
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img = Image.open(self.image.path)
        if img.width > 300 or img.height > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)

def create_profile(sender, **kwarg):
    if kwarg['created']:
        Profile.objects.create(user =kwarg['instance'])
post_save.connect(create_profile, sender=User)

views.py :

def ForgetPassword(request):
    try:
        if request.method == "POST":
            email = request.POST.get('email')
            if not User.object.filter(email=email).first():
                messages.error(request, 'Email not found ')
                return redirect('ResetPassword')
            user_obj = User.objects.get(email=email)
            token = str(uuid.uuid4())
            profile_obj = Profile.objects.get(user = user_obj)
            profile_obj.forget_password_token = token
            profile_obj.save()
            send_forget_password_mail(user_obj,token)
            messages.error(request, 'The Email Sent')
            return redirect('ResetPassword')
    except Exception as e:
        print(e)
    return render(request, 'user/ResetPassword.html')

def Test_ChangePass(request, token):
    context = {}
    try:
        Profile_obj = Profile.objects.filter(forget_password_token = token).first()
        print(Profile_obj)

        if request.method == "POST":
            new_password = request.POST.get ('new_password')
            confirm_password = request.POST.get('confirm_password')

            user_id = request.POST.get('user_id')

            if user_id is None:
                messages.error(request,'No Email Found')
                return redirect(f'Test_ChangePass/{token}/')

            if new_password != confirm_password:
                messages.error(request,'The passwords must be equal')
                return redirect(f'Test_ChangePass/{token}/')

            user_obj = User.objects.get(id = user_id)
            user_obj.set_password(new_password)
            user_obj.save()
            return redirect('login')

        context = {'user_id' : Profile_obj.user.id}
    except Exception as e:
        print(e)
    return render(request, 'user/Test_ChangePass.html', context)

helper.py :

from django.core.mail import send_mail
import uuid
from django.conf import settings
def send_forget_password_mail(email,token):
    subject = 'You forget password link'
    message = f'Hi, Click on the link to reset your password http://127.0.0.1:8000/Test_ChangePass/{token}/'
    email_from = settings.EMAIL_HOST_USER
    recipient_list = [email]
    send_mail(subject, message, email_from,recipient_list)
    return True

ResetPassword.html

{% if messages %}
{% for message in messages %}

        {{message}}

{% endfor %}
{% endif %}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" charset="UTF-8">

        <form method="post"  class="login-form" id="form">
            {% csrf_token %}

                Email
                <input type="text" name="email" id="email"  >
                     {{form.email}}
                    {{form.email.errors}}

<input class="submit-button" type="submit" value="Send">

         </form>

        {% endblock %}

Test_ChangePass.html:

{% if messages %}
{% for message in messages %}

        {{message}}

{% endfor %}
{% endif %}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" charset="UTF-8">

Change Password/h1>
        <form method="POST" class="register-form">
            {% csrf_token %}

                Password1:

                {{form.password1}}
                {{form.password1.errors}}

                Confirem Password
                {{form.password2}}
                {{form.password2.errors}}

            {% if form.non_field_errors %}

                {{form.non_field_errors.as_ul}}

            {% endif %}

            <input type="hidden" name="user_id" value="{{user_id}}" >

            <input type="submit" value="Reset" class="submit-button">

        </form>

{% endblock %}

**No forms.py for the ResetPassword.html and TestChangePass.html
**


问:
how to introduce a new version / different logic for ActionFilter in c#
I am trying to change the way our existing c# application handles security.  The end result is that a we will use a new "user" object that looks different from the current user object we have.  But we want to introduce this user model in a way that won't break existing code.  Until we finish migrating all our old code, we will have 2 ways of handling security / determining what functionality a user is allowed to access.

How the Code Works Today

As a part of our authentication process, when a user logs in, we load a their profile from our database, and this profile includes a list of application permissions.

Here's a sample controller that would trigger the security logic:

```<code>    [Route("me/permissions")]
    [HttpGet]
    [SecuredEndpoint(WidgetAppPermissions.General)]
    public string DoSomethingAmazing(GetAmazingDataRequest request)
    {
        try
        {
            var x = someAmazingObject.DoSomething()
            return JsonConvert.SerializeObject(x);
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }
</code>```

This is what the GetAmazingDataRequest class looks like:

```<code>    public class GetAmazingDataRequest : Request
    {

    }
</code>```

And the logic behind the SecuredEndpoint attribute looks like this: (note: it's a public sealed class)

```<code> public sealed class SecuredEndpointAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    private readonly WidgetAppPermissions[] functions;

    public SecuredEndpointAttribute(params WidgetAppPermissions[] functions)
    {
        this.functions = functions;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {

        //it's inside this method that eventually we call GetUserProfile to load the user
          profile from the database, including the list of permissions.

        var user = userRepo.GetUserProfile(context.HttpContext.User);
</code>```

The idea is that the OnActionExecuting() logic checks the user's profile that was retrieved from the database to ensure that he / she has, in this case, a permission called "General" included in their profile.  If they do, then the execution returns and the system actually tries the logic inside the DoSomethingAmazing() method.

What I Tried

The system runs the SecuredEndPoint attribute logic before actually running the logic inside the DoSomethingAmazing().  But while debugging I noticed that the name of the request class is included inside the "context" object that's passed into OnActionExecuting()

So I was thinking that for each method in any controller that we want to 'migrate', we could change the request object to include a new property like

```<code>    public class Request
    {
       public virtual bool securityVersionBeta {get; set;} = false;
    }

    public class GetAmazingDataRequest : Request
    {
       public virtual bool securityVersionBeta {get; set;} = true;
    }
</code>```

And then I can hijack the existing OnActionExecuting to include a new check:

```<code>    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (((GetAmazingDataRequest )context.ActionArguments["Request"]).securityVersionBeta)
        {
            newProfileLogic(context);
        } else
        {
            Originalcode(context);
        }
</code>```

Questions

Do you see anything glaring bad / wrong about this approach?  Is there another approach that would allow us to migrate our code in a piecemeal fashion?
Any other suggestions would also be appreciated.

Body:
I am trying to change the way our existing c# application handles security.  The end result is that a we will use a new "user" object that looks different from the current user object we have.  But we want to introduce this user model in a way that won't break existing code.  Until we finish migrating all our old code, we will have 2 ways of handling security / determining what functionality a user is allowed to access.

How the Code Works Today

As a part of our authentication process, when a user logs in, we load a their profile from our database, and this profile includes a list of application permissions.

Here's a sample controller that would trigger the security logic:

    [Route("me/permissions")]
    [HttpGet]
    [SecuredEndpoint(WidgetAppPermissions.General)]
    public string DoSomethingAmazing(GetAmazingDataRequest request)
    {
        try
        {
            var x = someAmazingObject.DoSomething()
            return JsonConvert.SerializeObject(x);
        }
        catch (Exception ex)
        {
            return ex.Message.ToString();
        }
    }

This is what the GetAmazingDataRequest class looks like:

    public class GetAmazingDataRequest : Request
    {

    }

And the logic behind the SecuredEndpoint attribute looks like this: (note: it's a public sealed class)

 public sealed class SecuredEndpointAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    private readonly WidgetAppPermissions[] functions;

    public SecuredEndpointAttribute(params WidgetAppPermissions[] functions)
    {
        this.functions = functions;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {

        //it's inside this method that eventually we call GetUserProfile to load the user
          profile from the database, including the list of permissions.

        var user = userRepo.GetUserProfile(context.HttpContext.User);

The idea is that the OnActionExecuting() logic checks the user's profile that was retrieved from the database to ensure that he / she has, in this case, a permission called "General" included in their profile.  If they do, then the execution returns and the system actually tries the logic inside the DoSomethingAmazing() method.

What I Tried

The system runs the SecuredEndPoint attribute logic before actually running the logic inside the DoSomethingAmazing().  But while debugging I noticed that the name of the request class is included inside the "context" object that's passed into OnActionExecuting()

So I was thinking that for each method in any controller that we want to 'migrate', we could change the request object to include a new property like

    public class Request
    {
       public virtual bool securityVersionBeta {get; set;} = false;
    }

    public class GetAmazingDataRequest : Request
    {
       public virtual bool securityVersionBeta {get; set;} = true;
    }

And then I can hijack the existing OnActionExecuting to include a new check:

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (((GetAmazingDataRequest )context.ActionArguments["Request"]).securityVersionBeta)
        {
            newProfileLogic(context);
        } else
        {
            Originalcode(context);
        }

Questions

Do you see anything glaring bad / wrong about this approach?  Is there another approach that would allow us to migrate our code in a piecemeal fashion?
Any other suggestions would also be appreciated.


问:
using https://developer.apple.com/forums/thread/691304 to try to integrate Mac M1 gpu into tensor flow
My constant problem is that I am using the apple recommended way to get 'Get started with tensorflow-metal'. My problem is always in the same place no matter which method I try- I have the same problem:

PackagesNotFoundError: The following packages are not available from current channels:

tensorflow-deps

I can't seem to get arounf this despite using Anaconda 2022.3.1. Can someone suggest a way to get around this? Or can someone suggest a completely new starting point


问:
How to run animation.Funcanimation in an asyncio task?
I'm a beginner, so please be patient and don't downgrade my question and help me ;-)
I want to start my Scatterplot -  animation.FuncAnimation in an asyncio task
I didn't knew how to directly start it via loop.create.task so I started a function that calls the animate-function, which draws the plot.
How to make this code easier? I need something like:
loop.create_task(self.ani = animation.FuncAnimation(self.figure, self.animate, interval=1000)), which doesn't work obviously

My biggest problem is the freezing of the GUI after some time

THANK YOU!

```<code>class MainWin(tk.Tk):

    def __init__(self, loop, interv=1/120):

        super().__init__()
        self.tasks = []
        self.loop = loop
        self.tasks.append(self.loop.create_task(self.subs(interv)))
        self.tasks.append(loop.create_task(self.updater(interv)))
        [...more code...]

        self.tasks.append(loop.create_task(self.animation_starter()))

     async def animation_starter(self,interv):

         self.ani = animation.FuncAnimation(self.figure, self.animate, interval=1000)
         await asyncio.sleep(interv)

     def animate(self,interval):
       [...plot Scatterplot...]

     async def updater(self, interv):
        while True:
            self.update()
            await asyncio.sleep(interv)

     async def subs(self,interv):
       while await asyncio.sleep(interv, True):
            [...do stuff...]

def main():

  loop = asyncio.get_event_loop()
  app = MainWin(loop)
  loop.run_forever()
  loop.close()

if __name__ == '__main__':
    main()
</code>```

What did you try and what were you expecting?

I want to run my animation.Funcanimation in an asyncio-task to avoid freezing of the GUI

Body:
I'm a beginner, so please be patient and don't downgrade my question and help me ;-)
I want to start my Scatterplot -  animation.FuncAnimation in an asyncio task
I didn't knew how to directly start it via loop.create.task so I started a function that calls the animate-function, which draws the plot.
How to make this code easier? I need something like:
loop.create_task(self.ani = animation.FuncAnimation(self.figure, self.animate, interval=1000)), which doesn't work obviously

My biggest problem is the freezing of the GUI after some time

THANK YOU!

class MainWin(tk.Tk):

    def __init__(self, loop, interv=1/120):

        super().__init__()
        self.tasks = []
        self.loop = loop
        self.tasks.append(self.loop.create_task(self.subs(interv)))
        self.tasks.append(loop.create_task(self.updater(interv)))
        [...more code...]

        self.tasks.append(loop.create_task(self.animation_starter()))

     async def animation_starter(self,interv):

         self.ani = animation.FuncAnimation(self.figure, self.animate, interval=1000)
         await asyncio.sleep(interv)

     def animate(self,interval):
       [...plot Scatterplot...]

     async def updater(self, interv):
        while True:
            self.update()
            await asyncio.sleep(interv)

     async def subs(self,interv):
       while await asyncio.sleep(interv, True):
            [...do stuff...]

def main():

  loop = asyncio.get_event_loop()
  app = MainWin(loop)
  loop.run_forever()
  loop.close()

if __name__ == '__main__':
    main()

What did you try and what were you expecting?

I want to run my animation.Funcanimation in an asyncio-task to avoid freezing of the GUI


问:
How can I make elements show up in a dropdown menu from a firestore database when a certain date is selected?
So I'm working on a booking system project and I have a form that the user can fill out, with a date picker using react-datepicker and a dropdown menu with times that the users can select from. These times are fetched from a firestore database. The times collection looks like this: times collection. I open up the bookings slots for the next 2 weeks, but I want to render the available times from the arrays in each document when that specific date is selected in the react-datepicker component here is my code but it doesn't work, when I select a date, no times for that date show up whereas I want the times from the array from that date to show up. Here is my code:</p>
```<code>  function GThirtyminsp() {
  // Form values
  const [date, setDate] = useState(null);
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [age, setAge] = useState("");
  const [team, setTeam] = useState("");
  const [number, setNumber] = useState("");
  const [time, setTime] = useState("");

  // To show times on screen
  const [times, setTimes] = useState([]);

  const timesRef = collection(db, "30min-goalie-semiprivate-times");
  const formRef = collection(db, "30min-goalie-semiprivate");

  useEffect(() => {
    const fetchData = async () => {
      if (date) {
        const timeData = await query(
          timesRef,
          where("date", "==", date.toISOString().slice(0, 10)),
          orderBy("time", "asc")
        );
        if (timeData.docs) {
          const times = timeData.docs.map((doc) => doc.data().times);
          setTimes(times);
        }
      }
    };
    fetchData();
  }, [timesRef, date]);

  const createBooking = async () => {
    await addDoc(formRef, {
      name: name,
      date: date,
      email: email,
      number: number,
      team: team,
      age: age,
      time: time,
    });
  };

  const addTimesForNextThreeWeeks = async () => {
    // Get current date
    let currentDate = new Date();

    // Check if current day is Monday
    if (currentDate.getDay() === 1) {
      // Set times to generate
      const times = ["09:00", "10:00", "11:00"];

      // Generate times for next three weeks
      for (let i = 0; i < 14; i++) {
        // Format date as string
        const formattedDate = currentDate.toISOString().slice(0, 10);

        // Add the times for this date to the database
        await addDoc(timesRef, {
          date: formattedDate,
          times: times,
        });

        // Increment current date by 1 day
        currentDate.setDate(currentDate.getDate() + 1);
      }
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    createBooking();

    setName("");
    setEmail("");
    setDate(null);
    setNumber("");
    setTeam("");
    setTime(null);
    setAge("");
  };

  return (
    <div>
      <h1 class="text-3xl w-full text-center pt-10 font-bold">
        Book 30min Semi-Private Goalie Clinic
      </h1>
      <div class="flex flex-col items-center">
        <form onSubmit={handleSubmit} class="flex flex-col pt-10 w-3/4">
          <input
            type="text"
            name="name"
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="number"
            placeholder="Phone Number"
            value={number}
            onChange={(e) => setNumber(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="team"
            placeholder="Team Name"
            value={team}
            onChange={(e) => setTeam(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="age"
            placeholder="Age"
            value={age}
            onChange={(e) => setAge(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <h2 class="text-center text-xl py-5 font-bold">
            Pick a Date and Time
          </h2>
          <div class="pb-10">
            <DatePicker
              className="border-2 p-3 w-full border-gray rounded-lg"
              selected={date}
              onChange={(date) => setDate(date)}
              placeholderText="Select a Date"
            />
            <div class="pt-10">
              <Select
                options={times}
                placeholder="Time"
                onChange={(e) => setTime(e.value)}
                value={time}
              />
            </div>
          </div>

          <button
            type="submit"
            class="bg-accent text-white font-semibold p-3 rounded-full"
          >
            Submit
          </button>
        </form>
      </div>
    </div>
  );
}

export default GThirtyminsp;
</code>```

Body:
So I'm working on a booking system project and I have a form that the user can fill out, with a date picker using react-datepicker and a dropdown menu with times that the users can select from. These times are fetched from a firestore database. The times collection looks like this: times collection. I open up the bookings slots for the next 2 weeks, but I want to render the available times from the arrays in each document when that specific date is selected in the react-datepicker component here is my code but it doesn't work, when I select a date, no times for that date show up whereas I want the times from the array from that date to show up. Here is my code:

  function GThirtyminsp() {
  // Form values
  const [date, setDate] = useState(null);
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [age, setAge] = useState("");
  const [team, setTeam] = useState("");
  const [number, setNumber] = useState("");
  const [time, setTime] = useState("");

  // To show times on screen
  const [times, setTimes] = useState([]);

  const timesRef = collection(db, "30min-goalie-semiprivate-times");
  const formRef = collection(db, "30min-goalie-semiprivate");

  useEffect(() => {
    const fetchData = async () => {
      if (date) {
        const timeData = await query(
          timesRef,
          where("date", "==", date.toISOString().slice(0, 10)),
          orderBy("time", "asc")
        );
        if (timeData.docs) {
          const times = timeData.docs.map((doc) => doc.data().times);
          setTimes(times);
        }
      }
    };
    fetchData();
  }, [timesRef, date]);

  const createBooking = async () => {
    await addDoc(formRef, {
      name: name,
      date: date,
      email: email,
      number: number,
      team: team,
      age: age,
      time: time,
    });
  };

  const addTimesForNextThreeWeeks = async () => {
    // Get current date
    let currentDate = new Date();

    // Check if current day is Monday
    if (currentDate.getDay() === 1) {
      // Set times to generate
      const times = ["09:00", "10:00", "11:00"];

      // Generate times for next three weeks
      for (let i = 0; i < 14; i++) {
        // Format date as string
        const formattedDate = currentDate.toISOString().slice(0, 10);

        // Add the times for this date to the database
        await addDoc(timesRef, {
          date: formattedDate,
          times: times,
        });

        // Increment current date by 1 day
        currentDate.setDate(currentDate.getDate() + 1);
      }
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();

    createBooking();

    setName("");
    setEmail("");
    setDate(null);
    setNumber("");
    setTeam("");
    setTime(null);
    setAge("");
  };

  return (

        Book 30min Semi-Private Goalie Clinic

        <form onSubmit={handleSubmit} class="flex flex-col pt-10 w-3/4">
          <input
            type="text"
            name="name"
            placeholder="Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="number"
            placeholder="Phone Number"
            value={number}
            onChange={(e) => setNumber(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="team"
            placeholder="Team Name"
            value={team}
            onChange={(e) => setTeam(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />
          <input
            type="text"
            name="age"
            placeholder="Age"
            value={age}
            onChange={(e) => setAge(e.target.value)}
            class="border-2 p-3 mb-5 border-gray rounded-lg"
          />

            Pick a Date and Time

            <DatePicker
              className="border-2 p-3 w-full border-gray rounded-lg"
              selected={date}
              onChange={(date) => setDate(date)}
              placeholderText="Select a Date"
            />

              <Select
                options={times}
                placeholder="Time"
                onChange={(e) => setTime(e.value)}
                value={time}
              />

          <button
            type="submit"
            class="bg-accent text-white font-semibold p-3 rounded-full"
          >
            Submit
          </button>
        </form>

  );
}

export default GThirtyminsp;


问:
how to disable master username/password access to AWS RDS instance
I have an AWS RDS Instance that has IAM DB authentication enabled, where people can connect to the database via IAM roles as per the instructions at https://aws.amazon.com/premiumsupport/knowledge-center/rds-postgresql-connect-using-iam/. However, I want users to be able to connect to the RDS instance only via IAM roles, and not via the master username/password that was previously used? Is there a way to disable the master username/password, or enforce that people can only access the database via IAM roles?</p>


问:
How to pass object with string type field to arraylist
```<code>public class NewClass {
    ArrayList<stu> m = new ArrayList<>();
    private Scanner sc = new Scanner(System.in);
    public void add(){
        int id = sc.nextInt();
        sc.next();
        String name = sc.nextLine();
        m.add(new stu(id, name));
    }
    public void printList(){
        for(stu i : m){
            System.out.println(i.getId() +" "+i.getName());
        }
    }
}
</code>```

stu class have id is number and name is String.
The 'id' variable is passed to the arraylist but the 'name' variable cannot.
I hope someone can show me how to fix it

Body:
public class NewClass {
    ArrayList<stu> m = new ArrayList<>();
    private Scanner sc = new Scanner(System.in);
    public void add(){
        int id = sc.nextInt();
        sc.next();
        String name = sc.nextLine();
        m.add(new stu(id, name));
    }
    public void printList(){
        for(stu i : m){
            System.out.println(i.getId() +" "+i.getName());
        }
    }
}

stu class have id is number and name is String.
The 'id' variable is passed to the arraylist but the 'name' variable cannot.
I hope someone can show me how to fix it


问:
Find strings even with a possible margin of error in the input
I let the user search elements with a searchbar, elements are strings, if input text query has no match then the user can add a new element with the searched query text. The problem is that if the user misses the input by even one letter then he will add an item that actually already exists. Is there a prebuilt function which chosen a margin of error, finds strings similar to the user input that fall within this margin?

For example:

Elements = [try, code, stackoverflow]

user input "stakoveflow", margin error setted as 2

output -> stackoverflow

user input "stakoveflow", margin error setted as 1

output -> ""


问:
How to merge two lists by alternating elements from both lists?
I want to merge two lists but in between each other. For example.

```<code>char = ["A", "B", "C", "D", "E", "F", "G"]
num = ["1", "2", "3", "4", "5", "6", "7"]
</code>```

I want to have the results as following

```<code>result = ["A", "1", "B", "2", "C", "3", "D", "4", "E", "5", "F", "6", "G", "7"]
</code>```

Body:
I want to merge two lists but in between each other. For example.

char = ["A", "B", "C", "D", "E", "F", "G"]
num = ["1", "2", "3", "4", "5", "6", "7"]

I want to have the results as following

result = ["A", "1", "B", "2", "C", "3", "D", "4", "E", "5", "F", "6", "G", "7"]


问:
How to create a partial view of an external page
I have a question about how to create a partial view of an external page, for example, Google's in C# .NET Core.

What I want is like the iframe that loads an external page but the iframe is not allowed to be used in the company.

I already tried with

```<code>await Html.RenderPartial("_AuthorPartial");
</code>```

and it didn't work for me

Body:
I have a question about how to create a partial view of an external page, for example, Google's in C# .NET Core.

What I want is like the iframe that loads an external page but the iframe is not allowed to be used in the company.

I already tried with

await Html.RenderPartial("_AuthorPartial");

and it didn't work for me


问:
How to add shadow or border on donut chart using Chartist
I am using a Chartist chart for showing data. I want to add a shadow on the selected slice of the chart on hover or mouse enter event. Attache below screenshot for the output

enter image description here

Attache below screenshot for the output

enter image description here


问:
Cannot select and update record in the same transaction
I use webflux + spring data and in the same transaction, I'm trying to fetch data and update in the same transaction. On userPrivilegesRepository::saveAll execution stops. That works on H2 database, but does not work on postgres database.

```<code>    @Transactional
    public Flux<Void> syncUsersWithPrivileges() {
        return userDetailsRepository.findUserWithoutPrivileges()
                .doOnNext(it -> log.info("Syncing users without privileges: id {}", it.getId()))
                .concatMap(this::createUserPrivileges)
                .buffer(BATCH_SIZE)
                .doOnNext(it -> log.info("Update complete for batch users size {}", it.size()))
                .flatMap(it -> Mono.empty());
    }

    public Mono<UserEntity> createUserPrivileges(UserEntity user) {
        return Flux.fromIterable(Privileges.jobSeeker())
                .map(it -> UserPrivilegesEntity.builder()
                        .privilegesId(it)
                        .userId(user.getId())
                        .id(user.getId() + "-" + it.name())
                        .isNew(true).build())
                .collectList()
                .flatMapMany(userPrivilegesRepository::saveAll)
                .then(Mono.just(user));
    }
</code>```

the repository

```<code>    @Query("select u.* from users as u left join user_privileges as up ON up.user_id = u.id\n"
            + "where up.user_id is null")
    Flux<UserEntity> findUserWithoutPrivileges();
</code>```

If I remove @Transactional annotation everything works fine. Any thoughts on that?

Body:
I use webflux + spring data and in the same transaction, I'm trying to fetch data and update in the same transaction. On userPrivilegesRepository::saveAll execution stops. That works on H2 database, but does not work on postgres database.

    @Transactional
    public Flux<Void> syncUsersWithPrivileges() {
        return userDetailsRepository.findUserWithoutPrivileges()
                .doOnNext(it -> log.info("Syncing users without privileges: id {}", it.getId()))
                .concatMap(this::createUserPrivileges)
                .buffer(BATCH_SIZE)
                .doOnNext(it -> log.info("Update complete for batch users size {}", it.size()))
                .flatMap(it -> Mono.empty());
    }

    public Mono<UserEntity> createUserPrivileges(UserEntity user) {
        return Flux.fromIterable(Privileges.jobSeeker())
                .map(it -> UserPrivilegesEntity.builder()
                        .privilegesId(it)
                        .userId(user.getId())
                        .id(user.getId() + "-" + it.name())
                        .isNew(true).build())
                .collectList()
                .flatMapMany(userPrivilegesRepository::saveAll)
                .then(Mono.just(user));
    }

the repository

    @Query("select u.* from users as u left join user_privileges as up ON up.user_id = u.id\n"
            + "where up.user_id is null")
    Flux<UserEntity> findUserWithoutPrivileges();

If I remove @Transactional annotation everything works fine. Any thoughts on that?


问:
how to get files built in vscode extension using webpack with vscode-webview-ui-toolkit
We have using @vscode/webview-ui-toolkit and it works when we are testing. But we set up the webpack version of the extension. When we package and run the extension, we are missing the toolkit and our other files. Errors like

```<code>Error: Unable to read file '/Users/jkh/.vscode/extensions/ext-0.0.2/node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js' (Error: Unable to resolve nonexistent file '/Users/jkh/.vscode/extensions/ext-0.0.2/node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js')
</code>```

and also the webpage src/newExtensionWizard/main.js and css src/newExtensionWizard/style.css.

Am I right that this is an issue with our webpack? Or why can we get webview-ui-toolkit to work under development but not through the vsix file?

Body:
We have using @vscode/webview-ui-toolkit and it works when we are testing. But we set up the webpack version of the extension. When we package and run the extension, we are missing the toolkit and our other files. Errors like

Error: Unable to read file '/Users/jkh/.vscode/extensions/ext-0.0.2/node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js' (Error: Unable to resolve nonexistent file '/Users/jkh/.vscode/extensions/ext-0.0.2/node_modules/@vscode/webview-ui-toolkit/dist/toolkit.js')

and also the webpage src/newExtensionWizard/main.js and css src/newExtensionWizard/style.css.

Am I right that this is an issue with our webpack? Or why can we get webview-ui-toolkit to work under development but not through the vsix file?


问:
Is L1-L2 cache in Hibernate is same as L1-L2 caches in CPU?
Related to the question in the title, my second question is:

I've seen somebody saying that Hibernate caching happens in the RAM. So if the first question is right, then is that statement false?

Thank you for the answers.


Title: Multiple numpy arrays to pyspark dataframe

Body:
I have three numpy array with following shape:

a: (7981112,1) b:(7981112, 512) c:(7981112, 512)

Out:
a:
array([688743769, 545912053, 808469048, 461771194, 530236220])

b:
array([[1323918997, 1065153327, 1454490576, ..., 1621399393, 1493357579,
        1173145058],
       [1035213154, 1346101646, 1289847510, ..., 1692153971, 1150495270,
        1409599713],
       [1116144235, 1267744472, 1183898555, ..., 1759829995, 1231069117,
        1975723915],
       ...,
       [1570211637, 1164654960, 1599919000, ..., 1698202029, 1358765977,
        1739904259],
       [1014660033, 1821178091, 1413697040, ..., 1573689035, 1642503461,
        1621724954],
       [1131806805, 1853176501, 1981513805, ..., 1250190178, 1143342728,
        1590477729]])

c:
array([[1.2421567 , 1.2582937 , 1.2679486 , ..., 1.5837815 , 1.5837815 ,
        1.5841558 ],
       [0.46870112, 0.46870112, 0.5081928 , ..., 0.82052135, 0.82052135,
        0.82052135],
       [1.0426544 , 1.0426544 , 1.0426544 , ..., 1.437469  , 1.4375292 ,
        1.4378369 ],
       ...,
       [0.9572059 , 0.9649285 , 0.97881615, ..., 1.3755796 , 1.3759067 ,
        1.3759067 ],
       [0.84625053, 0.88099194, 0.93783414, ..., 1.3557749 , 1.3564951 ,
        1.356785  ],
       [0.4750075 , 0.5645814 , 0.5645814 , ..., 0.8574506 , 0.85773677,
        0.85773677]], dtype=float32)

Now I want to create spark dataframe with 7981112 rows, 3 columns, where first row will have single value from a, 2nd row will array of shape(512,) from b and third column will have same shape array from c.

In pandas I did following and it worked, but I cannot convert to pandas and then pyspark as it'll take lot of memory:

pd.DataFrame([a, b, c]], index = ['a', 'b', 'c']).T

Expected Out:

a                                b                                             c
688743769   [1.2421567, 1.2582937, 1.2679486, 1.2679486, 1...   [1323918997, 1065153327, 1454490576, 119357402...
545912053   [0.46870112, 0.46870112, 0.5081928, 0.50944287...   [1035213154, 1346101646, 1289847510, 125282344...
808469048   [1.0426544, 1.0426544, 1.0426544, 1.0583999, 1...   [1116144235, 1267744472, 1183898555, 112992817...
461771194   [0.66322315, 0.67969656, 0.69165784, 0.6916578...   [1089704317, 1131806805, 1573565029, 193765644...
530236220   [1.1247283, 1.1247283, 1.130106, 1.1571715, 1....   [1611450197, 1494898734, 1767275624, 107101289...


问:
Fullcalendar in angular problem with print of multiple events
I have an angular 14 application with fullcalendar. If I have a lot of events in my calendar and I try to print it, the print looks like this :

First page:

Second page:

Here are the events on my calendar:

Does anyone know what might be the problem ?

Here is my package.json

```<code>    {
      "name": "pilotage",
      "version": "1.10.0",
      "scripts": {
        "start": "npm run init-version && ng serve",
        "start-local": "npm run init-version && ng serve",
        "init-version": "node -e \"console.log('export const APP_VERSION = \\'' + process.env.npm_package_version +'\\';')\" > ./src/app/version.ts",
        "build": "node --max_old_space_size=4092 \"node_modules/@angular/cli/bin/ng\" build --configuration production --configuration=production",
        "bundle-all": "node bundle-all.js",
        "lint": "ng lint",
        "e2e": "ng e2e",
        "test": "ng test --browsers Chrome",
        "coverage": "ng test --code-coverage=true --browsers Chrome",
        "set-node": "nvm use 12.4.0",
        "msvs": "npm config set msvs_version 2017",
        "memory": "node --max_old_space_size=8192",
        "postinstall": "ngcc"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "14.2.12",
        "@angular/cdk": "14.2.1",
        "@angular/common": "14.2.12",
        "@angular/compiler": "14.2.12",
        "@angular/core": "14.2.12",
        "@angular/elements": "14.2.12",
        "@angular/flex-layout": "^14.0.0-beta.41",
        "@angular/forms": "14.2.12",
        "@angular/localize": "14.2.12",
        "@angular/platform-browser": "14.2.12",
        "@angular/platform-browser-dynamic": "14.2.12",
        "@angular/router": "14.2.12",
        "@angular/service-worker": "14.2.12",
        "@auth0/angular-jwt": "5.0.2",
        "@formio/angular": "^5.3.0",
        "@fullcalendar/adaptive": "6.0.1",
        "@fullcalendar/angular": "6.0.1",
        "@fullcalendar/core": "6.0.1",
        "@fullcalendar/daygrid": "6.0.1",
        "@fullcalendar/interaction": "6.0.0",
        "@fullcalendar/moment": "6.0.0",
        "@fullcalendar/moment-timezone": "6.0.0",
        "@fullcalendar/resource": "^6.0.0",
        "@fullcalendar/resource-timeline": "6.0.0",
        "@fullcalendar/rrule": "6.0.0",
        "@fullcalendar/timegrid": "6.0.0",
        "@ng-bootstrap/ng-bootstrap": "^14.0.0",
        "@popperjs/core": "^2.11.2",
        "@ng-select/ng-select": "^9.0.0",
        "@ngx-translate/core": "12.1.1",
        "@ngx-translate/http-loader": "4.0.0",
        "@swimlane/ngx-datatable": "^20.1.0",
        "@types/quill": "^1.3.10",
        "admin-lte": "2.3.8",
        "angular-pipes": "^10.0.0",
        "angular2-logger": "^0.7.0",
        "bootstrap": "3.4.1",
        "bootstrap-datepicker": "1.9.0",
        "bootstrap3-wysihtml5-bower": "0.3.3",
        "chart.js": "4.0.1",
        "class-validator": "0.11.0",
        "daterangepicker": "3.0.5",
        "exceljs": "4.1.1",
        "fastclick": "1.0.6",
        "file-saver": "2.0.2",
        "formio-export-mc": "0.3.32",
        "formiojs": "4.12.7",
        "html2canvas": "1.0.0-rc.5",
        "html2pdf.js": "^0.9.2",
        "i": "0.3.7",
        "jQuery.print": "1.5.1",
        "jquery": "3.6.2",
        "jquery-knob": "1.2.11",
        "jquery-slimscroll": "1.3.8",
        "jquery-sparkline": "2.4.0",
        "lodash": "4.17.21",
        "lodash-es": "^4.17.21",
        "moment": "2.29.4",
        "moment-timezone": "0.5.27",
        "ng-drag-drop": "^5.0.0",
        "ng2-date-picker": "^15.0.1",
        "ng2-file-upload": "1.4.0",
        "ng2-pdf-viewer": "^6.4.0",
        "ng2-timezone-selector": "0.2.4",
        "ngx-accordion": "^0.0.17",
        "ngx-bootstrap": "10.0.0",
        "ngx-datatable": "^1.0.3",
        "ngx-filesize": "2.0.2",
        "ngx-image-cropper": "3.0.3",
        "ngx-infinite-scroll": "8.0.1",
        "ngx-pagination": "5.0.0",
        "ngx-print": "^1.2.1",
        "ngx-quill": "17.0.0",
        "ngx-select-dropdown": "3.2.0",
        "ngx-time-duration-picker": "^2.0.3",
        "ngx-toastr": "13.2.1",
        "ngx-tooltip": "^0.0.9",
        "ngx-ui-switch": "^14.0.3",
        "ngx-webstorage-service": "4.1.0",
        "quill": "1.3.7",
        "quill-image-resize-module": "3.0.0",
        "rrule": "2.6.4",
        "rxjs": "6.5.4",
        "select2": "4.0.13",
        "timepicker": "1.13.0",
        "xlsx": "^0.16.0",
        "yiq": "3.0.1",
        "zone.js": "~0.11.4"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~14.2.10",
        "@angular-devkit/core": "^14.2.10",
        "@angular-devkit/schematics": "^14.2.10",
        "@angular/cli": "^14.2.10",
        "@angular/compiler-cli": "14.2.12",
        "@angular/language-service": "14.2.12",
        "@types/core-js": "2.5.2",
        "@types/events": "^3.0.0",
        "@types/file-saver": "2.0.1",
        "@types/jasmine": "~3.6.0",
        "@types/jasminewd2": "2.0.6",
        "@types/jquery": "3.3.32",
        "@types/moment": "2.13.0",
        "@types/node": "^12.11.1",
        "codelyzer": "^6.0.0",
        "jasmine-core": "~3.6.0",
        "jasmine-spec-reporter": "~5.0.0",
        "karma": "~6.3.1",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage-istanbul-reporter": "~3.0.2",
        "karma-jasmine": "~4.0.0",
        "karma-jasmine-html-reporter": "^1.5.0",
        "prettier": "^2.4.1",
        "protractor": "~7.0.0",
        "sass-material-colors": "0.0.5",
        "ts-node": "8.6.2",
        "tslib": "^2.4.1",
        "tslint": "~6.1.0",
        "typescript": "4.6.4"
      }
    }

</code>```

Also this is the configuration for my full calendar that I use :

```<code>  this.options = {
      editable: !this.isBusy,
      events: this.eventsModel,
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridThreeDays,timeGridDay',
      },
      height: this.maxHeight,
      droppable: true,
      dayMaxEventRows: 3,
      dayMaxEvents: 4,
      firstDay: this.firstDay,
      snapDuration: {
        minutes: 15,
      },
      selectable: true,
      timeZone: this.timeZone,
      dateClick: this._dateClick,
      datesSet: this._datesRender,
      drop: this._drop,
      eventClick: this._eventClick,
      eventDidMount: this._eventDidMount,
      eventDragStart: this._eventDragStart,
      eventDragStop: this._eventDragStop,
      eventDrop: this._eventDrop,
      eventResize: this._eventResize,
      eventResizeStart: this._eventResizeStart,
      select: this._select,
      schedulerLicenseKey: this.schedulerLicenseKey,
      initialView: 'timeGridWeek',
      nowIndicator: true,
      locales: [frLocale],
      locale: utils.getCurrentLang(),
      views: {
        timeGridThreeDays: {
          type: 'timeGrid',
          duration: { days: 3 },
          buttonText: this.translateService.instant(constants.AGENDA_CUSTOMVIEWS_TIMEGRIDTHREEDAYS),
        },
      },
      eventTimeFormat: {
        hour: 'numeric',
        minute: '2-digit',
      },
      plugins: [
        dayGridPlugin,
        timeGridPlugin,
        interactionPlugin,
        momentPlugin,
        momentTimezonePlugin,
        rrulePlugin,
        adaptivePlugin,
      ],
    };
</code>```

Body:
I have an angular 14 application with fullcalendar. If I have a lot of events in my calendar and I try to print it, the print looks like this :

First page:

Second page:

Here are the events on my calendar:

Does anyone know what might be the problem ?

Here is my package.json

    {
      "name": "pilotage",
      "version": "1.10.0",
      "scripts": {
        "start": "npm run init-version && ng serve",
        "start-local": "npm run init-version && ng serve",
        "init-version": "node -e \"console.log('export const APP_VERSION = \\'' + process.env.npm_package_version +'\\';')\" > ./src/app/version.ts",
        "build": "node --max_old_space_size=4092 \"node_modules/@angular/cli/bin/ng\" build --configuration production --configuration=production",
        "bundle-all": "node bundle-all.js",
        "lint": "ng lint",
        "e2e": "ng e2e",
        "test": "ng test --browsers Chrome",
        "coverage": "ng test --code-coverage=true --browsers Chrome",
        "set-node": "nvm use 12.4.0",
        "msvs": "npm config set msvs_version 2017",
        "memory": "node --max_old_space_size=8192",
        "postinstall": "ngcc"
      },
      "private": true,
      "dependencies": {
        "@angular/animations": "14.2.12",
        "@angular/cdk": "14.2.1",
        "@angular/common": "14.2.12",
        "@angular/compiler": "14.2.12",
        "@angular/core": "14.2.12",
        "@angular/elements": "14.2.12",
        "@angular/flex-layout": "^14.0.0-beta.41",
        "@angular/forms": "14.2.12",
        "@angular/localize": "14.2.12",
        "@angular/platform-browser": "14.2.12",
        "@angular/platform-browser-dynamic": "14.2.12",
        "@angular/router": "14.2.12",
        "@angular/service-worker": "14.2.12",
        "@auth0/angular-jwt": "5.0.2",
        "@formio/angular": "^5.3.0",
        "@fullcalendar/adaptive": "6.0.1",
        "@fullcalendar/angular": "6.0.1",
        "@fullcalendar/core": "6.0.1",
        "@fullcalendar/daygrid": "6.0.1",
        "@fullcalendar/interaction": "6.0.0",
        "@fullcalendar/moment": "6.0.0",
        "@fullcalendar/moment-timezone": "6.0.0",
        "@fullcalendar/resource": "^6.0.0",
        "@fullcalendar/resource-timeline": "6.0.0",
        "@fullcalendar/rrule": "6.0.0",
        "@fullcalendar/timegrid": "6.0.0",
        "@ng-bootstrap/ng-bootstrap": "^14.0.0",
        "@popperjs/core": "^2.11.2",
        "@ng-select/ng-select": "^9.0.0",
        "@ngx-translate/core": "12.1.1",
        "@ngx-translate/http-loader": "4.0.0",
        "@swimlane/ngx-datatable": "^20.1.0",
        "@types/quill": "^1.3.10",
        "admin-lte": "2.3.8",
        "angular-pipes": "^10.0.0",
        "angular2-logger": "^0.7.0",
        "bootstrap": "3.4.1",
        "bootstrap-datepicker": "1.9.0",
        "bootstrap3-wysihtml5-bower": "0.3.3",
        "chart.js": "4.0.1",
        "class-validator": "0.11.0",
        "daterangepicker": "3.0.5",
        "exceljs": "4.1.1",
        "fastclick": "1.0.6",
        "file-saver": "2.0.2",
        "formio-export-mc": "0.3.32",
        "formiojs": "4.12.7",
        "html2canvas": "1.0.0-rc.5",
        "html2pdf.js": "^0.9.2",
        "i": "0.3.7",
        "jQuery.print": "1.5.1",
        "jquery": "3.6.2",
        "jquery-knob": "1.2.11",
        "jquery-slimscroll": "1.3.8",
        "jquery-sparkline": "2.4.0",
        "lodash": "4.17.21",
        "lodash-es": "^4.17.21",
        "moment": "2.29.4",
        "moment-timezone": "0.5.27",
        "ng-drag-drop": "^5.0.0",
        "ng2-date-picker": "^15.0.1",
        "ng2-file-upload": "1.4.0",
        "ng2-pdf-viewer": "^6.4.0",
        "ng2-timezone-selector": "0.2.4",
        "ngx-accordion": "^0.0.17",
        "ngx-bootstrap": "10.0.0",
        "ngx-datatable": "^1.0.3",
        "ngx-filesize": "2.0.2",
        "ngx-image-cropper": "3.0.3",
        "ngx-infinite-scroll": "8.0.1",
        "ngx-pagination": "5.0.0",
        "ngx-print": "^1.2.1",
        "ngx-quill": "17.0.0",
        "ngx-select-dropdown": "3.2.0",
        "ngx-time-duration-picker": "^2.0.3",
        "ngx-toastr": "13.2.1",
        "ngx-tooltip": "^0.0.9",
        "ngx-ui-switch": "^14.0.3",
        "ngx-webstorage-service": "4.1.0",
        "quill": "1.3.7",
        "quill-image-resize-module": "3.0.0",
        "rrule": "2.6.4",
        "rxjs": "6.5.4",
        "select2": "4.0.13",
        "timepicker": "1.13.0",
        "xlsx": "^0.16.0",
        "yiq": "3.0.1",
        "zone.js": "~0.11.4"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~14.2.10",
        "@angular-devkit/core": "^14.2.10",
        "@angular-devkit/schematics": "^14.2.10",
        "@angular/cli": "^14.2.10",
        "@angular/compiler-cli": "14.2.12",
        "@angular/language-service": "14.2.12",
        "@types/core-js": "2.5.2",
        "@types/events": "^3.0.0",
        "@types/file-saver": "2.0.1",
        "@types/jasmine": "~3.6.0",
        "@types/jasminewd2": "2.0.6",
        "@types/jquery": "3.3.32",
        "@types/moment": "2.13.0",
        "@types/node": "^12.11.1",
        "codelyzer": "^6.0.0",
        "jasmine-core": "~3.6.0",
        "jasmine-spec-reporter": "~5.0.0",
        "karma": "~6.3.1",
        "karma-chrome-launcher": "~3.1.0",
        "karma-coverage-istanbul-reporter": "~3.0.2",
        "karma-jasmine": "~4.0.0",
        "karma-jasmine-html-reporter": "^1.5.0",
        "prettier": "^2.4.1",
        "protractor": "~7.0.0",
        "sass-material-colors": "0.0.5",
        "ts-node": "8.6.2",
        "tslib": "^2.4.1",
        "tslint": "~6.1.0",
        "typescript": "4.6.4"
      }
    }

Also this is the configuration for my full calendar that I use :

  this.options = {
      editable: !this.isBusy,
      events: this.eventsModel,
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridThreeDays,timeGridDay',
      },
      height: this.maxHeight,
      droppable: true,
      dayMaxEventRows: 3,
      dayMaxEvents: 4,
      firstDay: this.firstDay,
      snapDuration: {
        minutes: 15,
      },
      selectable: true,
      timeZone: this.timeZone,
      dateClick: this._dateClick,
      datesSet: this._datesRender,
      drop: this._drop,
      eventClick: this._eventClick,
      eventDidMount: this._eventDidMount,
      eventDragStart: this._eventDragStart,
      eventDragStop: this._eventDragStop,
      eventDrop: this._eventDrop,
      eventResize: this._eventResize,
      eventResizeStart: this._eventResizeStart,
      select: this._select,
      schedulerLicenseKey: this.schedulerLicenseKey,
      initialView: 'timeGridWeek',
      nowIndicator: true,
      locales: [frLocale],
      locale: utils.getCurrentLang(),
      views: {
        timeGridThreeDays: {
          type: 'timeGrid',
          duration: { days: 3 },
          buttonText: this.translateService.instant(constants.AGENDA_CUSTOMVIEWS_TIMEGRIDTHREEDAYS),
        },
      },
      eventTimeFormat: {
        hour: 'numeric',
        minute: '2-digit',
      },
      plugins: [
        dayGridPlugin,
        timeGridPlugin,
        interactionPlugin,
        momentPlugin,
        momentTimezonePlugin,
        rrulePlugin,
        adaptivePlugin,
      ],
    };


问:
How to save a Bitmap as a PNG File with transparency
I'm working on an Android App written in Kotlin. I need a function that takes a Bitmap and saves it as a PNG File in a variable path because I need a mask. The problem is that my current code doesn't seem to have transparency. If I set my bitmap to an ImageView it has a transparent background, but when I see the created File it's black

This is how I mask the original Bitmap:

```<code>    private fun maskImage(points: List<PointF>, bitmap: Bitmap){
        val maskedBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
        val canvas = Canvas(maskedBitmap)

        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.TRANSPARENT
        paint.style = Paint.Style.FILL
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

        //Create the path and set the starting point
        val path = Path()
        path.moveTo(points[0].x, points[0].y)

        for (point in points){
            Log.i("Point", "$point.x}, ${point.y}")
            path.lineTo(point.x, point.y)
        }

        path.close()
        path.fillType = Path.FillType.INVERSE_WINDING
        canvas.drawPath(path, paint)

        imageBitmap.value = maskedBitmap
        val maskFile = fileFromBitmap(maskedBitmap)
    }
</code>```

And this is my failed solution:

```<code>    private fun fileFromBitmap(bitmap: Bitmap): File?{
        return try {
            val maskFile = File(
                Environment.getExternalStorageDirectory().toString() + "/Pictures/AppName",            "mask.png")
            val outputStream = FileOutputStream(maskFile)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            //outputStream.flush()
            outputStream.close()
            Log.e("Status", "Mask saved successfully")
            maskFile
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            Log.e("Status", "Save file error!")
            null
        }
    }
</code>```

Body:
I'm working on an Android App written in Kotlin. I need a function that takes a Bitmap and saves it as a PNG File in a variable path because I need a mask. The problem is that my current code doesn't seem to have transparency. If I set my bitmap to an ImageView it has a transparent background, but when I see the created File it's black

This is how I mask the original Bitmap:

    private fun maskImage(points: List<PointF>, bitmap: Bitmap){
        val maskedBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
        val canvas = Canvas(maskedBitmap)

        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.TRANSPARENT
        paint.style = Paint.Style.FILL
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

        //Create the path and set the starting point
        val path = Path()
        path.moveTo(points[0].x, points[0].y)

        for (point in points){
            Log.i("Point", "$point.x}, ${point.y}")
            path.lineTo(point.x, point.y)
        }

        path.close()
        path.fillType = Path.FillType.INVERSE_WINDING
        canvas.drawPath(path, paint)

        imageBitmap.value = maskedBitmap
        val maskFile = fileFromBitmap(maskedBitmap)
    }

And this is my failed solution:

    private fun fileFromBitmap(bitmap: Bitmap): File?{
        return try {
            val maskFile = File(
                Environment.getExternalStorageDirectory().toString() + "/Pictures/AppName",            "mask.png")
            val outputStream = FileOutputStream(maskFile)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            //outputStream.flush()
            outputStream.close()
            Log.e("Status", "Mask saved successfully")
            maskFile
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            Log.e("Status", "Save file error!")
            null
        }
    }