问:
Next-firebase-auth causing endless loop
I have the following setup using Next-firebase-auth:

Login page:

```<code>import {
  AuthAction,
  withAuthUser,
  withAuthUserSSR,
  withAuthUserTokenSSR,
} from "next-firebase-auth";
import { FormProvider, useForm } from "react-hook-form";

import Link from "next/link";
import { MoonLoader } from "react-spinners";
import PageHead from "../components/PageHead";
import { auth } from "../config/firebase";
import { signInWithEmailAndPassword } from "firebase/auth";
import { useRouter } from "next/router";
import { useState } from "react";

interface LoginType {
  email: string;
  password: string;
}
const LoginPage = () => {
  const methods = useForm<LoginType>({ mode: "onBlur" });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = methods;

  const onSubmit = async (data: LoginType) => {
    try {
      setLoading(true);
      const { email, password } = data;
      await signInWithEmailAndPassword(auth, email, password);
      setLoading(false);
    } catch (e: any) {
      setError(e.message);
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen flex-col justify-center py-12 sm:px-6 lg:px-8 bg-gray-50">
      <PageHead title="Inloggen" />
      <div className="bg-white py-8 shadow rounded-lg px-10 mx-auto">
        <FormProvider {...methods}>
          <form
            className="w-80 mx-auto pb-12 px-4"
            onSubmit={handleSubmit(onSubmit)}
          >
            <div className="mt-5">
              <label
                htmlFor="email"
                className="block text-sm font-medium text-gray-600"
              >
                Email
              </label>
              <input
                type="email"
                {...register("email", { required: "Email is verplicht" })}
                className="block mt-1 w-full appearance-none rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-hurks-green focus:ring-hurks-green focus:outline-none  sm:text-sm"
              />
              {errors.email && (
                <p className="text-red-400 mt-1  text-sm font-medium">
                  {errors.email.message}
                </p>
              )}
            </div>
            <div className="mt-7">
              <label
                htmlFor="password"
                className="block text-sm font-medium text-gray-600"
              >
                Wachtwoord
              </label>
              <input
                type="password"
                {...register("password", {
                  required: "Wachtwoord is verplicht",
                })}
                className="block w-full mt-1 appearance-none rounded-md border border-gray-300 px-3 py-2shadow-sm focus:border-hurks-green  focus:ring-hurks-green  focus:outline-none  sm:text-sm"
              />
              {errors.password && (
                <p className="text-red-400 mt-1  text-sm font-medium">
                  {errors.password.message}
                </p>
              )}
            </div>
            <div className="text-sm mt-2">
              <Link
                href="/forgot-password"
                className="font-medium text-hurks-green "
              >
                Wachtwoord vergeten?
              </Link>
            </div>
            <div className="pt-8">
              <button
                type="submit"
                className="flex w-full justify-center rounded-md border border-transparent bg-hurks-green py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-hurks-green focus:outline-none   "
              >
                {loading && (
                  <MoonLoader
                    size={15}
                    color={"white"}
                    className="-ml-0.5 mr-2 "
                  />
                )}
                Login
              </button>
              {error && (
                <p className="text-red-400 mt-1  text-sm font-medium">
                  {error}
                </p>
              )}
            </div>
          </form>
        </FormProvider>
      </div>
    </div>
  );
};

export const getServerSideProps = withAuthUserTokenSSR({
  whenAuthed: AuthAction.REDIRECT_TO_APP,
})();

export default withAuthUser({
  whenAuthed: AuthAction.REDIRECT_TO_APP,
})(LoginPage);
</code>```

Protected page:

```<code>import { AuthAction, withAuthUser, withAuthUserTokenSSR } from "next-firebase-auth";
import { deleteDoc, doc } from "firebase/firestore";
import { useContext, useState } from "react";

import DeleteModal from "../../components/DeleteModal";
import { GeneralContext } from "../../context/GeneralContext";
import Link from "next/link";
import MaterialsTable from "../../components/material/MaterialsTable";
import PageHead from "../../components/PageHead";
import { db } from "../../config/firebase";

const Materials = () => {
  const { showDeleteModal, setShowDeleteModal } = useContext(GeneralContext);
  const [materialId, setMaterialId] = useState<null | string>(null);

  const handleSetMaterialId = (id: string) => {
    setMaterialId(id);
  };

  const deleteMaterial = async () => {
    setShowDeleteModal(!showDeleteModal);
    await deleteDoc(doc(db, "materials", `${materialId}`));
  };
  return (
    <>
      <PageHead title="Materialen Overzicht" />
      <div className="mt-14 w-9/12 mx-auto">
        <div className="flex pb-8 justify-between items-center">
          <h1 className="text-2xl font-semibold text-gray-900">Materialen</h1>
          <Link
            href="/materials/create"
            type="button"
            className="items-center justify-center rounded-md bg-hurks-green px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-hurks-green sm:w-auto"
          >
            Voeg materiaal toe
          </Link>
        </div>
        <MaterialsTable handleSetMaterialId={handleSetMaterialId} />
      </div>
      <DeleteModal deleteItem={deleteMaterial} />
    </>
  );
};

export const getServerSideProps = withAuthUserTokenSSR({
  whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,
})();

export default withAuthUser({
  whenUnauthedAfterInit: AuthAction.REDIRECT_TO_LOGIN,
})(Materials);
</code>```

Config:

```<code>import { init } from "next-firebase-auth";

const TWELVE_DAYS_IN_MS = 12 * 60 * 60 * 24 * 1000;

const initAuth = () => {
  init({
    debug: true,
    authPageURL: "/login",
    appPageURL: "/materials",
    loginAPIEndpoint: "/api/login", // required
    logoutAPIEndpoint: "/api/logout", // required
    firebaseAdminInitConfig: {
      credential: {
        projectId:
          process.env.NODE_ENV === "production"
            ? process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID!
            : process.env.NEXT_PUBLIC_FIREBASE_DEV_PROJECT_ID!,
        privateKey:
          process.env.NODE_ENV === "production"
            ? process.env.FIREBASE_PRIVATE_KEY!
            : process.env.FIREBASE_DEV_PRIVATE_KEY!,
      },
    },

    firebaseClientInitConfig: {
      apiKey:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_FIREBASE_API_KEY!
          : process.env.NEXT_PUBLIC_FIREBASE_DEV_API_KEY!,
      authDomain:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN
          : process.env.NEXT_PUBLIC_FIREBASE_DEV_AUTH_DOMAIN,
      projectId:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
          : process.env.NEXT_PUBLIC_FIREBASE_DEV_PROJECT_ID,
    },
    cookies: {
      name: "Project",
      keys: [
        process.env.COOKIE_SECRET_CURRENT,
        process.env.COOKIE_SECRET_PREVIOUS,
      ],
      httpOnly: false,
      path: "/",
      maxAge: TWELVE_DAYS_IN_MS,
      overwrite: true,
      sameSite: "lax",
      secure: process.env.NEXT_PUBLIC_COOKIE_SECURE === "true",
      signed: true,
    },
  });
};

export default initAuth;
</code>```

After logging in, i get the next-firebase-auth: [getUserFromCookies] Failed to retrieve the ID token from cookies. This will happen if the user is not logged in, the provided cookie values are invalid, or the cookie values don't align with your cookie settings. The user will be unauthenticated. error, which redirects me to the login page, which in turn redirects me to the protected page again, creating an endless loop. When inspecting the cookies, I do see that they are being written, so I'm not sure where it is going wrong at the moment.

Title: Next-firebase-auth causing endless loop

Body:
I have the following setup using Next-firebase-auth:

Login page:

import {
  AuthAction,
  withAuthUser,
  withAuthUserSSR,
  withAuthUserTokenSSR,
} from "next-firebase-auth";
import { FormProvider, useForm } from "react-hook-form";

import Link from "next/link";
import { MoonLoader } from "react-spinners";
import PageHead from "../components/PageHead";
import { auth } from "../config/firebase";
import { signInWithEmailAndPassword } from "firebase/auth";
import { useRouter } from "next/router";
import { useState } from "react";

interface LoginType {
  email: string;
  password: string;
}
const LoginPage = () => {
  const methods = useForm<LoginType>({ mode: "onBlur" });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = methods;

  const onSubmit = async (data: LoginType) => {
    try {
      setLoading(true);
      const { email, password } = data;
      await signInWithEmailAndPassword(auth, email, password);
      setLoading(false);
    } catch (e: any) {
      setError(e.message);
      setLoading(false);
    }
  };

  return (

      <PageHead title="Inloggen" />

        <FormProvider {...methods}>
          <form
            className="w-80 mx-auto pb-12 px-4"
            onSubmit={handleSubmit(onSubmit)}
          >

                Email

              <input
                type="email"
                {...register("email", { required: "Email is verplicht" })}
                className="block mt-1 w-full appearance-none rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-hurks-green focus:ring-hurks-green focus:outline-none  sm:text-sm"
              />
              {errors.email && (

                  {errors.email.message}

              )}

                Wachtwoord

              <input
                type="password"
                {...register("password", {
                  required: "Wachtwoord is verplicht",
                })}
                className="block w-full mt-1 appearance-none rounded-md border border-gray-300 px-3 py-2shadow-sm focus:border-hurks-green  focus:ring-hurks-green  focus:outline-none  sm:text-sm"
              />
              {errors.password && (

                  {errors.password.message}

              )}

              <Link
                href="/forgot-password"
                className="font-medium text-hurks-green "
              >
                Wachtwoord vergeten?
              </Link>

              <button
                type="submit"
                className="flex w-full justify-center rounded-md border border-transparent bg-hurks-green py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-hurks-green focus:outline-none   "
              >
                {loading && (
                  <MoonLoader
                    size={15}
                    color={"white"}
                    className="-ml-0.5 mr-2 "
                  />
                )}
                Login
              </button>
              {error && (

                  {error}

              )}

          </form>
        </FormProvider>

  );
};

