问:
Why is my flutter widgets not working when in a different state management
I bought an online template app and i am trying to hardcode my email and password credentials in my flutter frontend because i don't have access to the backend api yet to change from email/password auth to phone auth, so i want to force code the logic into my flutter widget.

This means i am trying to implement the  onPressed: () { controller.login(); }, function on a login button to get me to the home screen with my customized widget.

The original code given to me works fine when i hardcode the credentials in the text form field but when i hardcode the text form field in my customized widget and use same onPressed: () { controller.login(); }, function it don't work.

I want to know if it's because of i'm in a different state management or there's something i'm failing to do.

I will give the original code and my customized UI code in the snippets for comparison.

PS: i even tried to use same text form field in my widget but hide it with Visibility() in flutter. When i use Visibility() in the original code,  onPressed: () { controller.login(); }, works but when i use it in my customized widget, it doest.

How do work around this? If you need more clarification, i am willing to offer. Thanks.

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../common/helper.dart';
import '../../../../../common/ui.dart';
import '../../../../models/setting_model.dart';
import '../../../../routes/app_routes.dart';
import '../../../../services/settings_service.dart';
import '../../../global_widgets/block_button_widget.dart';
import '../../../global_widgets/circular_loading_widget.dart';
import '../../../global_widgets/text_field_widget.dart';
import '../../controllers/auth_controller.dart';

class LoginView extends GetView<AuthController> {
  final Setting _settings = Get.find<SettingsService>().setting.value;

  @override
  Widget build(BuildContext context) {
    controller.loginFormKey = new GlobalKey<FormState>();
    return Visibility(
      visible: false,
      child: WillPopScope(
        onWillPop: Helper().onWillPop,
        child: Scaffold(
          appBar: AppBar(
            title: Text(
              "Login".tr,
              style: Get.textTheme.headline6
                  .merge(TextStyle(color: context.theme.primaryColor)),
            ),
            centerTitle: true,
            backgroundColor: Get.theme.colorScheme.secondary,
            automaticallyImplyLeading: false,
            elevation: 0,
          ),
          body: Form(
            key: controller.loginFormKey,
            child: ListView(
              primary: true,
              children: [
                Stack(
                  alignment: AlignmentDirectional.bottomCenter,
                  children: [
                    Container(
                      height: 180,
                      width: Get.width,
                      decoration: BoxDecoration(
                        color: Get.theme.colorScheme.secondary,
                        borderRadius:
                            BorderRadius.vertical(bottom: Radius.circular(10)),
                        boxShadow: [
                          BoxShadow(
                              color: Get.theme.focusColor.withOpacity(0.2),
                              blurRadius: 10,
                              offset: Offset(0, 5)),
                        ],
                      ),
                      margin: EdgeInsets.only(bottom: 50),
                      child: Padding(
                        padding: const EdgeInsets.all(20),
                        child: Column(
                          children: [
                            Text(
                              _settings.salonAppName,
                              style: Get.textTheme.headline6.merge(TextStyle(
                                  color: Get.theme.primaryColor, fontSize: 24)),
                            ),
                            SizedBox(height: 5),
                            Text(
                              "Welcome to the best salon service system!".tr,
                              style: Get.textTheme.caption.merge(
                                  TextStyle(color: Get.theme.primaryColor)),
                              textAlign: TextAlign.center,
                            ),
                            // Text("Fill the following credentials to login your account", style: Get.textTheme.caption.merge(TextStyle(color: Get.theme.primaryColor))),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      decoration: Ui.getBoxDecoration(
                        radius: 14,
                        border:
                            Border.all(width: 5, color: Get.theme.primaryColor),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                        child: Image.asset(
                          'assets/icon/icon.png',
                          fit: BoxFit.cover,
                          width: 100,
                          height: 100,
                        ),
                      ),
                    ),
                  ],
                ),
                Obx(() {
                  if (controller.loading.isTrue)
                    return CircularLoadingWidget(height: 300);
                  else {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Visibility(
                          visible: false,
                          maintainState: true,
                          child: TextFieldWidget(
                            labelText: "Email Address".tr,
                            hintText: "johndoe@gmail.com".tr,
                            initialValue: 'salon@demo.com',
                            onSaved: (input) =>
                                controller.currentUser.value.email = input,
                            validator: (input) => !input.contains('@')
                                ? "Should be a valid email".tr
                                : null,
                            iconData: Icons.alternate_email,
                          ),
                        ),
                        Obx(() {
                          return Visibility(
                            visible: false,
                            maintainState: true,
                            child: TextFieldWidget(
                              labelText: "Password".tr,
                              hintText: "••••••••••••".tr,
                              initialValue: '123456',
                              onSaved: (input) =>
                                  controller.currentUser.value.password = input,
                              validator: (input) => input.length < 3
                                  ? "Should be more than 3 characters".tr
                                  : null,

                            ),
                          );
                        }),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            TextButton(
                              onPressed: () {
                                Get.toNamed(Routes.FORGOT_PASSWORD);
                              },
                              child: Text("Forgot Password?".tr),
                            ),
                          ],
                        ).paddingSymmetric(horizontal: 20),
                        BlockButtonWidget(
                          onPressed: () {
                            controller.login();
                          },
                          color: Get.theme.colorScheme.secondary,
                          text: Text(
                            "Login".tr,
                            style: Get.textTheme.headline6.merge(
                                TextStyle(color: Get.theme.primaryColor)),
                          ),
                        ).paddingSymmetric(vertical: 10, horizontal: 20),
                        TextButton(
                          onPressed: () {
                            //Get.toNamed(Routes.REGISTER);
                          },
                          child: Text("You don't have an account?".tr),
                        ).paddingOnly(top: 20),
                        GestureDetector(
                          onTap: () {
                            Get.toNamed(Routes.SETTINGS_LANGUAGE);
                          },
                          child: Text(
                            Get.locale.toString().tr,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ],
                    );
                  }
                }),
              ],
            ),
          ),
        ),
      ),
    );
  }
}```
</div>
</div>
</p>
<p>THIS IS THE ORIGINAL WIDGET CODE</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../routes/app_routes.dart';
import '../../../global_widgets/circular_loading_widget.dart';
import '../../../global_widgets/text_field_widget.dart';
import '../../controllers/auth_controller.dart';
import 'login_view.dart';
import 'pin_number.dart';

import 'keyboard_number.dart';

class PinScreen extends StatefulWidget {
  const PinScreen({Key key}) : super(key: key);

  @override
  State<PinScreen> createState() => _PinScreenState();
}

class _PinScreenState extends State<PinScreen> {
  List<String> currentPin = ["", "", "", ""];

  TextEditingController pinOneController = TextEditingController();
  TextEditingController pinTwoController = TextEditingController();
  TextEditingController pinThreeController = TextEditingController();
  TextEditingController pinFourController = TextEditingController();

  var outlineInputBorder = OutlineInputBorder(
    borderRadius: BorderRadius.circular(10),
    borderSide: BorderSide(color: Colors.transparent),
  );

  int pinIndex = 0;
  @override
  Widget build(BuildContext context) {
    final controller = Get.find<AuthController>();

    controller.loginFormKey = new GlobalKey<FormState>();
    return Form(
      key: controller.loginFormKey,
      child: SafeArea(
        child: Column(
          children: [
            buildExitButton(),
            Obx(() {
              if (controller.loading.isTrue)
                return CircularLoadingWidget(height: 300);
              else {
                return Expanded(
                  child: Container(
                    alignment: Alignment(0, 0.5),
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        buildSecurityText(),
                        SizedBox(height: 20.0),
                        buildPinRow(),
                        SizedBox(height: 10.0),
                        buildNumberPad(),
                        SizedBox(height: 20.0),
                        Visibility(
                          visible: false,
                          maintainState: true,
                          child: TextFieldWidget(
                            labelText: "Email Address".tr,
                            hintText: "johndoe@gmail.com".tr,
                            initialValue: 'salon@demo.com',
                            validator: (input) => !input.contains('@')
                                ? "Should be a valid email".tr
                                : null,
                            iconData: Icons.alternate_email,
                          ),
                        ),
                        Obx(() {
                          return Visibility(
                            visible: false,
                            maintainState: true,
                            child: TextFieldWidget(
                              labelText: "Password".tr,
                              hintText: "••••••••••••".tr,
                              initialValue: '123456',
                              validator: (input) => input.length < 3
                                  ? "Should be more than 3 characters".tr
                                  : null,
                              iconData: Icons.lock_outline,
                              keyboardType: TextInputType.visiblePassword,
                              suffixIcon: IconButton(
                                onPressed: () {
                                  controller.hidePassword.value =
                                      !controller.hidePassword.value;
                                },
                                color: Theme.of(context).focusColor,
                                icon: Icon(controller.hidePassword.value
                                    ? Icons.visibility_outlined
                                    : Icons.visibility_off_outlined),
                              ),
                            ),
                          );
                        }),
                        Container(
                          child: new RichText(
                            text: new TextSpan(
                              children: [
                                new TextSpan(
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      // Get.toNamed(Routes.REGISTER);
                                    },
                                  text: 'Forgot Pin ?',
                                  style: new TextStyle(
                                      color: Color(0xff3498DB),
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500),
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 20.0),
                        MaterialButton(
                          onPressed: () {
                            controller.login();
                          },
                          color: Color(0xff34495E),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.18),
                          ),
                          padding: EdgeInsets.symmetric(
                              horizontal: 30, vertical: 10),
                          minWidth: double.infinity,
                          child: Text(
                            'Next',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                        SizedBox(height: 32.0),
                      ],
                    ),
                  ),
                );
              }
            })
          ],
        ),
      ),
    );
  }

  buildNumberPad() {
    return Expanded(
      child: Container(
        alignment: Alignment.bottomCenter,
        child: Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  KeyboardNumber(
                    n: 1,
                    onPressed: () {
                      pinIndexSetup("1");
                    },
                  ),
                  KeyboardNumber(
                    n: 2,
                    onPressed: () {
                      pinIndexSetup("2");
                    },
                  ),
                  KeyboardNumber(
                    n: 3,
                    onPressed: () {
                      pinIndexSetup("3");
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  KeyboardNumber(
                    n: 4,
                    onPressed: () {
                      pinIndexSetup("4");
                    },
                  ),
                  KeyboardNumber(
                    n: 5,
                    onPressed: () {
                      pinIndexSetup("5");
                    },
                  ),
                  KeyboardNumber(
                    n: 6,
                    onPressed: () {
                      pinIndexSetup("6");
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  KeyboardNumber(
                    n: 7,
                    onPressed: () {
                      pinIndexSetup("7");
                    },
                  ),
                  KeyboardNumber(
                    n: 8,
                    onPressed: () {
                      pinIndexSetup("8");
                    },
                  ),
                  KeyboardNumber(
                    n: 9,
                    onPressed: () {
                      pinIndexSetup("9");
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Container(
                    width: 60.0,
                    child: MaterialButton(
                      onPressed: null,
                      child: SizedBox(),
                    ),
                  ),
                  KeyboardNumber(
                    n: 0,
                    onPressed: () {
                      pinIndexSetup("0");
                    },
                  ),
                  Container(
                    width: 60.0,
                    child: MaterialButton(
                      onPressed: () {
                        clearPin();
                      },
                      height: 60.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(60.0),
                      ),
                      child: Image.asset(
                        'assets/icon/clear-symbol.png',
                      ),
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  clearPin() {
    if (pinIndex == 0)
      pinIndex = 0;
    else if (pinIndex == 4) {
      setPin(pinIndex, "");
      currentPin[pinIndex - 1] = "";
      pinIndex--;
    } else {
      setPin(pinIndex, "");
      currentPin[pinIndex - 1] = "";
      pinIndex--;
    }
  }

  pinIndexSetup(String text) {
    if (pinIndex == 0)
      pinIndex = 1;
    else if (pinIndex < 4) pinIndex++;
    setPin(pinIndex, text);
    currentPin[pinIndex - 1] = text;
    String strPin = "";
    currentPin.forEach((e) {
      strPin += e;
    });
    if (pinIndex == 4) print(strPin);
  }

  setPin(int n, String text) {
    switch (n) {
      case 1:
        pinOneController.text = text;
        break;
      case 2:
        pinTwoController.text = text;
        break;
      case 3:
        pinThreeController.text = text;
        break;
      case 4:
        pinFourController.text = text;
        break;
    }
  }

  buildExitButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: MaterialButton(
            onPressed: () {
              Navigator.pop(context);
            },
            height: 50.0,
            minWidth: 50.0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(50.0),
            ),
            child: Icon(
              Icons.clear,
              color: Colors.black54,
            ),
          ),
        ),
      ],
    );
  }

  buildSecurityText() {
    return Column(
      children: [
        Align(
          alignment: Alignment.topLeft,
          child: Text(
            'Enter PIN',
            style: TextStyle(
              color: Color(0xff151515),
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        SizedBox(
          height: 12,
        ),
        Align(
          alignment: Alignment.topLeft,
          child: Padding(
            padding: const EdgeInsets.only(right: 80),
            child: Text(
              'Enter 4 digit PIN to access your account ',
              style: TextStyle(
                color: Color(0xff151515),
                fontSize: 14,
                fontWeight: FontWeight.w500,
                fontStyle: FontStyle.normal,
              ),
            ),
          ),
        ),
      ],
    );
  }

  buildPinRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinOneController,
        ),
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinTwoController,
        ),
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinThreeController,
        ),
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinFourController,
        ),
      ],
    );
  }
}</code>```