export const getServerSideProps = withAuthUserTokenSSR({
  whenAuthed: AuthAction.REDIRECT_TO_APP,
})();

export default withAuthUser({
  whenAuthed: AuthAction.REDIRECT_TO_APP,
})(LoginPage);

Protected page:

import { AuthAction, withAuthUser, withAuthUserTokenSSR } from "next-firebase-auth";
import { deleteDoc, doc } from "firebase/firestore";
import { useContext, useState } from "react";

import DeleteModal from "../../components/DeleteModal";
import { GeneralContext } from "../../context/GeneralContext";
import Link from "next/link";
import MaterialsTable from "../../components/material/MaterialsTable";
import PageHead from "../../components/PageHead";
import { db } from "../../config/firebase";

const Materials = () => {
  const { showDeleteModal, setShowDeleteModal } = useContext(GeneralContext);
  const [materialId, setMaterialId] = useState<null | string>(null);

  const handleSetMaterialId = (id: string) => {
    setMaterialId(id);
  };

  const deleteMaterial = async () => {
    setShowDeleteModal(!showDeleteModal);
    await deleteDoc(doc(db, "materials", `${materialId}`));
  };
  return (
    <>
      <PageHead title="Materialen Overzicht" />

Materialen

          <Link
            href="/materials/create"
            type="button"
            className="items-center justify-center rounded-md bg-hurks-green px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-hurks-green sm:w-auto"
          >
            Voeg materiaal toe
          </Link>

        <MaterialsTable handleSetMaterialId={handleSetMaterialId} />

      <DeleteModal deleteItem={deleteMaterial} />
    </>
  );
};

export const getServerSideProps = withAuthUserTokenSSR({
  whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,
})();

export default withAuthUser({
  whenUnauthedAfterInit: AuthAction.REDIRECT_TO_LOGIN,
})(Materials);

Config:

import { init } from "next-firebase-auth";

const TWELVE_DAYS_IN_MS = 12 * 60 * 60 * 24 * 1000;

const initAuth = () => {
  init({
    debug: true,
    authPageURL: "/login",
    appPageURL: "/materials",
    loginAPIEndpoint: "/api/login", // required
    logoutAPIEndpoint: "/api/logout", // required
    firebaseAdminInitConfig: {
      credential: {
        projectId:
          process.env.NODE_ENV === "production"
            ? process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID!
            : process.env.NEXT_PUBLIC_FIREBASE_DEV_PROJECT_ID!,
        privateKey:
          process.env.NODE_ENV === "production"
            ? process.env.FIREBASE_PRIVATE_KEY!
            : process.env.FIREBASE_DEV_PRIVATE_KEY!,
      },
    },

    firebaseClientInitConfig: {
      apiKey:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_FIREBASE_API_KEY!
          : process.env.NEXT_PUBLIC_FIREBASE_DEV_API_KEY!,
      authDomain:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN
          : process.env.NEXT_PUBLIC_FIREBASE_DEV_AUTH_DOMAIN,
      projectId:
        process.env.NODE_ENV === "production"
          ? process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
          : process.env.NEXT_PUBLIC_FIREBASE_DEV_PROJECT_ID,
    },
    cookies: {
      name: "Project",
      keys: [
        process.env.COOKIE_SECRET_CURRENT,
        process.env.COOKIE_SECRET_PREVIOUS,
      ],
      httpOnly: false,
      path: "/",
      maxAge: TWELVE_DAYS_IN_MS,
      overwrite: true,
      sameSite: "lax",
      secure: process.env.NEXT_PUBLIC_COOKIE_SECURE === "true",
      signed: true,
    },
  });
};

export default initAuth;

After logging in, i get the next-firebase-auth: [getUserFromCookies] Failed to retrieve the ID token from cookies. This will happen if the user is not logged in, the provided cookie values are invalid, or the cookie values don't align with your cookie settings. The user will be unauthenticated. error, which redirects me to the login page, which in turn redirects me to the protected page again, creating an endless loop. When inspecting the cookies, I do see that they are being written, so I'm not sure where it is going wrong at the moment.


来源: stackexchange

问:
Change of displayed images for webp versions
I've got in my uploads folder in Wordpress all of images converted to webp - so now i've got in uploads 2 versions of each image: 1. jpg's/png's and 2. webp version.

Images was converted to webp on the server side.

How to bulk change all of png/jpg versions displayed on my website for webp version?

ContentLicense: CC BY-SA 4.0


问:
c programming, question regarding scanf function
I just learned scanf() functions alongside printf() and I'm wondering why my program kept finishing after I typed some characters from my first user input code. Because it kept finishing, I wasn't able to give input to my second user input code.

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

int main()
{

    double nUm;
    char name[100];

    printf("enter number \t:");
    scanf("%lf", &nUm);
    printf("%f\n", nUm);

    printf("enter name \t:");
    fgets(name, 100, stdin);
    printf("%s", name);

    return 0;
}

</code>```

I tried to change the variables hoping that it would work but still no changes.

Body:
I just learned scanf() functions alongside printf() and I'm wondering why my program kept finishing after I typed some characters from my first user input code. Because it kept finishing, I wasn't able to give input to my second user input code.

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

int main()
{

    double nUm;
    char name[100];

    printf("enter number \t:");
    scanf("%lf", &nUm);
    printf("%f\n", nUm);

    printf("enter name \t:");
    fgets(name, 100, stdin);
    printf("%s", name);

    return 0;
}

I tried to change the variables hoping that it would work but still no changes.


问:
FCM: Sending notification via Firebase Console vs Postman/curl
Does anyone know the difference between sending notification by firebase console and by postman using POST request: https://fcm.googleapis.com/fcm/send

As I have observed, when we send notification via Firebase console, the onMessageReceived callback is executed when user clicks on notification whereas when we send notification by Postman, The onMessageReceived is executed as soon as notification is received.

What is the difference between both ways?

Thanks!


问:
android studio firebasestore nested query
not sure that the second query never meet the success stage even
everything properly setting -- collection, document

FirebaseFirestore fbs = FirebaseFirestore.getInstance();

fbs.collection(Constants.application)
.whereEqualTo(Constants.KEY_USER_ID, preferenceManager.getString(Constants.KEY_USER_ID))
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult() != null && task.getResult().size() > 0) {
List list = new ArrayList<>();

```<code>            **for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult()) {

                fbs.collection(Constants.KEY_COLLECTION_RESERVE)
                        .document(queryDocumentSnapshot.getString(Constants.docId))
                        .get()
                        .addOnSuccessListener(qD -> {**
</code>```

it seems working these structure in simple testing project though

```<code>firebaseFirestore.collection("reservation").whereEqualTo("userId", userId)
        .get().addOnCompleteListener(task -> {
           if (task.isSuccessful() && task.getResult().size() > 0) {
               List<String> list = new ArrayList<>();
               for (DocumentSnapshot documentSnapshot : task.getResult()) {

                   firebaseFirestore.collection("users").document(userId)
                           .get().addOnSuccessListener(result -> {
                               Log.d(TAG, "email : " + result.getString("email"));
                           });
               }

           }

        });
</code>```

Body:
not sure that the second query never meet the success stage even
everything properly setting -- collection, document

FirebaseFirestore fbs = FirebaseFirestore.getInstance();

fbs.collection(Constants.application)
.whereEqualTo(Constants.KEY_USER_ID, preferenceManager.getString(Constants.KEY_USER_ID))
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult() != null && task.getResult().size() > 0) {
List list = new ArrayList<>();

            **for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult()) {

                fbs.collection(Constants.KEY_COLLECTION_RESERVE)
                        .document(queryDocumentSnapshot.getString(Constants.docId))
                        .get()
                        .addOnSuccessListener(qD -> {**

it seems working these structure in simple testing project though

firebaseFirestore.collection("reservation").whereEqualTo("userId", userId)
        .get().addOnCompleteListener(task -> {
           if (task.isSuccessful() && task.getResult().size() > 0) {
               List<String> list = new ArrayList<>();
               for (DocumentSnapshot documentSnapshot : task.getResult()) {

                   firebaseFirestore.collection("users").document(userId)
                           .get().addOnSuccessListener(result -> {
                               Log.d(TAG, "email : " + result.getString("email"));
                           });
               }

           }

        });


问:
Pandas make columns as row
I have following dataframe

```<code>  artist_id  explicit   count
0   10245     False     489
1   10245     True      219
</code>```

I need to convert this dataframe to

```<code>  artist_id  explicit_False     explicit_True
0   10245         489                 219
</code>```

Title: Pandas make columns as row

Body:
I have following dataframe

  artist_id  explicit   count
0   10245     False     489
1   10245     True      219

I need to convert this dataframe to

  artist_id  explicit_False     explicit_True
0   10245         489                 219


问:
ValueError: Input 0 of layer "sequential_5" is incompatible with the layer: expected shape=(None, 200, 200, 3), found shape=(None, 200, 3)
I am coding a model that can classify between images of cats and dogs, Everything works up to fitting the model with the array of resized images, however, when I attempt to run the fitting, it gives me the following error

```<code>ValueError: in user code:

    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 889, in train_step
        y_pred = self(x, training=True)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "sequential_5" is incompatible with the layer: expected shape=(None, 200, 200, 3), found shape=(None, 200, 3)
</code>```

Code:

```<code>files_train = '/content/drive/MyDrive/Colab Notebooks/Cats_Dogs/training_set/*.jpg'
files_test = '/content/drive/MyDrive/Colab Notebooks/Cats_Dogs/test_set/*.jpg'
glob.glob(files_train)
glob.glob(files_test)
images_train = [cv2.imread(image) for image in glob.glob(files_train)]
images_test = [cv2.imread(image) for image in glob.glob(files_test)]
</code>```
```<code>x_train = []
x_test = []
for img in images_train:
  x_train.append(cv2.resize(img, (200,200), interpolation=cv2.INTER_CUBIC))
for img in images_test:
  x_test.append(cv2.resize(img, (200,200), interpolation=cv2.INTER_CUBIC))
</code>```
```<code>for x in x_train_arr:
  x_train_arr = x / 255

for x in x_test_arr:
  x_test_arr = x / 255
</code>```
```<code>model = Sequential()

model.add( Conv2D(200, (5,5), activation='relu', input_shape=(200, 200, 3)))

model.add(MaxPooling2D(pool_size = (2,2)))

model.add( Conv2D(200, (5,5), activation='relu'))

model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Flatten())

model.add(Dense(250, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(100, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(10, activation='relu'))

model.add(Dense(2, activation='softmax'))
</code>```
```<code>hist = model.fit(x_train_arr,text_train,
                 batch_size = 256,
                 epochs = 10,
                 validation_split = 0.2)
</code>```

(Did not paste all code, only which what I thought was relevant)

What I do not understand is that when I run: print(x_train_arr.shape) it gives (3003, 200, 200, 3)
How do I solve this issue?

Body:
I am coding a model that can classify between images of cats and dogs, Everything works up to fitting the model with the array of resized images, however, when I attempt to run the fitting, it gives me the following error

ValueError: in user code:

    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 889, in train_step
        y_pred = self(x, training=True)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "sequential_5" is incompatible with the layer: expected shape=(None, 200, 200, 3), found shape=(None, 200, 3)

Code:

files_train = '/content/drive/MyDrive/Colab Notebooks/Cats_Dogs/training_set/*.jpg'
files_test = '/content/drive/MyDrive/Colab Notebooks/Cats_Dogs/test_set/*.jpg'
glob.glob(files_train)
glob.glob(files_test)
images_train = [cv2.imread(image) for image in glob.glob(files_train)]
images_test = [cv2.imread(image) for image in glob.glob(files_test)]

x_train = []
x_test = []
for img in images_train:
  x_train.append(cv2.resize(img, (200,200), interpolation=cv2.INTER_CUBIC))
for img in images_test:
  x_test.append(cv2.resize(img, (200,200), interpolation=cv2.INTER_CUBIC))

for x in x_train_arr:
  x_train_arr = x / 255

for x in x_test_arr:
  x_test_arr = x / 255

model = Sequential()

model.add( Conv2D(200, (5,5), activation='relu', input_shape=(200, 200, 3)))

model.add(MaxPooling2D(pool_size = (2,2)))

model.add( Conv2D(200, (5,5), activation='relu'))

model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Flatten())

model.add(Dense(250, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(100, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(10, activation='relu'))

model.add(Dense(2, activation='softmax'))

hist = model.fit(x_train_arr,text_train,
                 batch_size = 256,
                 epochs = 10,
                 validation_split = 0.2)

(Did not paste all code, only which what I thought was relevant)

What I do not understand is that when I run: print(x_train_arr.shape) it gives (3003, 200, 200, 3)
How do I solve this issue?


问:
git push stuck at %100. But no error occur
Im trying to push my repository to git.
My remote and branch have correct point to remote address.
I tried to following.

```<code>git add *
git commit -m "..."
git push origin main
</code>```

After that, the terminal output is as follows;

```<code>Enumerating objects: 280, done.
Counting objects: 100% (280/280), done.
Delta compression using up to 8 threads
Compressing objects: 100% (266/266), done.
Writing objects: 100% (279/279), 3.63 MiB | 777.00 KiB/s, done.
Total 279 (delta 31), reused 0 (delta 0), pack-reused 0
</code>```

And process stuck at this point. There are no errors or something. I'm tried to pushing with create a new repository but process stuck at the same and nothing pushed to repository.
Why does this problem occur?

Body:
Im trying to push my repository to git.
My remote and branch have correct point to remote address.
I tried to following.

git add *
git commit -m "..."
git push origin main

After that, the terminal output is as follows;

Enumerating objects: 280, done.
Counting objects: 100% (280/280), done.
Delta compression using up to 8 threads
Compressing objects: 100% (266/266), done.
Writing objects: 100% (279/279), 3.63 MiB | 777.00 KiB/s, done.
Total 279 (delta 31), reused 0 (delta 0), pack-reused 0

And process stuck at this point. There are no errors or something. I'm tried to pushing with create a new repository but process stuck at the same and nothing pushed to repository.
Why does this problem occur?


问:
NegativeArraySizeException occur in kotlin mp android chart
I want to make real-time line chart to show linear acceleration of android phone.
So, I used mp android chart library but NegativeArraySizeException occurs.

```<code>package com.example.graph_example

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.utils.EntryXComparator
import java.util.Calendar
import java.util.Collections

class MainActivity : AppCompatActivity(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private lateinit var linearAccelerationSensor: Sensor
    private lateinit var chart : LineChart
    private lateinit var dataSetX: LineDataSet
    private lateinit var dataSetY: LineDataSet
    private lateinit var dataSetZ: LineDataSet
    private var lastX = 0.0f
    private var lastY = 0.0f
    private var lastZ = 0.0f
    private var timestamp: Double = 0.0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        linearAccelerationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)

        chart = findViewById(R.id.line_chart)

        dataSetX = LineDataSet(null, "X")
        dataSetX.color = Color.RED
        dataSetX.lineWidth = 2.5f
        dataSetX.setDrawValues(false)
        dataSetX.setDrawValues(false)
        dataSetX.mode = LineDataSet.Mode.CUBIC_BEZIER

        dataSetY = LineDataSet(null, "Y")
        dataSetY.color = Color.GREEN
        dataSetY.lineWidth = 2.5f
        dataSetY.setDrawValues(false)
        dataSetY.setDrawValues(false)
        dataSetY.mode = LineDataSet.Mode.CUBIC_BEZIER

        dataSetZ = LineDataSet(null, "Z")
        dataSetZ.color = Color.BLUE
        dataSetZ.lineWidth = 2.5f
        dataSetZ.setDrawValues(false)
        dataSetZ.setDrawValues(false)
        dataSetZ.mode = LineDataSet.Mode.CUBIC_BEZIER

        chart.data = LineData(dataSetX, dataSetY, dataSetZ)
        chart.description.isEnabled = false
        chart.legend.isEnabled = false
        chart.setNoDataText("Waiting for data...")
        chart.setNoDataTextColor(Color.BLACK)
        chart.setTouchEnabled(false)
        chart.isDragEnabled = false
        chart.setScaleEnabled(false)
        chart.setPinchZoom(false)
        chart.setDrawGridBackground(false)
        chart.axisRight.isEnabled = false
        chart.xAxis.position = XAxis.XAxisPosition.BOTTOM
        chart.xAxis.setDrawAxisLine(false)

    }

    override fun onResume() {
        super.onResume()
        sensorManager.registerListener(this, linearAccelerationSensor, SensorManager.SENSOR_DELAY_GAME)
    }

    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (event != null) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]

            val currentTime = Calendar.getInstance().timeInMillis
            if (timestamp != 0.0) {
                val dt = ((currentTime - timestamp) / 1000.0).toFloat()
                val dx = x * dt
                val dy = y * dt
                val dz = z * dt
                val pointX = Entry(lastX + dx, x.toFloat())
                val pointY = Entry(lastY + dy, y.toFloat())
                val pointZ = Entry(lastZ + dz, z.toFloat())
                dataSetX.addEntry(pointX)
                dataSetY.addEntry(pointY)
                dataSetZ.addEntry(pointZ)
                chart.notifyDataSetChanged()
                chart.setVisibleXRangeMaximum(20.0f)
                chart.moveViewToX(dataSetX.entryCount.toFloat())
            }
            lastX += x * ((currentTime - timestamp) / 1000.0).toFloat()
            lastY += y * ((currentTime - timestamp) / 1000.0).toFloat()
            lastZ += z * ((currentTime - timestamp) / 1000.0).toFloat()
            timestamp = currentTime.toDouble()
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        // Do nothing
    }

}
</code>```

and this is error code:

```<code>2023-01-02 22:13:27.370 13697-13697/com.example.graph_example E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.graph_example, PID: 13697
    java.lang.NegativeArraySizeException: -12
        at com.github.mikephil.charting.utils.Transformer.generateTransformedValuesLine(Transformer.java:178)
        at com.github.mikephil.charting.renderer.LineChartRenderer.drawValues(LineChartRenderer.java:549)
        at com.github.mikephil.charting.charts.BarLineChartBase.onDraw(BarLineChartBase.java:278)
        at android.view.View.draw(View.java:22350)
        at android.view.View.updateDisplayListIfDirty(View.java:21226)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4500)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4473)
        at android.view.View.updateDisplayListIfDirty(View.java:21186)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4500)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4473)
        at android.view.View.updateDisplayListIfDirty(View.java:21186)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.updateDisplayListIfDirty(View.java:21217)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.updateDisplayListIfDirty(View.java:21217)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.updateDisplayListIfDirty(View.java:21217)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.draw(View.java:22353)
        at com.android.internal.policy.DecorView.draw(DecorView.java:806)
        at android.view.View.updateDisplayListIfDirty(View.java:21226)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:559)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:565)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:642)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:4101)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3828)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3099)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
        at android.view.Choreographer.doCallbacks(Choreographer.java:796)
        at android.view.Choreographer.doFrame(Choreographer.java:731)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