THIS IS MY CUSTOMIZED WIDGET TREE/CODE

Body:
I bought an online template app and i am trying to hardcode my email and password credentials in my flutter frontend because i don't have access to the backend api yet to change from email/password auth to phone auth, so i want to force code the logic into my flutter widget.

This means i am trying to implement the  onPressed: () { controller.login(); }, function on a login button to get me to the home screen with my customized widget.

The original code given to me works fine when i hardcode the credentials in the text form field but when i hardcode the text form field in my customized widget and use same onPressed: () { controller.login(); }, function it don't work.

I want to know if it's because of i'm in a different state management or there's something i'm failing to do.

I will give the original code and my customized UI code in the snippets for comparison.

PS: i even tried to use same text form field in my widget but hide it with Visibility() in flutter. When i use Visibility() in the original code,  onPressed: () { controller.login(); }, works but when i use it in my customized widget, it doest.

How do work around this? If you need more clarification, i am willing to offer. Thanks.

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../common/helper.dart';
import '../../../../../common/ui.dart';
import '../../../../models/setting_model.dart';
import '../../../../routes/app_routes.dart';
import '../../../../services/settings_service.dart';
import '../../../global_widgets/block_button_widget.dart';
import '../../../global_widgets/circular_loading_widget.dart';
import '../../../global_widgets/text_field_widget.dart';
import '../../controllers/auth_controller.dart';

class LoginView extends GetView<AuthController> {
  final Setting _settings = Get.find<SettingsService>().setting.value;