</code>```

Body:
I want to make real-time line chart to show linear acceleration of android phone.
So, I used mp android chart library but NegativeArraySizeException occurs.

package com.example.graph_example

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.utils.EntryXComparator
import java.util.Calendar
import java.util.Collections

class MainActivity : AppCompatActivity(), SensorEventListener {

    private lateinit var sensorManager: SensorManager
    private lateinit var linearAccelerationSensor: Sensor
    private lateinit var chart : LineChart
    private lateinit var dataSetX: LineDataSet
    private lateinit var dataSetY: LineDataSet
    private lateinit var dataSetZ: LineDataSet
    private var lastX = 0.0f
    private var lastY = 0.0f
    private var lastZ = 0.0f
    private var timestamp: Double = 0.0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        linearAccelerationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)

        chart = findViewById(R.id.line_chart)

        dataSetX = LineDataSet(null, "X")
        dataSetX.color = Color.RED
        dataSetX.lineWidth = 2.5f
        dataSetX.setDrawValues(false)
        dataSetX.setDrawValues(false)
        dataSetX.mode = LineDataSet.Mode.CUBIC_BEZIER

        dataSetY = LineDataSet(null, "Y")
        dataSetY.color = Color.GREEN
        dataSetY.lineWidth = 2.5f
        dataSetY.setDrawValues(false)
        dataSetY.setDrawValues(false)
        dataSetY.mode = LineDataSet.Mode.CUBIC_BEZIER

        dataSetZ = LineDataSet(null, "Z")
        dataSetZ.color = Color.BLUE
        dataSetZ.lineWidth = 2.5f
        dataSetZ.setDrawValues(false)
        dataSetZ.setDrawValues(false)
        dataSetZ.mode = LineDataSet.Mode.CUBIC_BEZIER

        chart.data = LineData(dataSetX, dataSetY, dataSetZ)
        chart.description.isEnabled = false
        chart.legend.isEnabled = false
        chart.setNoDataText("Waiting for data...")
        chart.setNoDataTextColor(Color.BLACK)
        chart.setTouchEnabled(false)
        chart.isDragEnabled = false
        chart.setScaleEnabled(false)
        chart.setPinchZoom(false)
        chart.setDrawGridBackground(false)
        chart.axisRight.isEnabled = false
        chart.xAxis.position = XAxis.XAxisPosition.BOTTOM
        chart.xAxis.setDrawAxisLine(false)

    }

    override fun onResume() {
        super.onResume()
        sensorManager.registerListener(this, linearAccelerationSensor, SensorManager.SENSOR_DELAY_GAME)
    }

    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(this)
    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (event != null) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]

            val currentTime = Calendar.getInstance().timeInMillis
            if (timestamp != 0.0) {
                val dt = ((currentTime - timestamp) / 1000.0).toFloat()
                val dx = x * dt
                val dy = y * dt
                val dz = z * dt
                val pointX = Entry(lastX + dx, x.toFloat())
                val pointY = Entry(lastY + dy, y.toFloat())
                val pointZ = Entry(lastZ + dz, z.toFloat())
                dataSetX.addEntry(pointX)
                dataSetY.addEntry(pointY)
                dataSetZ.addEntry(pointZ)
                chart.notifyDataSetChanged()
                chart.setVisibleXRangeMaximum(20.0f)
                chart.moveViewToX(dataSetX.entryCount.toFloat())
            }
            lastX += x * ((currentTime - timestamp) / 1000.0).toFloat()
            lastY += y * ((currentTime - timestamp) / 1000.0).toFloat()
            lastZ += z * ((currentTime - timestamp) / 1000.0).toFloat()
            timestamp = currentTime.toDouble()
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        // Do nothing
    }

}

and this is error code:

2023-01-02 22:13:27.370 13697-13697/com.example.graph_example E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.graph_example, PID: 13697
    java.lang.NegativeArraySizeException: -12
        at com.github.mikephil.charting.utils.Transformer.generateTransformedValuesLine(Transformer.java:178)
        at com.github.mikephil.charting.renderer.LineChartRenderer.drawValues(LineChartRenderer.java:549)
        at com.github.mikephil.charting.charts.BarLineChartBase.onDraw(BarLineChartBase.java:278)
        at android.view.View.draw(View.java:22350)
        at android.view.View.updateDisplayListIfDirty(View.java:21226)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4500)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4473)
        at android.view.View.updateDisplayListIfDirty(View.java:21186)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4500)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4473)
        at android.view.View.updateDisplayListIfDirty(View.java:21186)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.updateDisplayListIfDirty(View.java:21217)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.updateDisplayListIfDirty(View.java:21217)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.updateDisplayListIfDirty(View.java:21217)
        at android.view.View.draw(View.java:22081)
        at android.view.ViewGroup.drawChild(ViewGroup.java:4516)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4277)
        at android.view.View.draw(View.java:22353)
        at com.android.internal.policy.DecorView.draw(DecorView.java:806)
        at android.view.View.updateDisplayListIfDirty(View.java:21226)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:559)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:565)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:642)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:4101)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3828)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3099)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1952)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8171)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:972)
        at android.view.Choreographer.doCallbacks(Choreographer.java:796)
        at android.view.Choreographer.doFrame(Choreographer.java:731)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:957)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)


问:
How to upload multiple XMLs in Tally Accounting Software?
I am currently uploading single sales XML in Tally. I want to know how can i bulk upload multiple XML's at 1 time? I have to upload multiple XML's in a day and that takes a lot of my time.</p>


问:
script to identify resource without private end point configured (Key vault & Storage)
any script to identify resource without private end point configured (Key vault & Storage)

script to identify resource without private end point configured (Key vault & Storage)


问:
Trace Marker not updating with go.Scattermapbox
I am using go.Scattermapbox in a python script for rendering location of objects. The underlying data changes on user interaction with another component. When the user selects another entity, the hover info for the plot updates to the correct labels and the hover data is diplayed in the correct position as it should, the map snaps to the right center point, but the actual markers themselves aren’t in the correct spot. They hang on the previously selected entity.</p>
```<code>    try:
        fig.add_trace(
            go.Scattermapbox(
                name="Location 1",
                lat=gen_df.latitude.unique().tolist(),
                lon=gen_df.longitude.unique().tolist(),
                mode="markers",
                text=gen_df["name"].iloc[0],
                hoverinfo="text",
            )
        )
except:
        warnings.append("Location 1 has no coordinates")
try:
        fig.add_trace(
            go.Scattermapbox(
                name="Location 2",
                lat=gen_df.lat.unique().tolist(),
                lon=gen_df.lon.unique().tolist(),
                mode="markers",
                text=gen_df["_id"].iloc[0],
                hoverinfo="text",
            )
        )
except:
        warnings.append("Location 2 has no coordinates")
fig.update_layout(
        height=800,
        autosize=True,
        showlegend=True,
        mapbox=dict(
            accesstoken=MAPBOX_TOKEN,
            bearing=0,
            center=dict(
                lat=gen_df.latitude.unique().tolist()[0],
                lon=gen_df.longitude.unique().tolist()[0],
            ),
            zoom=11,
            pitch=0,
            style="dark",
        ),
    )
fig.show()
</code>```

Body:
I am using go.Scattermapbox in a python script for rendering location of objects. The underlying data changes on user interaction with another component. When the user selects another entity, the hover info for the plot updates to the correct labels and the hover data is diplayed in the correct position as it should, the map snaps to the right center point, but the actual markers themselves aren’t in the correct spot. They hang on the previously selected entity.

    try:
        fig.add_trace(
            go.Scattermapbox(
                name="Location 1",
                lat=gen_df.latitude.unique().tolist(),
                lon=gen_df.longitude.unique().tolist(),
                mode="markers",
                text=gen_df["name"].iloc[0],
                hoverinfo="text",
            )
        )
except:
        warnings.append("Location 1 has no coordinates")
try:
        fig.add_trace(
            go.Scattermapbox(
                name="Location 2",
                lat=gen_df.lat.unique().tolist(),
                lon=gen_df.lon.unique().tolist(),
                mode="markers",
                text=gen_df["_id"].iloc[0],
                hoverinfo="text",
            )
        )
except:
        warnings.append("Location 2 has no coordinates")
fig.update_layout(
        height=800,
        autosize=True,
        showlegend=True,
        mapbox=dict(
            accesstoken=MAPBOX_TOKEN,
            bearing=0,
            center=dict(
                lat=gen_df.latitude.unique().tolist()[0],
                lon=gen_df.longitude.unique().tolist()[0],
            ),
            zoom=11,
            pitch=0,
            style="dark",
        ),
    )
fig.show()


问:
ResNet50: Transfer learning with GradCam
I am new to the field and am having trouble applying GradCam to a Tensorflow ResNet50 model I have re-trained.

I have created my model as follows:

```<code>IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.ResNet50(input_shape=IMG_SHAPE,
                                               include_top=False,
                                               weights='imagenet')
</code>```
```<code>global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
feature_batch_average = global_average_layer(feature_batch)
</code>```
```<code>prediction_layer = tf.keras.layers.Dense(5, activation='softmax')
prediction_batch = prediction_layer(feature_batch_average)

</code>```
```<code>inputs = tf.keras.Input(shape=(224, 224, 3))
x = data_augmentation(inputs)
x = preprocess_input(x)
x = base_model(x, training=False)
x = global_average_layer(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)
</code>```
```<code>base_learning_rate = 0.0001
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),
              loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False),
              metrics=['accuracy'])
</code>```
```<code>model.summary()

Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_2 (InputLayer)        [(None, 224, 224, 3)]     0

 sequential (Sequential)     (None, 224, 224, 3)       0

 tf.__operators__.getitem (S  (None, 224, 224, 3)      0
 licingOpLambda)

 tf.nn.bias_add (TFOpLambda)  (None, 224, 224, 3)      0

 resnet50 (Functional)       (None, 7, 7, 2048)        23587712

 global_average_pooling2d (G  (None, 2048)             0
 lobalAveragePooling2D)

 dropout (Dropout)           (None, 2048)              0

 dense (Dense)               (None, 5)                 10245

=================================================================
Total params: 23,597,957
Trainable params: 19,463,173
Non-trainable params: 4,134,784
_________________________________________________________________
</code>```

For the application of GradCam in the following tutorial:
https://github.com/ismailuddin/gradcam-tensorflow-2/blob/master/notebooks/GradCam.ipynb
the output of the last convulution layer is now required

```<code>last_conv_layer = model.get_layer("conv5_block3_out")
last_conv_layer_model = tf.keras.Model(model.inputs, last_conv_layer.output)
</code>```

The problem I have, however, is that this last convulutional layer in my model is in the "resnet50 (Functional)", which I cannot access.

I can only access this layer if I use the unmodified ResNet50 base model which I cannot use for my project.

```<code>Model: "resnet50"
__________________________________________________________________________________________________
 Layer (type)                   Output Shape         Param #     Connected to
==================================================================================================
 input_1 (InputLayer)           [(None, 224, 224, 3  0           []
                                )]

 conv1_pad (ZeroPadding2D)      (None, 230, 230, 3)  0           ['input_1[0][0]']

 conv1_conv (Conv2D)            (None, 112, 112, 64  9472        ['conv1_pad[0][0]']
                                )

 conv1_bn (BatchNormalization)  (None, 112, 112, 64  256         ['conv1_conv[0][0]']
                                )

 conv1_relu (Activation)        (None, 112, 112, 64  0           ['conv1_bn[0][0]']
                                )

 pool1_pad (ZeroPadding2D)      (None, 114, 114, 64  0           ['conv1_relu[0][0]']
                                )

 pool1_pool (MaxPooling2D)      (None, 56, 56, 64)   0           ['pool1_pad[0][0]']

 conv2_block1_1_conv (Conv2D)   (None, 56, 56, 64)   4160        ['pool1_pool[0][0]']

 conv2_block1_1_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block1_1_conv[0][0]']
 ization)

 conv2_block1_1_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block1_1_bn[0][0]']
 n)

 conv2_block1_2_conv (Conv2D)   (None, 56, 56, 64)   36928       ['conv2_block1_1_relu[0][0]']

 conv2_block1_2_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block1_2_conv[0][0]']
 ization)
...
 conv5_block3_2_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block3_2_bn[0][0]']
 n)

 conv5_block3_3_conv (Conv2D)   (None, 7, 7, 2048)   1050624     ['conv5_block3_2_relu[0][0]']

 conv5_block3_3_bn (BatchNormal  (None, 7, 7, 2048)  8192        ['conv5_block3_3_conv[0][0]']
 ization)

 conv5_block3_add (Add)         (None, 7, 7, 2048)   0           ['conv5_block2_out[0][0]',
                                                                  'conv5_block3_3_bn[0][0]']

 conv5_block3_out (Activation)  (None, 7, 7, 2048)   0           ['conv5_block3_add[0][0]']

 avg_pool (GlobalAveragePooling  (None, 2048)        0           ['conv5_block3_out[0][0]']
 2D)

 predictions (Dense)            (None, 1000)         2049000     ['avg_pool[0][0]']

==================================================================================================
Total params: 25,636,712
Trainable params: 25,583,592
Non-trainable params: 53,120
__________________________________________________________________________________________________
</code>```

What do I have to do to access this layer in my model?

I would be infinitely grateful for a solution.

Body:
I am new to the field and am having trouble applying GradCam to a Tensorflow ResNet50 model I have re-trained.

I have created my model as follows:

IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.ResNet50(input_shape=IMG_SHAPE,
                                               include_top=False,
                                               weights='imagenet')

global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
feature_batch_average = global_average_layer(feature_batch)

prediction_layer = tf.keras.layers.Dense(5, activation='softmax')
prediction_batch = prediction_layer(feature_batch_average)

inputs = tf.keras.Input(shape=(224, 224, 3))
x = data_augmentation(inputs)
x = preprocess_input(x)
x = base_model(x, training=False)
x = global_average_layer(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)

base_learning_rate = 0.0001
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),
              loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False),
              metrics=['accuracy'])

model.summary()

Model: "model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_2 (InputLayer)        [(None, 224, 224, 3)]     0

 sequential (Sequential)     (None, 224, 224, 3)       0

 tf.__operators__.getitem (S  (None, 224, 224, 3)      0
 licingOpLambda)

 tf.nn.bias_add (TFOpLambda)  (None, 224, 224, 3)      0

 resnet50 (Functional)       (None, 7, 7, 2048)        23587712

 global_average_pooling2d (G  (None, 2048)             0
 lobalAveragePooling2D)

 dropout (Dropout)           (None, 2048)              0

 dense (Dense)               (None, 5)                 10245

=================================================================
Total params: 23,597,957
Trainable params: 19,463,173
Non-trainable params: 4,134,784
_________________________________________________________________

For the application of GradCam in the following tutorial:
https://github.com/ismailuddin/gradcam-tensorflow-2/blob/master/notebooks/GradCam.ipynb
the output of the last convulution layer is now required

last_conv_layer = model.get_layer("conv5_block3_out")
last_conv_layer_model = tf.keras.Model(model.inputs, last_conv_layer.output)

The problem I have, however, is that this last convulutional layer in my model is in the "resnet50 (Functional)", which I cannot access.

I can only access this layer if I use the unmodified ResNet50 base model which I cannot use for my project.

Model: "resnet50"
__________________________________________________________________________________________________
 Layer (type)                   Output Shape         Param #     Connected to
==================================================================================================
 input_1 (InputLayer)           [(None, 224, 224, 3  0           []
                                )]

 conv1_pad (ZeroPadding2D)      (None, 230, 230, 3)  0           ['input_1[0][0]']

 conv1_conv (Conv2D)            (None, 112, 112, 64  9472        ['conv1_pad[0][0]']
                                )

 conv1_bn (BatchNormalization)  (None, 112, 112, 64  256         ['conv1_conv[0][0]']
                                )

 conv1_relu (Activation)        (None, 112, 112, 64  0           ['conv1_bn[0][0]']
                                )

 pool1_pad (ZeroPadding2D)      (None, 114, 114, 64  0           ['conv1_relu[0][0]']
                                )

 pool1_pool (MaxPooling2D)      (None, 56, 56, 64)   0           ['pool1_pad[0][0]']

 conv2_block1_1_conv (Conv2D)   (None, 56, 56, 64)   4160        ['pool1_pool[0][0]']

 conv2_block1_1_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block1_1_conv[0][0]']
 ization)

 conv2_block1_1_relu (Activatio  (None, 56, 56, 64)  0           ['conv2_block1_1_bn[0][0]']
 n)

 conv2_block1_2_conv (Conv2D)   (None, 56, 56, 64)   36928       ['conv2_block1_1_relu[0][0]']

 conv2_block1_2_bn (BatchNormal  (None, 56, 56, 64)  256         ['conv2_block1_2_conv[0][0]']
 ization)
...
 conv5_block3_2_relu (Activatio  (None, 7, 7, 512)   0           ['conv5_block3_2_bn[0][0]']
 n)

 conv5_block3_3_conv (Conv2D)   (None, 7, 7, 2048)   1050624     ['conv5_block3_2_relu[0][0]']

 conv5_block3_3_bn (BatchNormal  (None, 7, 7, 2048)  8192        ['conv5_block3_3_conv[0][0]']
 ization)

 conv5_block3_add (Add)         (None, 7, 7, 2048)   0           ['conv5_block2_out[0][0]',
                                                                  'conv5_block3_3_bn[0][0]']

 conv5_block3_out (Activation)  (None, 7, 7, 2048)   0           ['conv5_block3_add[0][0]']

 avg_pool (GlobalAveragePooling  (None, 2048)        0           ['conv5_block3_out[0][0]']
 2D)

 predictions (Dense)            (None, 1000)         2049000     ['avg_pool[0][0]']

==================================================================================================
Total params: 25,636,712
Trainable params: 25,583,592
Non-trainable params: 53,120
__________________________________________________________________________________________________

What do I have to do to access this layer in my model?

I would be infinitely grateful for a solution.


问:
Explain the difference between Docstring and Comment with an appropriate example in python?
I was confused between the docstring and comment in python can could not able to differentiate between them

I was recently working on a project which include comment and docstring and puzzled between there differences and their uses.


问:
Problem with recyclerview last item added not showed inside a fragment
I having problem showing the last item when I update my recyclerview. The data is correct but I have to scroll down to show the last item because is out of screen. It's not a problem about constraint, nor margins, I've double checked it.I've read several posts here about how to fix it but none has worked for my code so far. Any suggestions?
This is my adapter:

```<code>class ComentarioAdaptador(private var context: Context, private var publicacionLista: ArrayList<Comentario>): RecyclerView.Adapter<ComentarioAdaptador.ViewHolder>()
{
    private  var tipoUsuario=""
    class ViewHolder( itemView: View):RecyclerView.ViewHolder(itemView) {
        var ivPerfil : ImageView = itemView.findViewById(R.id.iv_perfil)
        var tvNombreUsuario: TextView = itemView.findViewById(R.id.tv_propietario)
        var tvComentario: TextView = itemView.findViewById(R.id.tv_comentario)
        var tvFecha: TextView = itemView.findViewById(R.id.tv_fecha)
        var btnBorrar: Button =itemView.findViewById(R.id.brn_borrar_comentario)

    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =LayoutInflater.from(context).inflate(R.layout.comentario,parent,false)
        determinarTipoUsuario()
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return publicacionLista.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val comentario = publicacionLista[position]
        holder.tvComentario.text =comentario.contenido
        holder.tvFecha.text= comentario.fecha
        buscarUsuario(holder.ivPerfil, holder.tvNombreUsuario, comentario.creadoPor,holder.btnBorrar)
        holder.btnBorrar.setOnClickListener{
        }
    }

    private fun buscarUsuario(ivPerfil: ImageView, tvNombreUsuario: TextView, propietario: String, btnBorrar:Button) {
        val usuarioRef = FirebaseDatabase.getInstance().reference.child("Usuarios").child(propietario)
        usuarioRef.addValueEventListener(object: ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                    val usuario=snapshot.getValue(Usuario::class.java)
                    tvNombreUsuario.text=usuario!!.usuario
                    Glide.with(context).load(usuario.perfil).circleCrop().into(ivPerfil)
                    if (tipoUsuario=="usuario")
                        btnBorrar.isGone=true
                    else
                        btnBorrar.isVisible=true
                }
            }
            override fun onCancelled(error: DatabaseError) {
            }
        })
    }
    private fun determinarTipoUsuario(){
    val usuarioActual  = FirebaseAuth.getInstance().currentUser!!
    val userID = usuarioActual.uid
    //LUEGO HAGO UNA INSTANCIA DE ESA UID
    val busqueda = FirebaseDatabase.getInstance().getReference("Usuarios").child(userID)
    //FINALMENTE LE PONGO UN LISTENER PARA GUARDAR DATOS
    busqueda.addValueEventListener(object : ValueEventListener
    {
        override fun onDataChange(snapshot: DataSnapshot)
        {
            tipoUsuario = snapshot.getValue(Usuario::class.java)!!.tipo
            Toast.makeText(context, tipoUsuario, Toast.LENGTH_SHORT).show()
        }
        override fun onCancelled(error: DatabaseError)
        {}
    })
    }
}
</code>```

This is how I call the the recyclerview on my fragment:

```<code>private fun mostrarComentarios(uidPostRecibido:String){
        val comentariosRef= FirebaseDatabase.getInstance().reference.child("Comentarios").child(uidPostRecibido)
        listaComentarios!!.clear()
        comentariosRef.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                        for (snapshot in snapshot.children)
                    {
                        val comentario = snapshot.getValue(Comentario::class.java)
                        listaComentarios!!.add(comentario!!)
                    }
                    comentarioAdaptador!!.notifyDataSetChanged()
                 }
            }
            override fun onCancelled(error: DatabaseError) {
            }
        }
        )
    }