  @override
  Widget build(BuildContext context) {
    controller.loginFormKey = new GlobalKey<FormState>();
    return Visibility(
      visible: false,
      child: WillPopScope(
        onWillPop: Helper().onWillPop,
        child: Scaffold(
          appBar: AppBar(
            title: Text(
              "Login".tr,
              style: Get.textTheme.headline6
                  .merge(TextStyle(color: context.theme.primaryColor)),
            ),
            centerTitle: true,
            backgroundColor: Get.theme.colorScheme.secondary,
            automaticallyImplyLeading: false,
            elevation: 0,
          ),
          body: Form(
            key: controller.loginFormKey,
            child: ListView(
              primary: true,
              children: [
                Stack(
                  alignment: AlignmentDirectional.bottomCenter,
                  children: [
                    Container(
                      height: 180,
                      width: Get.width,
                      decoration: BoxDecoration(
                        color: Get.theme.colorScheme.secondary,
                        borderRadius:
                            BorderRadius.vertical(bottom: Radius.circular(10)),
                        boxShadow: [
                          BoxShadow(
                              color: Get.theme.focusColor.withOpacity(0.2),
                              blurRadius: 10,
                              offset: Offset(0, 5)),
                        ],
                      ),
                      margin: EdgeInsets.only(bottom: 50),
                      child: Padding(
                        padding: const EdgeInsets.all(20),
                        child: Column(
                          children: [
                            Text(
                              _settings.salonAppName,
                              style: Get.textTheme.headline6.merge(TextStyle(
                                  color: Get.theme.primaryColor, fontSize: 24)),
                            ),
                            SizedBox(height: 5),
                            Text(
                              "Welcome to the best salon service system!".tr,
                              style: Get.textTheme.caption.merge(
                                  TextStyle(color: Get.theme.primaryColor)),
                              textAlign: TextAlign.center,
                            ),
                            // Text("Fill the following credentials to login your account", style: Get.textTheme.caption.merge(TextStyle(color: Get.theme.primaryColor))),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      decoration: Ui.getBoxDecoration(
                        radius: 14,
                        border:
                            Border.all(width: 5, color: Get.theme.primaryColor),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                        child: Image.asset(
                          'assets/icon/icon.png',
                          fit: BoxFit.cover,
                          width: 100,
                          height: 100,
                        ),
                      ),
                    ),
                  ],
                ),
                Obx(() {
                  if (controller.loading.isTrue)
                    return CircularLoadingWidget(height: 300);
                  else {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Visibility(
                          visible: false,
                          maintainState: true,
                          child: TextFieldWidget(
                            labelText: "Email Address".tr,
                            hintText: "johndoe@gmail.com".tr,
                            initialValue: 'salon@demo.com',
                            onSaved: (input) =>
                                controller.currentUser.value.email = input,
                            validator: (input) => !input.contains('@')
                                ? "Should be a valid email".tr
                                : null,
                            iconData: Icons.alternate_email,
                          ),
                        ),
                        Obx(() {
                          return Visibility(
                            visible: false,
                            maintainState: true,
                            child: TextFieldWidget(
                              labelText: "Password".tr,
                              hintText: "••••••••••••".tr,
                              initialValue: '123456',
                              onSaved: (input) =>
                                  controller.currentUser.value.password = input,
                              validator: (input) => input.length < 3
                                  ? "Should be more than 3 characters".tr
                                  : null,

                            ),
                          );
                        }),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            TextButton(
                              onPressed: () {
                                Get.toNamed(Routes.FORGOT_PASSWORD);
                              },
                              child: Text("Forgot Password?".tr),
                            ),
                          ],
                        ).paddingSymmetric(horizontal: 20),
                        BlockButtonWidget(
                          onPressed: () {
                            controller.login();
                          },
                          color: Get.theme.colorScheme.secondary,
                          text: Text(
                            "Login".tr,
                            style: Get.textTheme.headline6.merge(
                                TextStyle(color: Get.theme.primaryColor)),
                          ),
                        ).paddingSymmetric(vertical: 10, horizontal: 20),
                        TextButton(
                          onPressed: () {
                            //Get.toNamed(Routes.REGISTER);
                          },
                          child: Text("You don't have an account?".tr),
                        ).paddingOnly(top: 20),
                        GestureDetector(
                          onTap: () {
                            Get.toNamed(Routes.SETTINGS_LANGUAGE);
                          },
                          child: Text(
                            Get.locale.toString().tr,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ],
                    );
                  }
                }),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

THIS IS THE ORIGINAL WIDGET CODE

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../routes/app_routes.dart';
import '../../../global_widgets/circular_loading_widget.dart';
import '../../../global_widgets/text_field_widget.dart';
import '../../controllers/auth_controller.dart';
import 'login_view.dart';
import 'pin_number.dart';

import 'keyboard_number.dart';

class PinScreen extends StatefulWidget {
  const PinScreen({Key key}) : super(key: key);

  @override
  State<PinScreen> createState() => _PinScreenState();
}

class _PinScreenState extends State<PinScreen> {
  List<String> currentPin = ["", "", "", ""];

  TextEditingController pinOneController = TextEditingController();
  TextEditingController pinTwoController = TextEditingController();
  TextEditingController pinThreeController = TextEditingController();
  TextEditingController pinFourController = TextEditingController();

  var outlineInputBorder = OutlineInputBorder(
    borderRadius: BorderRadius.circular(10),
    borderSide: BorderSide(color: Colors.transparent),
  );

  int pinIndex = 0;
  @override
  Widget build(BuildContext context) {
    final controller = Get.find<AuthController>();

    controller.loginFormKey = new GlobalKey<FormState>();
    return Form(
      key: controller.loginFormKey,
      child: SafeArea(
        child: Column(
          children: [
            buildExitButton(),
            Obx(() {
              if (controller.loading.isTrue)
                return CircularLoadingWidget(height: 300);
              else {
                return Expanded(
                  child: Container(
                    alignment: Alignment(0, 0.5),
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        buildSecurityText(),
                        SizedBox(height: 20.0),
                        buildPinRow(),
                        SizedBox(height: 10.0),
                        buildNumberPad(),
                        SizedBox(height: 20.0),
                        Visibility(
                          visible: false,
                          maintainState: true,
                          child: TextFieldWidget(
                            labelText: "Email Address".tr,
                            hintText: "johndoe@gmail.com".tr,
                            initialValue: 'salon@demo.com',
                            validator: (input) => !input.contains('@')
                                ? "Should be a valid email".tr
                                : null,
                            iconData: Icons.alternate_email,
                          ),
                        ),
                        Obx(() {
                          return Visibility(
                            visible: false,
                            maintainState: true,
                            child: TextFieldWidget(
                              labelText: "Password".tr,
                              hintText: "••••••••••••".tr,
                              initialValue: '123456',
                              validator: (input) => input.length < 3
                                  ? "Should be more than 3 characters".tr
                                  : null,
                              iconData: Icons.lock_outline,
                              keyboardType: TextInputType.visiblePassword,
                              suffixIcon: IconButton(
                                onPressed: () {
                                  controller.hidePassword.value =
                                      !controller.hidePassword.value;
                                },
                                color: Theme.of(context).focusColor,
                                icon: Icon(controller.hidePassword.value
                                    ? Icons.visibility_outlined
                                    : Icons.visibility_off_outlined),
                              ),
                            ),
                          );
                        }),
                        Container(
                          child: new RichText(
                            text: new TextSpan(
                              children: [
                                new TextSpan(
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      // Get.toNamed(Routes.REGISTER);
                                    },
                                  text: 'Forgot Pin ?',
                                  style: new TextStyle(
                                      color: Color(0xff3498DB),
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500),
                                ),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(height: 20.0),
                        MaterialButton(
                          onPressed: () {
                            controller.login();
                          },
                          color: Color(0xff34495E),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.18),
                          ),
                          padding: EdgeInsets.symmetric(
                              horizontal: 30, vertical: 10),
                          minWidth: double.infinity,
                          child: Text(
                            'Next',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                        SizedBox(height: 32.0),
                      ],
                    ),
                  ),
                );
              }
            })
          ],
        ),
      ),
    );
  }

  buildNumberPad() {
    return Expanded(
      child: Container(
        alignment: Alignment.bottomCenter,
        child: Padding(
          padding: const EdgeInsets.only(bottom: 12),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  KeyboardNumber(
                    n: 1,
                    onPressed: () {
                      pinIndexSetup("1");
                    },
                  ),
                  KeyboardNumber(
                    n: 2,
                    onPressed: () {
                      pinIndexSetup("2");
                    },
                  ),
                  KeyboardNumber(
                    n: 3,
                    onPressed: () {
                      pinIndexSetup("3");
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  KeyboardNumber(
                    n: 4,
                    onPressed: () {
                      pinIndexSetup("4");
                    },
                  ),
                  KeyboardNumber(
                    n: 5,
                    onPressed: () {
                      pinIndexSetup("5");
                    },
                  ),
                  KeyboardNumber(
                    n: 6,
                    onPressed: () {
                      pinIndexSetup("6");
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  KeyboardNumber(
                    n: 7,
                    onPressed: () {
                      pinIndexSetup("7");
                    },
                  ),
                  KeyboardNumber(
                    n: 8,
                    onPressed: () {
                      pinIndexSetup("8");
                    },
                  ),
                  KeyboardNumber(
                    n: 9,
                    onPressed: () {
                      pinIndexSetup("9");
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Container(
                    width: 60.0,
                    child: MaterialButton(
                      onPressed: null,
                      child: SizedBox(),
                    ),
                  ),
                  KeyboardNumber(
                    n: 0,
                    onPressed: () {
                      pinIndexSetup("0");
                    },
                  ),
                  Container(
                    width: 60.0,
                    child: MaterialButton(
                      onPressed: () {
                        clearPin();
                      },
                      height: 60.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(60.0),
                      ),
                      child: Image.asset(
                        'assets/icon/clear-symbol.png',
                      ),
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  clearPin() {
    if (pinIndex == 0)
      pinIndex = 0;
    else if (pinIndex == 4) {
      setPin(pinIndex, "");
      currentPin[pinIndex - 1] = "";
      pinIndex--;
    } else {
      setPin(pinIndex, "");
      currentPin[pinIndex - 1] = "";
      pinIndex--;
    }
  }

  pinIndexSetup(String text) {
    if (pinIndex == 0)
      pinIndex = 1;
    else if (pinIndex < 4) pinIndex++;
    setPin(pinIndex, text);
    currentPin[pinIndex - 1] = text;
    String strPin = "";
    currentPin.forEach((e) {
      strPin += e;
    });
    if (pinIndex == 4) print(strPin);
  }

  setPin(int n, String text) {
    switch (n) {
      case 1:
        pinOneController.text = text;
        break;
      case 2:
        pinTwoController.text = text;
        break;
      case 3:
        pinThreeController.text = text;
        break;
      case 4:
        pinFourController.text = text;
        break;
    }
  }

  buildExitButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: MaterialButton(
            onPressed: () {
              Navigator.pop(context);
            },
            height: 50.0,
            minWidth: 50.0,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(50.0),
            ),
            child: Icon(
              Icons.clear,
              color: Colors.black54,
            ),
          ),
        ),
      ],
    );
  }

  buildSecurityText() {
    return Column(
      children: [
        Align(
          alignment: Alignment.topLeft,
          child: Text(
            'Enter PIN',
            style: TextStyle(
              color: Color(0xff151515),
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        SizedBox(
          height: 12,
        ),
        Align(
          alignment: Alignment.topLeft,
          child: Padding(
            padding: const EdgeInsets.only(right: 80),
            child: Text(
              'Enter 4 digit PIN to access your account ',
              style: TextStyle(
                color: Color(0xff151515),
                fontSize: 14,
                fontWeight: FontWeight.w500,
                fontStyle: FontStyle.normal,
              ),
            ),
          ),
        ),
      ],
    );
  }

  buildPinRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinOneController,
        ),
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinTwoController,
        ),
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinThreeController,
        ),
        PINNumber(
          outlineInputBorder: outlineInputBorder,
          textEditingController: pinFourController,
        ),
      ],
    );
  }
}

THIS IS MY CUSTOMIZED WIDGET TREE/CODE


来源: stackexchange

问:
Ingress doen't serve Django's static files
I have a simple app architecture:

A webapp build on Django Rest Framework providing an API

A Nginx reverse proxy used to serve webapp and its static files

A redis container used by webapp

A React app used as frontend

I tried to deploy this using Kubernetes in local first before deploying on the cloud (AWS or something similar).
Here my global deployment file (I intend to split in smaller part after).

apiVersion: v1
kind: Service
metadata:
  name: redis
  labels:
    app: redis
spec:
  ports:
    - port: 6379
      protocol: TCP
      targetPort: 6379
  selector:
    app: redis
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
spec:
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
        - name: redis
          image: redis
          ports:
            - containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
  name: webapp
  labels:
    app: webapp
spec:
  ports:
    - port: 8080
      protocol: TCP
      targetPort: 8080
      name: http
    - port: 8081
      protocol: TCP
      targetPort: 8081
      name: daphne
  selector:
    app: webapp
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
spec:
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
        - name: webapp
          image: registry.gitlab.com/anima879/celestorbe/backend
          imagePullPolicy: Always
          volumeMounts:
            - name: static-data
              mountPath: /vol/web
          env:
            - name: SECRET_KEY
              value: secretkey1234
            - name: ALLOWED_HOSTS
              value: "127.0.0.1,localhost,proxy"
          ports:
            - containerPort: 8080
            - containerPort: 8081
      imagePullSecrets:
        - name: gitlab-registry-secret
      volumes:
        - name: static-data
          hostPath:
            path: static-data
---
apiVersion: v1
kind: Service
metadata:
  name: front
  labels:
    app: front
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 80
  selector:
    app: front
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: front
spec:
  selector:
    matchLabels:
      app: front
  template:
    metadata:
      labels:
        app: front
    spec:
      containers:
        - name: front
          image: registry.gitlab.com/anima879/celestorbe/front
          imagePullPolicy: Always
          volumeMounts:
            - name: static-data
              mountPath: /vol/web
          ports:
            - containerPort: 80
          env:
            - name: REACT_APP_API_URL
              value: webapp
      imagePullSecrets:
        - name: gitlab-registry-secret
      volumes:
        - name: static-data
          hostPath:
            path: static-data
---
apiVersion: v1
kind: Service
metadata:
  name: proxy
  labels:
    app: proxy
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 80
  selector:
    app: proxy
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: proxy
  template:
    metadata:
      labels:
        app: proxy
    spec:
      containers:
        - name: proxy
          image: registry.gitlab.com/anima879/celestorbe/proxy
          imagePullPolicy: Always
          volumeMounts:
            - name: static-data
              mountPath: /vol/web
          ports:
            - containerPort: 80
      imagePullSecrets:
        - name: gitlab-registry-secret
      volumes:
        - name: static-data
          hostPath:
            path: static-data
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: main-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/configuration-snippet: |-
      rewrite ^/api/(.*)$ /$1 break;
      rewrite_log on;
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: front
                port:
                  number: 80
          - path: /api(/|$)(.*)
            pathType: Prefix
            backend:
              service:
                name: proxy
                port:
                  number: 80
          - path: /ws
            pathType: Prefix
            backend:
              service:
                name: proxy
                port:
                  number: 80

```

As you can see, I use an Ingress as the entrance for my application. Every url should go to the frontend by default (so the user have the UI to use the app). But when a request is made to the back, it starts with /api.
For instance:

localhost/login should display the login page from the React app

localhost/api/login should send a login request to the back (with the POST method)

I need to rewrite the url to the back to localhost/login because webapp doesn't understand URL starting with /api.
But if I go in the browser to an API endpoint, Django display a page that allows to use the endpoint.

My problem is here. When I tried to directly access the API from the browser, the CSS are not loaded:

The type of the CSS file are not correct, and I don't know how to solve this.
Also I suspect the Ingress tried to get the CSS from the frontend instead of Django.

I know it is a tricky issue, but if you have a better alternative or some workflow to solve the issue, i would appreciate.

Thank you.

P.S. When I don't use an Ingress and use a LoadBalancer service (On different port for Front and proxy), it works. Except the front can't do request to the back if I don't the IP of the proxy LoadBalancer. Because I want very low coupling, I don't think it is a good idea (But i may be wrong).

ContentLicense: CC BY-SA 4.0

Body:
I have a simple app architecture:

A webapp build on Django Rest Framework providing an API

A Nginx reverse proxy used to serve webapp and its static files

A redis container used by webapp

A React app used as frontend

I tried to deploy this using Kubernetes in local first before deploying on the cloud (AWS or something similar).
Here my global deployment file (I intend to split in smaller part after).

apiVersion: v1
kind: Service
metadata:
  name: redis
  labels:
    app: redis
spec:
  ports:
    - port: 6379
      protocol: TCP
      targetPort: 6379
  selector:
    app: redis
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
spec:
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
        - name: redis
          image: redis
          ports:
            - containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
  name: webapp
  labels:
    app: webapp
spec:
  ports:
    - port: 8080
      protocol: TCP
      targetPort: 8080
      name: http
    - port: 8081
      protocol: TCP
      targetPort: 8081
      name: daphne
  selector:
    app: webapp
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
spec:
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
        - name: webapp
          image: registry.gitlab.com/anima879/celestorbe/backend
          imagePullPolicy: Always
          volumeMounts:
            - name: static-data
              mountPath: /vol/web
          env:
            - name: SECRET_KEY
              value: secretkey1234
            - name: ALLOWED_HOSTS
              value: "127.0.0.1,localhost,proxy"
          ports:
            - containerPort: 8080
            - containerPort: 8081
      imagePullSecrets:
        - name: gitlab-registry-secret
      volumes:
        - name: static-data
          hostPath:
            path: static-data
---
apiVersion: v1
kind: Service
metadata:
  name: front
  labels:
    app: front
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 80
  selector:
    app: front
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: front
spec:
  selector:
    matchLabels:
      app: front
  template:
    metadata:
      labels:
        app: front
    spec:
      containers:
        - name: front
          image: registry.gitlab.com/anima879/celestorbe/front
          imagePullPolicy: Always
          volumeMounts:
            - name: static-data
              mountPath: /vol/web
          ports:
            - containerPort: 80
          env:
            - name: REACT_APP_API_URL
              value: webapp
      imagePullSecrets:
        - name: gitlab-registry-secret
      volumes:
        - name: static-data
          hostPath:
            path: static-data
---
apiVersion: v1
kind: Service
metadata:
  name: proxy
  labels:
    app: proxy
spec:
  ports:
    - port: 80
      protocol: TCP
      targetPort: 80
  selector:
    app: proxy
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: proxy
  template:
    metadata:
      labels:
        app: proxy
    spec:
      containers:
        - name: proxy
          image: registry.gitlab.com/anima879/celestorbe/proxy
          imagePullPolicy: Always
          volumeMounts:
            - name: static-data
              mountPath: /vol/web
          ports:
            - containerPort: 80
      imagePullSecrets:
        - name: gitlab-registry-secret
      volumes:
        - name: static-data
          hostPath:
            path: static-data
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: main-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
    nginx.ingress.kubernetes.io/configuration-snippet: |-
      rewrite ^/api/(.*)$ /$1 break;
      rewrite_log on;
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: front
                port:
                  number: 80
          - path: /api(/|$)(.*)
            pathType: Prefix
            backend:
              service:
                name: proxy
                port:
                  number: 80
          - path: /ws
            pathType: Prefix
            backend:
              service:
                name: proxy
                port:
                  number: 80

As you can see, I use an Ingress as the entrance for my application. Every url should go to the frontend by default (so the user have the UI to use the app). But when a request is made to the back, it starts with /api.
For instance:

localhost/login should display the login page from the React app

localhost/api/login should send a login request to the back (with the POST method)

I need to rewrite the url to the back to localhost/login because webapp doesn't understand URL starting with /api.
But if I go in the browser to an API endpoint, Django display a page that allows to use the endpoint.

My problem is here. When I tried to directly access the API from the browser, the CSS are not loaded:

The type of the CSS file are not correct, and I don't know how to solve this.
Also I suspect the Ingress tried to get the CSS from the frontend instead of Django.

I know it is a tricky issue, but if you have a better alternative or some workflow to solve the issue, i would appreciate.

Thank you.

P.S. When I don't use an Ingress and use a LoadBalancer service (On different port for Front and proxy), it works. Except the front can't do request to the back if I don't the IP of the proxy LoadBalancer. Because I want very low coupling, I don't think it is a good idea (But i may be wrong).


问:
The name 'PermissionGroup' isn't a type so it can't be used as a type argument
All the available solutions online tell me one thing: downgrade permission_handler. But how can I update this code so I can keep the current version of permission_handler?

The code:

```<code>class MyApp extends StatelessWidget {

@override
  Widget build(BuildContext context) {
    UserProvider auth = Provider.of<UserProvider>(context);
// Check if the location permission has been granted
_checkLocationPermission() async {
  PermissionStatus permission = await Permission.location.status;
  if (permission != PermissionStatus.granted) {
    // Location permission is not granted, request it
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler()
            .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] != PermissionStatus.granted) {
      // Location permission was denied
      return false;
    }
  }
  return true;
}

switch (auth.status) {
  case Status.Uninitialized:
    return Splash();
  case Status.Unauthenticated:
  case Status.Authenticating:
    return LoginScreen();
  case Status.Authenticated:
    // Request location permission before showing the home screen
    return FutureBuilder(
      future: _checkLocationPermission(),
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data) {
          // Location permission was granted
          return MyHomePage();
        } else {
          // Location permission was denied or is still being checked
          return Container();
        }
      },
    );
  default:
    return LoginScreen();
}
</code>```

}
}

Body:
All the available solutions online tell me one thing: downgrade permission_handler. But how can I update this code so I can keep the current version of permission_handler?

The code:

class MyApp extends StatelessWidget {

@override
  Widget build(BuildContext context) {
    UserProvider auth = Provider.of<UserProvider>(context);
// Check if the location permission has been granted
_checkLocationPermission() async {
  PermissionStatus permission = await Permission.location.status;
  if (permission != PermissionStatus.granted) {
    // Location permission is not granted, request it
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler()
            .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] != PermissionStatus.granted) {
      // Location permission was denied
      return false;
    }
  }
  return true;
}

switch (auth.status) {
  case Status.Uninitialized:
    return Splash();
  case Status.Unauthenticated:
  case Status.Authenticating:
    return LoginScreen();
  case Status.Authenticated:
    // Request location permission before showing the home screen
    return FutureBuilder(
      future: _checkLocationPermission(),
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data) {
          // Location permission was granted
          return MyHomePage();
        } else {
          // Location permission was denied or is still being checked
          return Container();
        }
      },
    );
  default:
    return LoginScreen();
}

}
}


问:
Google Analytics API authentication failure using JWT
I want to connect to Google Analytics Reporting API to fetch data, For which I have been provided with details of the service account in JSON format which contains details like (type, project_id, client_email, client_id, private_key,client_x509_cert_url, auth_provider_x509_cert_url)

Using this JSON file I am able to connect and fetch required report data via Python code Reporting API quickstart. However, due to business requirements, I have to establish the connection using HTTP Rest API.

So based on the details of the same service account I am trying to authenticate using JWT by referring to Google Docs Addendum: Service account authorization without OAuth so that once I get the signature I can use that as a static token and make next API call to get report data https://analyticsreporting.googleapis.com/v4/reports:batchGet and passing Request Body

But while testing in https://jwt.io/ & also in https://irrte.ch/jwt-js-decode/index.html signature creation is failing with an Invalid Signature error.

Can someone please help to understand what am I missing here?

```<code>Header

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "<service account's private key ID>"
}

Payload

{

  "iss": "<service account's email address i.e. client_email>",
  "sub": "<service account's email address i.e. client_email>",
  "aud": "https://oauth2.googleapis.com/token",
  "iat": <UTC Unix Epoch Start Time>,
  "exp": <UTC Unix Epoch End Time>

}

And then pasted X.509 PUBLIC CERTIFICATE generated for the service account and in Private key pasted Private key again which is from JSON file of service account

-----BEGIN CERTIFICATE-----\nMIrrhherhehrgssreheheherhehehehrhrdsfsfzcsvsvsvscssvsrjnfvdsfsscscscshgeferttyyuuuuuuuuuuudDxE/Q\n-----END CERTIFICATE-----\n

-----BEGIN PRIVATE KEY-----\nLDSVSVSCSYUNJKOLPDFSSSFSFSFSSFSFSFSFSFSFSSFSFSFSFSFSFSFSSSSSSSSSGGGGGGGGGGGGGGGGGGGGGGUUUUUUUUUUUUUUUUUM=\n-----END PRIVATE KEY-----\n
</code>```

PS: I have tried to test with \n without \n as well as with prefixes BEGIN, END and without it still have the same result.

Body:
I want to connect to Google Analytics Reporting API to fetch data, For which I have been provided with details of the service account in JSON format which contains details like (type, project_id, client_email, client_id, private_key,client_x509_cert_url, auth_provider_x509_cert_url)

Using this JSON file I am able to connect and fetch required report data via Python code Reporting API quickstart. However, due to business requirements, I have to establish the connection using HTTP Rest API.

So based on the details of the same service account I am trying to authenticate using JWT by referring to Google Docs Addendum: Service account authorization without OAuth so that once I get the signature I can use that as a static token and make next API call to get report data https://analyticsreporting.googleapis.com/v4/reports:batchGet and passing Request Body

But while testing in https://jwt.io/ & also in https://irrte.ch/jwt-js-decode/index.html signature creation is failing with an Invalid Signature error.

Can someone please help to understand what am I missing here?

Header

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "<service account's private key ID>"
}

Payload

{

  "iss": "<service account's email address i.e. client_email>",
  "sub": "<service account's email address i.e. client_email>",
  "aud": "https://oauth2.googleapis.com/token",
  "iat": <UTC Unix Epoch Start Time>,
  "exp": <UTC Unix Epoch End Time>

}

And then pasted X.509 PUBLIC CERTIFICATE generated for the service account and in Private key pasted Private key again which is from JSON file of service account

-----BEGIN CERTIFICATE-----\nMIrrhherhehrgssreheheherhehehehrhrdsfsfzcsvsvsvscssvsrjnfvdsfsscscscshgeferttyyuuuuuuuuuuudDxE/Q\n-----END CERTIFICATE-----\n

-----BEGIN PRIVATE KEY-----\nLDSVSVSCSYUNJKOLPDFSSSFSFSFSSFSFSFSFSFSFSSFSFSFSFSFSFSFSSSSSSSSSGGGGGGGGGGGGGGGGGGGGGGUUUUUUUUUUUUUUUUUM=\n-----END PRIVATE KEY-----\n

PS: I have tried to test with \n without \n as well as with prefixes BEGIN, END and without it still have the same result.


问:
Clean type output from complex generic types
Zod is amazing at performing crazy type transformations and provide an inferred result that is completely devoid of generic types when previewed in your IDE.

```<code>const ObjSchema = z.object({
    t: z.enum(['A', 'B'])
}).transform(obj => {
    return obj.t === 'A' ? { bar: true } : { baz: 'bar' }
})

type ObjSchemaInput = z.input<typeof ObjSchema>
// { t: 'A' | 'B' }

type ObjSchemaOutput = z.infer<typeof ObjSchema>
/* {
    bar: boolean;
    baz?: undefined;
} | {
    baz: string;
    bar?: undefined;
} */
</code>```

When trying to do my own complex type logic, I get much less useful previews.

Take this stupid example:

```<code>type Bar = { bar: true }
type Baz<T> = { baz: T extends 'A' ? 'foo' : 'bar' }

type Foo<T extends 'A' | 'B'> = {
    [K in 'A' | 'B']: T extends 'A' ? Bar : Baz<T>
}

type T1 = Foo<'B'> // { A: Baz<'B'>, B: Baz<'B'> }
</code>```

There I expect T1 to be reported as { A: { baz: 'foo' }, B: { baz: 'foo' } }

While looking complex, these types are shallow and finite, and should be easily resolvable.

See Playground

But this nonsense works great:

```<code>type Obj<U extends string, V extends string> = {
  uv: U extends 'a' ? `${U}-${V}` : never
}

type Foo<T extends string> =
  T extends `${infer U}:${infer V}` ? Obj<U, V> : never

type A = Foo<'a:b'> // { uv: 'a-b' }
</code>```

Based on the first example, I'd expect that to say like Obj<'a', 'b'>, but here it does the right thing and I'm not entirely sure why.

So how do I get type reporting more like Zod?

Motivating Example

I don't expect anyone to debug this, but it illustrates the problem better.

I'm trying to provide types for setter functions of GLSL shaders derived from only the source code.

For example:

```<code>const vertex = /* glsl */ `
  attribute vec3 position;
  attribute vec2 normal;

  uniform float value;
  uniform vec2 vec2Value;

  varying vec2 uv;

  void main() {
      gl_Position = vec4(position, 1.0);
      uv = position.xy;
  }
`

declare const shaderObject: ShaderObject<typeof vertex>
shaderObject.uniforms.vec2Value.set(1, 2)
//           ^?
</code>```

My types so far return a type hint at that location that looks like this:

```<code>(property) uniforms: Settables<"uniform", SettableVariableDeclarations<[SingleDeclaration<"vec3", "attribute", "position">, SingleDeclaration<"vec2", "attribute", "normal">, SingleDeclaration<"float", "uniform", "value">, SingleDeclaration<...>, SingleDeclaration<...>, SingleDeclaration<...>, FunctionDefinition<...>], "uniform">>
</code>```

Which is nearly useless.

I was hoping for something like:

```<code>{
  value: { set(n: number): void }
  vec2Value: { set(x: number, y: number): void }
}

</code>```

Which does get more clear as you drill in, and at this location:

```<code>shaderObject.uniforms.vec2Value.set(1, 2)
//                              ^?
</code>```

The reported type is:

```<code>(property) set: (x: number, y: number) => void
</code>```

Which is great, but you have to discover the properties through autocomplete first, and can't easily see a list of the available props.

See Playground

So is there some sort of trick to writing your types in such a way that resolves them fully when reported back to you?

Body:
Zod is amazing at performing crazy type transformations and provide an inferred result that is completely devoid of generic types when previewed in your IDE.

const ObjSchema = z.object({
    t: z.enum(['A', 'B'])
}).transform(obj => {
    return obj.t === 'A' ? { bar: true } : { baz: 'bar' }
})

type ObjSchemaInput = z.input<typeof ObjSchema>
// { t: 'A' | 'B' }

type ObjSchemaOutput = z.infer<typeof ObjSchema>
/* {
    bar: boolean;
    baz?: undefined;
} | {
    baz: string;
    bar?: undefined;
} */

When trying to do my own complex type logic, I get much less useful previews.

Take this stupid example:

type Bar = { bar: true }
type Baz<T> = { baz: T extends 'A' ? 'foo' : 'bar' }

type Foo<T extends 'A' | 'B'> = {
    [K in 'A' | 'B']: T extends 'A' ? Bar : Baz<T>
}

type T1 = Foo<'B'> // { A: Baz<'B'>, B: Baz<'B'> }

There I expect T1 to be reported as { A: { baz: 'foo' }, B: { baz: 'foo' } }

While looking complex, these types are shallow and finite, and should be easily resolvable.

<a href="https://www.typescriptlang.org/play?ts=5.0.0-dev.20221228#code/JYWwDg9gTgLgBALzgMyhEcDkCIBNMBQBAxhAHYDO8A8gEYBWAysQBYCmIAhnALyIB0EBm2IwAFAG8CcGXBgAuAWzIBXEGIDamAIKYANFgBCmALoBKAgF8z-GFE6Vk0dUPq8AfHCmy4UNjBUoMjhXW14ePh1MOAB+LzhaTihFOxU2OEs4RQkEzgRFTESoaMsrCwIYAE8wdLomVg5OAEkyMBV4PgR+YFb2gB4qmohkODrmdi53AgB6adkAPRiiQdqGccbqdraOgR7kNigB6rZh0bWGyZm5mUWiO7vZuAA5ckQ8eQrjuEMk3niilJQNIZT41b55PoAFU8fByiXycEhcDYAA8YMpcBQsLpYlgnBBogUiiVll8AGIQCBQ5FojFYqJwAA+RkwMK80lkGgA0nAetjoszMMYTIokaj0WRMfzcT8oFlwQgoVNSqD0pCAIx-ClUoWsuCPAASEAA7nBiA45CxgFjaOlbTB0VAlo8bkt7gQgA" rel="nofollow noreferrer">See Playground

But this nonsense works great:

type Obj = {
  uv: U extends 'a' ? `${U}-${V}` : never
}

type Foo<T extends string> =
  T extends `${infer U}:${infer V}` ? Obj : never

type A = Foo<'a:b'> // { uv: 'a-b' }

Based on the first example, I'd expect that to say like Obj<'a', 'b'>, but here it does the right thing and I'm not entirely sure why.

So how do I get type reporting more like Zod?

Motivating Example

I don't expect anyone to debug this, but it illustrates the problem better.

I'm trying to provide types for setter functions of GLSL shaders derived from only the source code.

For example:

const vertex = /* glsl */ `
  attribute vec3 position;
  attribute vec2 normal;

  uniform float value;
  uniform vec2 vec2Value;

  varying vec2 uv;

  void main() {
      gl_Position = vec4(position, 1.0);
      uv = position.xy;
  }
`

declare const shaderObject: ShaderObject<typeof vertex>
shaderObject.uniforms.vec2Value.set(1, 2)
//           ^?

My types so far return a type hint at that location that looks like this:

(property) uniforms: Settables<"uniform", SettableVariableDeclarations<[SingleDeclaration<"vec3", "attribute", "position">, SingleDeclaration<"vec2", "attribute", "normal">, SingleDeclaration<"float", "uniform", "value">, SingleDeclaration<...>, SingleDeclaration<...>, SingleDeclaration<...>, FunctionDefinition<...>], "uniform">>

Which is nearly useless.

I was hoping for something like:

{
  value: { set(n: number): void }
  vec2Value: { set(x: number, y: number): void }
}

Which does get more clear as you drill in, and at this location:

shaderObject.uniforms.vec2Value.set(1, 2)
//                              ^?

The reported type is:

(property) set: (x: number, y: number) => void

Which is great, but you have to discover the properties through autocomplete first, and can't easily see a list of the available props.

<a href="https://www.typescriptlang.org/play?ts=5.0.0-dev.20221228#code/JYWwDg9gTgLgBAbzgBQIZQM4FM4F84BmUEIcA5DBgLQDmANhnWQNwBQrAxhAHYbwBuWWFgAecALxwA9ACo49RnBlS4AA1Zw4qGDCjAARgFcYOQRwDMcSBmAxgPNpu26Dx01g4AmON2ghUdI5wGnCG3MAEfoR0ENpw-AGGWEFhEVFm3hkAaonJIamRUKT+MAAscCWlOXRJbCEJUACewNw08R7ehvx1mvwQwAAmFagtABQAlIghmvQA+sgQNnY8Eu0cpaPWtvbcADRwAIwAdAAM40GaXatby9xHIo1BuKzqrDCNYDgAglA0GABi0AAKh8cJIECECDFtAAuOAAbW4cO4hhA+iEAF16h04fCRMjUeioPtGgS0ZjsRZcfifIShCSyUT9gAvRkU3oeUrUtnEuCk2nk3msgVMuAAdx5WOeb1BcAAioYAhFgEJVgAiZx6IwmNVwAA+cDVBT8avY70+cAAylgdKh9HQsDk9HaHQARDx0dDaHYYAA8ISBlqgHDgohM3AGGFC3AA1r4xdx4RjdgGFUqCCqoKGROHI-LFXRlarJGnCxn6awAHyrCGaeEAaTgLTgMawjQgBDggeDWij3Y4DYx2dzUdrmjg5qwpaLUDhQOn5ag0ybAyw3Dsi7hLQIqqBAElV+uZ8O13m+HpWiFnuO4AB+LsHtcbzPL5FYQRQDFzoMD+tDsOnqOy6TpanwcDOW7cDuWZAiCFoARGUatu2nY-H8gJQHBWBXsu96waCr4+O+QisNKUgqECWB8FaNowC6jroMA9HuhwnpQN6PAYDKFpfJaQKrGgmBYL6k4du0wgiJW8JqvoEADI0apYpOXYHKs1q2vaDHOppLFsRxvC+rxQL7BqOham4aqVmasoAKrhIUIDqSYUC+vh8E5oBcDni0NDVpIowhEcQUJDUVFzlhJ6IS2bZiWhALAgRN73nFGFYfCblYFiN64twxGfqwkziNWfSDNZPFma4JhOcWcCjEYBDQXCADqWD6AA4gAMgAQoYDVCIVxX9AMZU4E59F+qmBbHgheYLpmKaaECulercUYzVGY2aU6TE6R6K0+r6YRxhACZJvs85TYulYpn5Ux1o2zbIWJS17exq1fnd47YDAc5zaq62GsaRSmjemj3nZaRFNVLkvax+2cYOcAAGReS4rRWaDcBwl8FXalg0M4WRFFUfAm0OlxylAt4khk1RvpGvZJr7LT23Ma9+l+kZJlAyAllWdxo0ABaoKuUAAPL6AAVh4MD+otP6RWeaM0AtcBGYrUZHfGiZDpIgnYK5P5STJckKVit1jjzGBwrTE03gzkO86rmgs4xbNw29B1c4DjPAxjcD+5qlVhTRGnk3L46mS4eNqs7od0Vtbu7R7HOGXxJlBzH-tWUTXYk1awuixL0scDArCrh7OBcLw8AYIXQjFzLNv1+LUsyyJoJiR+JiSawdciw3bel0cVtHNkuRHN9owHPsnjjKw5GY6DAB6t59y3jfD5nbgYEcNw7JPNqjLlYpwC17Xdb10ETPPQA" rel="nofollow noreferrer">See Playground

So is there some sort of trick to writing your types in such a way that resolves them fully when reported back to you?


问:
Common Language Runtime (CLR) on Mac M1
I'm Data Analyst student and using Macbook Pro M1.

At this time of my study we are using AdventureWorks2019 database.

Part of the exercise we have are not available for me because as far as I understand CLR isn't support on Azure-SQL-EDGE.

Solving this is really necessary for continue.

Any solutions?

Searched all over the net.

Title: Common Language Runtime (CLR) on Mac M1


问:
Need for a fast writing of binary data to a file
I receive a fair amount of binary data from an external device, about 30-40 MB/s. I need to save it to a file. On the external source device side, I have a very small buffer that I can't enlarge and as soon as the transmission stutters on the C# application side, it quickly gets clogged and I lose data.

In the application, I tried writing using FileStream, but unfortunately it is not fast enough.

```<code>_FileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);

...

void Handler_OnFtdiBytesReceived(object sender, FtdiBytesReceivedEventArgs e)
{

    ...

    Array.Copy(e.Bytes, 0, _ReceivedDataBuffer, _ReceivedDataBufferPosition, e.NumBytesAvailable);

    _ReceivedDataBufferPosition += (int)e.NumBytesAvailable;

    if (_ReceivedDataBufferPosition > 0)
    {
        _FileStream.Write(_ReceivedDataBuffer, 0, (int)e.NumBytesAvailable);
        _ReceivedDataBufferPosition = 0;
    }

    if (_IsOperationFinished == true)
    {
        _FileStream.Flush();
        _FileStream.Close();
    }

    ...
}
</code>```

I also tried adding a BinaryWriter:

```<code>_FileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);
_BinaryWriter = new BinaryWriter(_FileStream);
</code>```

and then:

```<code>_BinaryWriter.Write(_ReceivedDataBuffer, 0, (int)e.NumBytesAvailable);
</code>```

instead of previous _FileStream.Write(...), but also the buffer on the transmit side gets clogged.

Is there any way to deal with this?
I wonder if it might help to somehow buffer the data in the computer's RAM when receiving it and, for example, when it reaches some sizable amount (say, 512 MB), start writing to the file in a separate Task, so that in the meantime, new data can be collected into the buffer continuously. Perhaps I would need to use two buffers and use them alternately, one to receive data continuously and the other from which to write to the file, and swap??
This seems quite complex code for someone with little experience, which I don't know if it will help, so I'd like to ask you for a hint first.

I'll just add at the end that I have the ability to watch the buffer fill up in this external device and by commenting out this one line regarding writing:
_FileStream.Write(_ReceivedDataBuffer, 0, (int)e.NumBytesAvailable);
I see that the problem with its clogging disappears. Earlier I also analyzed whether other code fragments might be inefficient, such as Array.Copy(...) or passing parameters via Event, but it had no effect.

Body:
I receive a fair amount of binary data from an external device, about 30-40 MB/s. I need to save it to a file. On the external source device side, I have a very small buffer that I can't enlarge and as soon as the transmission stutters on the C# application side, it quickly gets clogged and I lose data.

In the application, I tried writing using FileStream, but unfortunately it is not fast enough.

_FileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);

...

void Handler_OnFtdiBytesReceived(object sender, FtdiBytesReceivedEventArgs e)
{

    ...

    Array.Copy(e.Bytes, 0, _ReceivedDataBuffer, _ReceivedDataBufferPosition, e.NumBytesAvailable);

    _ReceivedDataBufferPosition += (int)e.NumBytesAvailable;

    if (_ReceivedDataBufferPosition > 0)
    {
        _FileStream.Write(_ReceivedDataBuffer, 0, (int)e.NumBytesAvailable);
        _ReceivedDataBufferPosition = 0;
    }

    if (_IsOperationFinished == true)
    {
        _FileStream.Flush();
        _FileStream.Close();
    }

    ...
}

I also tried adding a BinaryWriter:

_FileStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);
_BinaryWriter = new BinaryWriter(_FileStream);

and then:

_BinaryWriter.Write(_ReceivedDataBuffer, 0, (int)e.NumBytesAvailable);

instead of previous _FileStream.Write(...), but also the buffer on the transmit side gets clogged.

Is there any way to deal with this?
I wonder if it might help to somehow buffer the data in the computer's RAM when receiving it and, for example, when it reaches some sizable amount (say, 512 MB), start writing to the file in a separate Task, so that in the meantime, new data can be collected into the buffer continuously. Perhaps I would need to use two buffers and use them alternately, one to receive data continuously and the other from which to write to the file, and swap??
This seems quite complex code for someone with little experience, which I don't know if it will help, so I'd like to ask you for a hint first.

I'll just add at the end that I have the ability to watch the buffer fill up in this external device and by commenting out this one line regarding writing:
_FileStream.Write(_ReceivedDataBuffer, 0, (int)e.NumBytesAvailable);
I see that the problem with its clogging disappears. Earlier I also analyzed whether other code fragments might be inefficient, such as Array.Copy(...) or passing parameters via Event, but it had no effect.


问:
How to display select options in mobile as same as desktop view?
I've been trying to figure out how to display select options like the desktop browser. This is how I want to display in all devices:

I tried to check if it was displayed as the same on the mobile, so I chose iPhone as a device and tried inspection. It was displayed correctly:

However, I tried to open it in a simulator and this was the result:

I have tried appearance: "none", but it didn't prevent the mobile version of the dropdown. It wasn't specific to the iPhone or the browser. The result was the same for the Android simulator and the chrome browser in it. My code was similar to the below one.

```<code>return (
<div>
  <select multiple style={{ width: 100, appearance: "none", "-moz-appearance": "none", "-webkit-appearance": "none" }}>
    {[1,2,3,4,5].map(number => <option>{number}</option>)}
  </select>
</div>
);
</code>```

My question is how can I prevent this from happening on mobile devices without a workaround like a dropdown that consists of semantic elements?

Body:
I've been trying to figure out how to display select options like the desktop browser. This is how I want to display in all devices:

I tried to check if it was displayed as the same on the mobile, so I chose iPhone as a device and tried inspection. It was displayed correctly:

However, I tried to open it in a simulator and this was the result:

I have tried appearance: "none", but it didn't prevent the mobile version of the dropdown. It wasn't specific to the iPhone or the browser. The result was the same for the Android simulator and the chrome browser in it. My code was similar to the below one.

return (

  <select multiple style={{ width: 100, appearance: "none", "-moz-appearance": "none", "-webkit-appearance": "none" }}>
    {[1,2,3,4,5].map(number => <option>{number}</option>)}
  </select>

);

My question is how can I prevent this from happening on mobile devices without a workaround like a dropdown that consists of semantic elements?


问:
Android Studio - Firebase storage not updating correctly
I'm trying to make a database of users with profile pictures(stored in storage) related to their IDs.

I'm using Firebase auth,Realtime database and Realime storage.

The code work like this : In user registration process, they choose username and picture. The database is filled with Users -> userUUid -> username and URL of picture stored.

The storage stores the picture.

If I keep such name of the table (Users) code works fine, however if I try to manipulate the tables, for example if I want to make more categories like Users -> SpecialUsers / NormalUsers -> userUUid -> ... the app just crashes.. I tried debugging but saw no errors.

Is there any way how to catch these Firebase exceptions (if there is any) or any explanation why if I change the structure of the tables, the code doesn't work ?

These is the method responsible for the registration :
(this one works)

```<code>public void signUp(String email,String password,String userName)
{
    auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

        if (task.isSuccessful())
        {
            dbReference.child("Users").child(auth.getUid()).child("userName").setValue(userName);

            //if user choose some picture
            if(imageControl)
            {
                UUID randomID = UUID.randomUUID(); //create random UUID for the picture
                final String imageName = "images/"+randomID+".jpg";
                storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        StorageReference myStorageRef = firebaseStorage.getReference(imageName);
                        myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String filePath = uri.toString();
                                dbReference.child("Users").child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
            }
            else
            {
                dbReference.child("Users").child(auth.getUid()).child("image").setValue("null");
            }

            Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        else
        {
            Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
        }
    });
}

</code>```

This doesn't work :

(As you can see the only thing changed is the structure of the tables from only 'Users' to 'superUsers' -> 'anotherCategory')

```<code>public void signUp(String email,String password,String userName)
{
    auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

        if (task.isSuccessful())
        {
            dbReference.child("superUsers").child('anotherCategory').child(auth.getUid()).child("userName").setValue(userName);

            //if user choose some picture
            if(imageControl)
            {
                UUID randomID = UUID.randomUUID(); //create random UUID for the picture
                final String imageName = "images/"+randomID+".jpg";
                storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        StorageReference myStorageRef = firebaseStorage.getReference(imageName);
                        myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String filePath = uri.toString();
                                dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
            }
            else
            {
                dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue("null");
            }

            Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        else
        {
            Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
        }
    });
}
</code>```

I suspect that the errors occurs somewhere after imageControl check.

In the second example of the code, the tables superUsers -> anotherCategory tables are created in the database, however the reference to the picture UUids is empty (not even null is placed)

What could be the error if nothing relevant to the process of storing pictures is changed ?

Body:
I'm trying to make a database of users with profile pictures(stored in storage) related to their IDs.

I'm using Firebase auth,Realtime database and Realime storage.

The code work like this : In user registration process, they choose username and picture. The database is filled with Users -> userUUid -> username and URL of picture stored.

The storage stores the picture.

If I keep such name of the table (Users) code works fine, however if I try to manipulate the tables, for example if I want to make more categories like Users -> SpecialUsers / NormalUsers -> userUUid -> ... the app just crashes.. I tried debugging but saw no errors.

Is there any way how to catch these Firebase exceptions (if there is any) or any explanation why if I change the structure of the tables, the code doesn't work ?

These is the method responsible for the registration :
(this one works)

public void signUp(String email,String password,String userName)
{
    auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

        if (task.isSuccessful())
        {
            dbReference.child("Users").child(auth.getUid()).child("userName").setValue(userName);

            //if user choose some picture
            if(imageControl)
            {
                UUID randomID = UUID.randomUUID(); //create random UUID for the picture
                final String imageName = "images/"+randomID+".jpg";
                storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        StorageReference myStorageRef = firebaseStorage.getReference(imageName);
                        myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String filePath = uri.toString();
                                dbReference.child("Users").child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
            }
            else
            {
                dbReference.child("Users").child(auth.getUid()).child("image").setValue("null");
            }

            Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        else
        {
            Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
        }
    });
}

This doesn't work :

(As you can see the only thing changed is the structure of the tables from only 'Users' to 'superUsers' -> 'anotherCategory')

public void signUp(String email,String password,String userName)
{
    auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {

        if (task.isSuccessful())
        {
            dbReference.child("superUsers").child('anotherCategory').child(auth.getUid()).child("userName").setValue(userName);

            //if user choose some picture
            if(imageControl)
            {
                UUID randomID = UUID.randomUUID(); //create random UUID for the picture
                final String imageName = "images/"+randomID+".jpg";
                storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        StorageReference myStorageRef = firebaseStorage.getReference(imageName);
                        myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String filePath = uri.toString();
                                dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
                                    }
                                }).addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
            }
            else
            {
                dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue("null");
            }

            Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        else
        {
            Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
        }
    });
}

I suspect that the errors occurs somewhere after imageControl check.

In the second example of the code, the tables superUsers -> anotherCategory tables are created in the database, however the reference to the picture UUids is empty (not even null is placed)

What could be the error if nothing relevant to the process of storing pictures is changed ?


问:
How to deploy a mkdocs website inside another github website?
I have a website created in my github account using this template:
https://github.com/greenelab/lab-website-template

As one of the links in this website, I want to create some documentation using mkdocs but I am not sure how can I configure it in order not to replace the existing website and just add it as another document inside the old website.

Any idea how (or if) I can do this?

thanks


问:
A custom command for printing generated pdf
I want to get data from database and render it in a printable form.

models.py:

```<code>class PurchaseItem(models.Model):

product = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item")
quantity = models.PositiveSmallIntegerField()
purchase_price = models.DecimalField(max_digits=6, decimal_places=2)
paid_amount = models.DecimalField(max_digits=6, decimal_places=2)
date_created = models.DateTimeField(auto_now_add=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
</code>```

I want all this data to be represented in an invoice and be printable.I know many ways to do this but I think I need help from start. VIEWS section in particular is giving me headaches.

Body:
I want to get data from database and render it in a printable form.

models.py:

class PurchaseItem(models.Model):

product = models.ForeignKey(Item, on_delete=models.CASCADE, related_name="item")
quantity = models.PositiveSmallIntegerField()
purchase_price = models.DecimalField(max_digits=6, decimal_places=2)
paid_amount = models.DecimalField(max_digits=6, decimal_places=2)
date_created = models.DateTimeField(auto_now_add=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)

I want all this data to be represented in an invoice and be printable.I know many ways to do this but I think I need help from start. VIEWS section in particular is giving me headaches.


问:
Robocopy - Copy Files By Date Instead Of By Filename
By default Robocopy copies files in order by their filenames. I want to copy the files by date (or date modified) because they appear by date to the end user. (They have no sort, date is the default and only option.)

I have this:

robocopy "C:\directory" "D:\directory" /MIR /R:5 /W:20 /TEE /NP /LOG:"C:\Log.txt"

It is a simple directory copy. Is there a way within Robocopy to copy files by date (or date modified) instead of by filename?

Thank you.


问:
Php query to GraphQl, using Guzzle, with array as param
How to create parameterized query in PHP using guzzle for schema query like this:

```<code>getObject(number: [Int]): [ObjectDTO]

</code>```

Direct query to graphQl work well as below:

```<code>query{
  getObject(
    number: [1, 2, 3]
  ){ someData }
}
</code>```

Wanna make this query by quzzle actually just set Body for:

```<code>$body = [
 'query' => "query ($number: Int) { getObject( number: [$number],) { someData }}",
 'variables' => [
   'number' => [1, 2],
 ]
]
</code>```

But it's not working and informed me about the wrong type of "number" variable.

When I use it the same way but instead of an array of numbers, I will put one int like 'number' => 1 query works.

Any advice on how to operate with this query?

Body:
How to create parameterized query in PHP using guzzle for schema query like this:

getObject(number: [Int]): [ObjectDTO]

Direct query to graphQl work well as below:

query{
  getObject(
    number: [1, 2, 3]
  ){ someData }
}

Wanna make this query by quzzle actually just set Body for:

$body = [
 'query' => "query ($number: Int) { getObject( number: [$number],) { someData }}",
 'variables' => [
   'number' => [1, 2],
 ]
]

But it's not working and informed me about the wrong type of "number" variable.

When I use it the same way but instead of an array of numbers, I will put one int like 'number' => 1 query works.

Any advice on how to operate with this query?


问:
Problem copying contents of virtual machine with DiscUtils
I'm able to view a virtual machine image (vhdx) using the Discutils library (https://github.com/DiscUtils/DiscUtils)
There are files belonging to the Linux operating system in these Vhdx

How can I transfer these files to the windows environment because of the special characters in their names?

What came to my mind was to remove the special characters in the filenames. However, since the method I use wants to open the file first, windows does not allow it.

```<code>var sourceStream = fs.OpenFile(name, FileMode.Open, FileAccess.Read);
var targetStream = System.IO.File.OpenWrite(@"D:\" + name);
sourceStream.CopyTo(targetStream);
</code>```

Body:
I'm able to view a virtual machine image (vhdx) using the Discutils library (https://github.com/DiscUtils/DiscUtils)
There are files belonging to the Linux operating system in these Vhdx

How can I transfer these files to the windows environment because of the special characters in their names?

What came to my mind was to remove the special characters in the filenames. However, since the method I use wants to open the file first, windows does not allow it.

var sourceStream = fs.OpenFile(name, FileMode.Open, FileAccess.Read);
var targetStream = System.IO.File.OpenWrite(@"D:\" + name);
sourceStream.CopyTo(targetStream);