</code>```

Body:
I having problem showing the last item when I update my recyclerview. The data is correct but I have to scroll down to show the last item because is out of screen. It's not a problem about constraint, nor margins, I've double checked it.I've read several posts here about how to fix it but none has worked for my code so far. Any suggestions?
This is my adapter:

class ComentarioAdaptador(private var context: Context, private var publicacionLista: ArrayList<Comentario>): RecyclerView.Adapter<ComentarioAdaptador.ViewHolder>()
{
    private  var tipoUsuario=""
    class ViewHolder( itemView: View):RecyclerView.ViewHolder(itemView) {
        var ivPerfil : ImageView = itemView.findViewById(R.id.iv_perfil)
        var tvNombreUsuario: TextView = itemView.findViewById(R.id.tv_propietario)
        var tvComentario: TextView = itemView.findViewById(R.id.tv_comentario)
        var tvFecha: TextView = itemView.findViewById(R.id.tv_fecha)
        var btnBorrar: Button =itemView.findViewById(R.id.brn_borrar_comentario)

    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =LayoutInflater.from(context).inflate(R.layout.comentario,parent,false)
        determinarTipoUsuario()
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return publicacionLista.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val comentario = publicacionLista[position]
        holder.tvComentario.text =comentario.contenido
        holder.tvFecha.text= comentario.fecha
        buscarUsuario(holder.ivPerfil, holder.tvNombreUsuario, comentario.creadoPor,holder.btnBorrar)
        holder.btnBorrar.setOnClickListener{
        }
    }

    private fun buscarUsuario(ivPerfil: ImageView, tvNombreUsuario: TextView, propietario: String, btnBorrar:Button) {
        val usuarioRef = FirebaseDatabase.getInstance().reference.child("Usuarios").child(propietario)
        usuarioRef.addValueEventListener(object: ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                    val usuario=snapshot.getValue(Usuario::class.java)
                    tvNombreUsuario.text=usuario!!.usuario
                    Glide.with(context).load(usuario.perfil).circleCrop().into(ivPerfil)
                    if (tipoUsuario=="usuario")
                        btnBorrar.isGone=true
                    else
                        btnBorrar.isVisible=true
                }
            }
            override fun onCancelled(error: DatabaseError) {
            }
        })
    }
    private fun determinarTipoUsuario(){
    val usuarioActual  = FirebaseAuth.getInstance().currentUser!!
    val userID = usuarioActual.uid
    //LUEGO HAGO UNA INSTANCIA DE ESA UID
    val busqueda = FirebaseDatabase.getInstance().getReference("Usuarios").child(userID)
    //FINALMENTE LE PONGO UN LISTENER PARA GUARDAR DATOS
    busqueda.addValueEventListener(object : ValueEventListener
    {
        override fun onDataChange(snapshot: DataSnapshot)
        {
            tipoUsuario = snapshot.getValue(Usuario::class.java)!!.tipo
            Toast.makeText(context, tipoUsuario, Toast.LENGTH_SHORT).show()
        }
        override fun onCancelled(error: DatabaseError)
        {}
    })
    }
}

This is how I call the the recyclerview on my fragment:

private fun mostrarComentarios(uidPostRecibido:String){
        val comentariosRef= FirebaseDatabase.getInstance().reference.child("Comentarios").child(uidPostRecibido)
        listaComentarios!!.clear()
        comentariosRef.addValueEventListener(object : ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()){
                        for (snapshot in snapshot.children)
                    {
                        val comentario = snapshot.getValue(Comentario::class.java)
                        listaComentarios!!.add(comentario!!)
                    }
                    comentarioAdaptador!!.notifyDataSetChanged()
                 }
            }
            override fun onCancelled(error: DatabaseError) {
            }
        }
        )
    }


问:
How To Count Number Hotels With Same City?

In database there are multiple hotels are available of the city same as that of query but I'm getting output as

[0,0,0]
what's the problem, I'm not able to understand why this is happening?

`

```<code>exports.countByCity = async (req, res, next) => {
  const cities = req.query.cities.split(",");
  try {
    const list = await Promise.all(
      cities.map((city) => {
        console.log(city);
        return Hotel.countDocuments({city:city});
      })
    );

    res.status(200).json(list);
  } catch (err) {
    next(err);
  }
};

</code>```

`

Body:
In database there are multiple hotels are available of the city same as that of query but I'm getting output as

[0,0,0]
what's the problem, I'm not able to understand why this is happening?

`

exports.countByCity = async (req, res, next) => {
  const cities = req.query.cities.split(",");
  try {
    const list = await Promise.all(
      cities.map((city) => {
        console.log(city);
        return Hotel.countDocuments({city:city});
      })
    );

    res.status(200).json(list);
  } catch (err) {
    next(err);
  }
};

`


问:
How to test Stripe Google/Apple pay button using Cypress?
I'm unable to test stripe Google/Apple pay button using cypress. Whenever I click on the Google/Apple pay button, It opens the page in a new tab and cypress only works on a single tab. Can someone suggest how to do it? Any suggestions might be really helpful.

I tried to automate it but whenever I click the Stripe Google/Apple pay button, it redirects me to the checkout page on a new tab which is not possible to test using cypress.

I tried to automate it but whenever I click the Stripe Google/Apple pay button, it redirects me to the checkout page on a new tab which is not possible to test using cypress.


问:
Making animated graph in R
So I have tried to make an animated graph in R, but it does not seem like I can make a final product that I am happy with. My final product I want to be similar to this tiktok:
https://www.tiktok.com/@sigma_finance2/video/7173237923821686022?is_copy_url=1&is_from_webapp=v1&q=sigma%20finance&t=1672666608208

But my experience is not that big with making animated graphs in R, so maybe this is not even possible. Right now my code looks like the following, but can anyone help me get a bit closer to the tiktok?:

```<code>p <- ggplot(data = Mappe4, aes(x=Date, y=Share)) +
  geom_line(color = "blue", size = 1.0) +
  geom_point(size = 5, color = "green") +
  geom_text(aes(label = Date), color="darkblue", fontface="bold", vjust = -2) +
  geom_text(aes(label = Share), color="red", fontface="bold", vjust = -4) +
  theme_dark() +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(x = 'Date', y = 'Value of shares', title = 'Apple') +
  transition_reveal(Date) +
  view_follow(fixed_y = TRUE)

animate(p, nframes = 144, fps = 2, width = 500, height = 300, renderer = gifski_renderer())

anim_save('test.gif', p)
</code>```

Thanks in advance!

Title: Making animated graph in R

Body:
So I have tried to make an animated graph in R, but it does not seem like I can make a final product that I am happy with. My final product I want to be similar to this tiktok:
https://www.tiktok.com/@sigma_finance2/video/7173237923821686022?is_copy_url=1&is_from_webapp=v1&q=sigma%20finance&t=1672666608208

But my experience is not that big with making animated graphs in R, so maybe this is not even possible. Right now my code looks like the following, but can anyone help me get a bit closer to the tiktok?:

p <- ggplot(data = Mappe4, aes(x=Date, y=Share)) +
  geom_line(color = "blue", size = 1.0) +
  geom_point(size = 5, color = "green") +
  geom_text(aes(label = Date), color="darkblue", fontface="bold", vjust = -2) +
  geom_text(aes(label = Share), color="red", fontface="bold", vjust = -4) +
  theme_dark() +
  theme(plot.title = element_text(hjust = 0.5)) +
  labs(x = 'Date', y = 'Value of shares', title = 'Apple') +
  transition_reveal(Date) +
  view_follow(fixed_y = TRUE)

animate(p, nframes = 144, fps = 2, width = 500, height = 300, renderer = gifski_renderer())

anim_save('test.gif', p)

Thanks in advance!


问:
non empty typescript array pop exclude undefined
I have a non empty array to pop an element from

import { AssertionError } from 'assert';
function foo(A: Array<number>): number {
  if (A.length > 0) {
    return A.pop()
  }
  throw new AssertionError();
}
```
<p>When I compile it with typescript I get an error:</p>
```$ npx tsc --strict main.ts
main.ts:4:5 - error TS2322: Type 'number | undefined' is not assignable to type 'number'.
  Type 'undefined' is not assignable to type 'number'.
```

This is a bit weird (?) because according to the docs:

If you call pop() on an empty array, it returns undefined

But my array is not empty.

Body:
I have a non empty array to pop an element from

import { AssertionError } from 'assert';
function foo(A: Array<number>): number {
  if (A.length > 0) {
    return A.pop()
  }
  throw new AssertionError();
}

When I compile it with typescript I get an error:

$ npx tsc --strict main.ts
main.ts:4:5 - error TS2322: Type 'number | undefined' is not assignable to type 'number'.
  Type 'undefined' is not assignable to type 'number'.

This is a bit weird (?) because according to the docs:

If you call pop() on an empty array, it returns undefined

But my array is not empty.


问:
Angular Apexcharts template generates errors - template elements unrecognised
I am following the example given in ApexCharts website to create candlestick with line combo chart in Angular. There's also a sandbox given.

Basically the way I am following the 'presciption' given in the webpage above by copying and pasting with very little modifications, so the component code is 99.99% identical (I removed some data). The code compiles fine before I define the template. However when I add the template code - most of the elements are not recognised.

If the template code is as follows:

```<code><div id="chart">
  <apx-chart
    [series]="chartOptions.series"
    [chart]="chartOptions.chart"
    [xaxis]="chartOptions.xaxis"
    [title]="chartOptions.title"
    [tooltip]="chartOptions.tooltip"
    [stroke]="chartOptions.stroke"
  ></apx-chart>
</div>
</code>```

only the [stroke] element is not getting a red underline marking an error. All the elements above [stroke] appear to generate errors - when I hover over any of them I can see:

```<code>Type 'ApexChart | undefined' is not assignable to type 'ApexChart'.
  Type 'undefined' is not assignable to type 'ApexChart'.ngtsc(2322)
my-chart.component.ts(12, 10): Error occurs in the template of component MyChartComponent.
</code>```

The project was created with Angular 14, but the version installed on the PC is Angular 15.

Can anyone advise what might be missing or what might be causing those errors?

In the same project charts-js is used and there's no issues - all charts-js charts are rendered correctly without errors.

Body:
I am following the example given in ApexCharts website to create candlestick with line combo chart in Angular. There's also a sandbox given.

Basically the way I am following the 'presciption' given in the webpage above by copying and pasting with very little modifications, so the component code is 99.99% identical (I removed some data). The code compiles fine before I define the template. However when I add the template code - most of the elements are not recognised.

If the template code is as follows:

  <apx-chart
    [series]="chartOptions.series"
    [chart]="chartOptions.chart"
    [xaxis]="chartOptions.xaxis"
    [title]="chartOptions.title"
    [tooltip]="chartOptions.tooltip"
    [stroke]="chartOptions.stroke"
  ></apx-chart>

only the [stroke] element is not getting a red underline marking an error. All the elements above [stroke] appear to generate errors - when I hover over any of them I can see:

Type 'ApexChart | undefined' is not assignable to type 'ApexChart'.
  Type 'undefined' is not assignable to type 'ApexChart'.ngtsc(2322)
my-chart.component.ts(12, 10): Error occurs in the template of component MyChartComponent.

The project was created with Angular 14, but the version installed on the PC is Angular 15.

Can anyone advise what might be missing or what might be causing those errors?

In the same project charts-js is used and there's no issues - all charts-js charts are rendered correctly without errors.


问:
Firebase change file name on download
I want to download a file but before that i would like to remove the prefix I've put

Current Code:

```<code>    getDownloadURL(ref(storage, props.fullPath))
    .then((url) => {
      const xhr = new XMLHttpRequest();
      xhr.responseType = 'blob';
      xhr.onload = (event) => {
        const blob = xhr.response;
      };
      xhr.open('GET', url);
      xhr.send();
      window.open(url, '_blank', 'noreferrer').focus();

    })
    .catch((error) => {
      console.log("download file error ", error)
    });
</code>```

E.g:

file name in database:
Data.csv7d931632-a562-4d7c-9b9c-d00a90a545e0

file name on download:
Data.csv

Title: Firebase change file name on download

Body:
I want to download a file but before that i would like to remove the prefix I've put

Current Code:

    getDownloadURL(ref(storage, props.fullPath))
    .then((url) => {
      const xhr = new XMLHttpRequest();
      xhr.responseType = 'blob';
      xhr.onload = (event) => {
        const blob = xhr.response;
      };
      xhr.open('GET', url);
      xhr.send();
      window.open(url, '_blank', 'noreferrer').focus();

    })
    .catch((error) => {
      console.log("download file error ", error)
    });

E.g:

file name in database:
Data.csv7d931632-a562-4d7c-9b9c-d00a90a545e0

file name on download:
Data.csv


问:
How to use cronbach alpha to check the internal validity of the first dimension?
I have this example dataset that I applied MCA as follows

```<code>library("FactoMineR")
library("factoextra")

data(poison)

poison.active <- poison[1:55, 5:15]

res.mca <- MCA(poison.active, graph = FALSE)
</code>```

The graph

I want to use cronbach alpha to check the internal validity of the first dimension. I know how to do it using PCA but it is not working with MCA as the variables are categorical.

Body:
I have this example dataset that I applied MCA as follows

library("FactoMineR")
library("factoextra")

data(poison)

poison.active <- poison[1:55, 5:15]

res.mca <- MCA(poison.active, graph = FALSE)

The graph

I want to use cronbach alpha to check the internal validity of the first dimension. I know how to do it using PCA but it is not working with MCA as the variables are categorical.


问:
Is it possible to add/modify system include path without modifying cmake in clion?
I'm working on a cross-platform project which requires dependencies which are not available on my machine. I basically use a cross-platform tool-chain in docker to build everything. Using buildroot I build a whole Linux system for an ARM platform.

So, I was wondering if there is an option to let Clion know or pick another path for system include header files? Then at least clion can help with code completion etc.


问:
error Xcode build: Undefined symbol: _OBJC_CLASS_$_FMDatabaseQueue
I'm having trouble when I'm building app on Xcode.
I'm getting below error

error build: Undefined symbol: OBJC_CLASS$_FMDatabaseQueue

Please help !

Thanks in advance.


问:
Adding Error Bars to ggplot2 scatter in R?
I am very new to R studio so sorry if the question is a bit simplistic. I am attempting to do a simple plot of my data with added error bars and an annotation of my P value, I also would like to change the labels currently present on my graph.

```<code>geom_errorbar(data = combinedsum,
                aes(x = Salt_concentration, ymin = mean - se, ymax = mean + se),
                width = 0.3)
geom_errorbar(data = combinedsum,
              aes(x = Salt_concentration, ymin = mean, ymax = mean),
              width = 0.2)
scale_y_continuous(name = "Generation time (Minutes)",
                   limits = c(0, 180),
                   expand = c(0, 0)) +
scale_x_discrete(name = "Salt concentration (%)", expand(0,0), limits = c(0, 10.3), breaks = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
annotate("text", x = 1.5,  y = 75,
         label = expression(italic(p)~"= 3.647e-05")) +
  theme_classic()
</code>```

Any help would be greatly appreciated. Thank you!

Body:
I am very new to R studio so sorry if the question is a bit simplistic. I am attempting to do a simple plot of my data with added error bars and an annotation of my P value, I also would like to change the labels currently present on my graph.

geom_errorbar(data = combinedsum,
                aes(x = Salt_concentration, ymin = mean - se, ymax = mean + se),
                width = 0.3)
geom_errorbar(data = combinedsum,
              aes(x = Salt_concentration, ymin = mean, ymax = mean),
              width = 0.2)
scale_y_continuous(name = "Generation time (Minutes)",
                   limits = c(0, 180),
                   expand = c(0, 0)) +
scale_x_discrete(name = "Salt concentration (%)", expand(0,0), limits = c(0, 10.3), breaks = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
annotate("text", x = 1.5,  y = 75,
         label = expression(italic(p)~"= 3.647e-05")) +
  theme_classic()

Any help would be greatly appreciated. Thank you!


问:
Got the error when "import tensorflow as tf". Any solutions?
I got the following error while importing TensorFlow. Is there any way this error can be solved?


问:
Template alternative for macros
I want to implement a macro like below

#define LogDebug(x) #ifdef _DEBUG #x #endif
```

But due to limitation of macros, above code was not possible. So what could be a template alternative for the above macro?

Title: Template alternative for macros

Body:
I want to implement a macro like below

#define LogDebug(x) #ifdef _DEBUG #x #endif

But due to limitation of macros, above code was not possible. So what could be a template alternative for the above macro?


问:
Wait for room's insert (suspend) function to return a value
I have the following requirement:

I wanted to get a long string from internet

Store it locally

Notify user about this

For step 1, I have the following repository functions:

```<code>fun getDataFromInternet() = flow<String> {
    // emits the data string from internet, else empty string
}

fun getString() = flow<String> {
    getDataFromInternet().collect{
        if (it.isNotEmpty()){
            appDao.insertString(it)
            // after successful execution of the above insert I want to emit("got data") or emit("") otherwise
        }
    }
}

</code>```

For step 2, I have a DAO with Room's Insert function:

```<code>@Dao

interface AppDAO {
    ...
    ...

    @Insert
    suspend fun insertString(largeString: String): Long
    ...
    ...
}
</code>```

But since the insertString() function is a suspend function how can I ensure that the insertion is completed, before I move step 3?

In the documentation it states

If the @Insert method receives a single parameter, it can return a long value, which is the new rowId for the inserted item.

Why does it say can in the statement? This is another confusion.

Body:
I have the following requirement:

I wanted to get a long string from internet

Store it locally

Notify user about this

For step 1, I have the following repository functions:

fun getDataFromInternet() = flow<String> {
    // emits the data string from internet, else empty string
}

fun getString() = flow<String> {
    getDataFromInternet().collect{
        if (it.isNotEmpty()){
            appDao.insertString(it)
            // after successful execution of the above insert I want to emit("got data") or emit("") otherwise
        }
    }
}

For step 2, I have a DAO with Room's Insert function:

@Dao

interface AppDAO {
    ...
    ...

    @Insert
    suspend fun insertString(largeString: String): Long
    ...
    ...
}

But since the insertString() function is a suspend function how can I ensure that the insertion is completed, before I move step 3?

In the documentation it states

If the @Insert method receives a single parameter, it can return a long value, which is the new rowId for the inserted item.

Why does it say can in the statement? This is another confusion.


问:
Reuse AWS External Application LoadBalancer with same DNS name on reinstall/delete service on EKS
I have 1-2 Kubernetes LoadBalancer services and I want to keep the LoadBalancer DNS name same on recreation or deletion of these services.

The changes to LoadBalancer kubernetes services lead to deletion of previous loadbalancer which also changes the DNS name of LoadBalancer.

How can reuse the Loadbalancer when the services are recreated? I checked AWS load balancer controller but didn't find the exact step to implement when services
are recreated.


问:
What is the right way of deploying a typescript application in production?
I have a typescript and nodejs backend application which exposes some REST APIs. I want to deploy this application in production. I have all my typescript files inside a src/ directory which are compiled to js files inside dist/ directory. I have also installed all my typescript dependencies as dev dependencies.

```<code>  "devDependencies": {
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.15",
    "@types/express-session": "^1.17.5",
    "@types/mongoose": "^5.11.97",
    "@types/node": "^18.11.18",
    "nodemon": "^2.0.20",
    "typescript": "^4.9.4"
  }
</code>```

Now I can think of two options of running the above application in production.

Commiting the dist/ folder and then running the application using node dist/app.js. This method is generally not recommended as build artifacts can easily be reproduced.

Using npm install instead of npm install --omit=dev which will allow me to build the application using tsc and then run it. If I go about this way then having typescript and all the types as dev dependencies don't even make sense.

What is the right way of deploying my typescript application in production and is there a better setup for deploying it?

Body:
I have a typescript and nodejs backend application which exposes some REST APIs. I want to deploy this application in production. I have all my typescript files inside a src/ directory which are compiled to js files inside dist/ directory. I have also installed all my typescript dependencies as dev dependencies.

  "devDependencies": {
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.15",
    "@types/express-session": "^1.17.5",
    "@types/mongoose": "^5.11.97",
    "@types/node": "^18.11.18",
    "nodemon": "^2.0.20",
    "typescript": "^4.9.4"
  }

Now I can think of two options of running the above application in production.

Commiting the dist/ folder and then running the application using node dist/app.js. This method is generally not recommended as build artifacts can easily be reproduced.

Using npm install instead of npm install --omit=dev which will allow me to build the application using tsc and then run it. If I go about this way then having typescript and all the types as dev dependencies don't even make sense.

What is the right way of deploying my typescript application in production and is there a better setup for deploying it?


问:
Dynamically position two backgrounds rendered across multiple divs
using background CSS property I have combined two different images (front and back). These images are being split onto multiple divs.

Though what I'm currently struggling with is that the front image is not being centered vertically & horizontally across the whole piece also depending on the image dimensions, I am getting different results. Right now the front image is bigger than expected and it's being drawn at the beginning of the container instead of the center.

I have added minimal reproducible code example that can be found here:
https://codesandbox.io/s/relaxed-gagarin-iw7euq?file=/src/Piece.js:361-400
To run it just: select image > select mode

Expected outcome:


问:
SignalR validation on client side in react with .net core API
Is there any security benefits or any other purpose to implement client side validation using SignalR.

In one of project I have seen that, using SignalR they are validating the react form by calling the api in .net core api.


问:
SDK for MediaTek and Documentation
How can we get (paying) the SDK for MediaTek MTK7526G/MTK7525 and courses about that?
I need to customize router firmware with that chipset to that i only need the knowledge to uncompact and compact again to work in tbhis chipset format.

Regards,

fueripe at outlook dot com.

Someone how can help with a way to do that or can show me where i can find that info to me learn about that.

Title: SDK for MediaTek and Documentation


问:
Unable to write waxman graph using graphml in Networkx
I am trying to generate the Waxman random graph using the built-in function which works fine and generates the Waxman graph.

Later in my code,  I am writing the above-generated graph using graphml as:
nx.write_graphml(my_graph_waxman, "waxman_Iteration.graphml")

This writing function gives the error:

networkx.exception.NetworkXError: GraphML writer does not support <class 'tuple'> as data values.

My complete code is here:

```<code>import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

my_graph_waxman=nx.waxman_graph(6, beta=0.8, alpha=0.6, L=None, domain=(0, 0, 1, 1), metric=None, seed=None)
nx.draw(my_graph_waxman, with_labels=True, font_weight='normal')

plt.axis('on')
plt.show()
nx.write_graphml(my_graph_waxman, "waxman_Iteration.graphml")
</code>```

Body:
I am trying to generate the Waxman random graph using the built-in function which works fine and generates the Waxman graph.

Later in my code,  I am writing the above-generated graph using graphml as:
nx.write_graphml(my_graph_waxman, "waxman_Iteration.graphml")

This writing function gives the error:

networkx.exception.NetworkXError: GraphML writer does not support <class 'tuple'> as data values.

My complete code is here:

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

my_graph_waxman=nx.waxman_graph(6, beta=0.8, alpha=0.6, L=None, domain=(0, 0, 1, 1), metric=None, seed=None)
nx.draw(my_graph_waxman, with_labels=True, font_weight='normal')

plt.axis('on')
plt.show()
nx.write_graphml(my_graph_waxman, "waxman_Iteration.graphml")


问:
How do I implement Frequency Pattern growth algorithm on 100s of millions of transactions?
I need to implement a "frequently bought together" recommendation engine on my website. I did my research and figured out that FP growth would be the most appropriate algorithm for such an application. However, I am not able to find any solution/library available on the internet to implement it on my transactions that can work for millions of records.

The pyfpgrowth algorithm is taking forever and pyspark seems to not yield results as soon as I increase the size to over 500.

Please help me with a solution.


问:
What module/s can I use to open a pdf with python that works after I converted it to an apk?
I'm trying to make an android app that opens a pdf file on a click of a button. I am using the modules kivy as gui, subprocess to open a pdf and it worked on my PC but after converting it to an apk with buildozer, the gui works but the button to open a pdf is not working, the button can be seen that it is being pressed but does not do its function. I tried to find the mistake in my code, searching what's wrong and then I found a statement that says the subprocess module does not work on android.

I then used the webbrowser module, same as above it was working on my PC but after it got converted the gui works but when the I click the button that opens a pdf, the app crashes. I would like to see if there's a fix using webbrowser as it looks more promising than looking for another module

Below are the .py files for the one I used subprocess on and then webbrowser.

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

Using webbrowser

```<code>    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    import webbrowser

    file_path = r"file://C:\Users\...\...\...\sample.pdf"

    class WelcomeScreen(Screen):
        pass

    class SecondScreen(Screen):
        def openPDF(self):
            webbrowser.open_new(file_path)

    class WindowManager(ScreenManager):
        pass

    kv = Builder.load_file('design.kv')

    class MAINAPP(App):
        def build(self):
            return kv

    if __name__ == '__main__':
        MAINAPP().run()
</code>```
```<code>
</code>```
```<code>
</code>```

Using Subprocess

```<code>    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    import webbrowser

    file_path = "C:\Users\...\...\...\sample.pdf"

    class WelcomeScreen(Screen):
        pass

    class SecondScreen(Screen):
        def openPDF(self):
            subprocess.Popen((file_path), shell=True)

    class WindowManager(ScreenManager):
        pass

    kv = Builder.load_file('design.kv')

    class MAINAPP(App):
        def build(self):
            return kv

    if __name__ == '__main__':
        MAINAPP().run()
</code>```
```<code>
</code>```

Body:
I'm trying to make an android app that opens a pdf file on a click of a button. I am using the modules kivy as gui, subprocess to open a pdf and it worked on my PC but after converting it to an apk with buildozer, the gui works but the button to open a pdf is not working, the button can be seen that it is being pressed but does not do its function. I tried to find the mistake in my code, searching what's wrong and then I found a statement that says the subprocess module does not work on android.

I then used the webbrowser module, same as above it was working on my PC but after it got converted the gui works but when the I click the button that opens a pdf, the app crashes. I would like to see if there's a fix using webbrowser as it looks more promising than looking for another module

Below are the .py files for the one I used subprocess on and then webbrowser.

Using webbrowser

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    import webbrowser

    file_path = r"file://C:\Users\...\...\...\sample.pdf"

    class WelcomeScreen(Screen):
        pass

    class SecondScreen(Screen):
        def openPDF(self):
            webbrowser.open_new(file_path)

    class WindowManager(ScreenManager):
        pass

    kv = Builder.load_file('design.kv')

    class MAINAPP(App):
        def build(self):
            return kv

    if __name__ == '__main__':
        MAINAPP().run()

Using Subprocess

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    import webbrowser

    file_path = "C:\Users\...\...\...\sample.pdf"

    class WelcomeScreen(Screen):
        pass

    class SecondScreen(Screen):
        def openPDF(self):
            subprocess.Popen((file_path), shell=True)

    class WindowManager(ScreenManager):
        pass

    kv = Builder.load_file('design.kv')

    class MAINAPP(App):
        def build(self):
            return kv

    if __name__ == '__main__':
        MAINAPP().run()