问:
Can't Transfer Amount to Connect Stripe Account
BackGround:

What i'm trying to do is set-up a marketplace where the customer can acquire services of a seller,The Project is a MERN Stack Travel Application to be exact. What i would like is for the customer to Pay the Platform(My Website connected with Stripe) when he wishes to acquire a service e.g a hotel Room. The Customer stays at the hotel for the allotted time and when he checksout the platform keeps some of the customers amount as application fee and transfers the rest to the service provider,in this case the hotel.

Current Effort:

I Used STRIPE CONNECT to acheive the required functionality.

(Note: you guys don't need to see all of the code below just the heading and description would give you an idea of what i have done and what i'm trying to ask,but please do read the issue section)

i create a Connect account for the seller when he signs up on my Website

Create Connect Account

```<code>const express = require("express");
const router = express.Router();
  router.post("/createAccount", async (req, res) => {
  const { name, email } = req.body; //Data Passed from the FrontEnd
  stripe.accounts.create(
    {
      type: "custom",
      country: "US",
      email: email,
      requested_capabilities: ["card_payments", "transfers"],
    },
    function (err, account) {
      res.json({ account: account });
    }
  );
});
</code>```

When the Seller Provides the rest of the required details(including bank Account) after logging-in to the Seller Portal i create a bank_account,update the already created Connect Account and link the bank_account with the Connect Account (Hopefully, that somehow makes sense)

Create Bank Account

```<code>  router.post("/createBankAccount", async (req, res) => {
  const { account_holder_name, routing_number, account_number } = req.body;
  stripe.tokens.create(
    {
      bank_account: {
        country: "US",
        currency: "USD",
        account_holder_name,
        account_holder_type: "individual",
        routing_number,
        account_number,
      },
    },
    function (err, token) {
      res.send(token);
    }
  );
});
</code>```

Update Account:

```<code>  router.post("/updateAccount", async (req, res) => {
      const {
        AccountID,
        Day,
        Month,
        Year,
        first_name,
        last_name,
        email,
        BankAccountID,
      } = req.body;

      const FrontFilePath = fs.readFileSync("PathToFileHere");
      const FrontPhotoIDUpload = await stripe.files.create({
        file: {
          data: FrontFilePath,
          name: "FrontPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      const BackFilePath = fs.readFileSync("PathToFileHere");
      const BackPhotoIDUpload = await stripe.files.create({
        file: {
          data: BackFilePath,
          name: "BackPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      stripe.accounts.update(
        AccountID,
        {
          business_type: "individual",
          individual: {
            dob: { day: Day, month: Month, year: Year },
            first_name: first_name,
            last_name: last_name,
            id_number: "006-20-8311",
            phone: "605-628-6049",
            address: {
              city: "Half Way",
              line1: "2467  Twin House Lane",
              postal_code: "65663",
              state: "MO",
            },
            email,
            ssn_last_4: "8311",
            verification: {
              document: {
                front: FrontPhotoIDUpload.id,
                back: BackPhotoIDUpload.id,
              },
            },
          },
          business_profile: {
            mcc: "4722",
            url: "http://www.baoisne.com",
          },
          tos_acceptance: {
            date: Math.floor(Date.now() / 1000),
            ip: req.connection.remoteAddress,
          },
        },
        function (err, account) {
          console.log(err);
          console.log(account);
        }
      );
     //Connect External Account
      stripe.accounts.createExternalAccount(
        AccountID,
        {
          external_account: BankAccountID,
        },
        function (err, bankAccount) {
          console.log(err);
          res.send(bankAccount);
        }
      );
    });
</code>```

Then when the customers provides his account details i charge the customer,keep some money as application fee and move the rest to the Service Providers Connect account.

Charge Customer

```<code>  router.post("/charge", async (req, res) => {
  const { TokenID, CustomerID, Amount, AccountID } = req.body;
  let PaymentAmount = Amount * 100;
  let application_fee_amount = 400;
  try {
    const payment = await stripe.paymentIntents.create({
      amount: PaymentAmount,
      currency: "USD",
      description: "We did it boss",
      payment_method_data: {
        type: "card",
        card: {
          token: TokenID,
        },
      },
      receipt_email: "abdullahabid427@gmail.com",
      customer: CustomerID,
      application_fee_amount,
      transfer_data: {
      destination: AccountID,
      },
      confirm: true,
    });
    return res.status(200).json({
      confirm: "Payment Succeeded",
    });
  } catch (error) {
    console.log(error);
    return res.status(400).json({
      message: error.message,
    });
  }
});
</code>```

By doing the above procedure a connect account is created and the amount is moved into the connected account.

Issue

The Above procedure although works correctly, it moves the amount into the Connected Service Provider Account directly after the customer is charged, what i would like is for the customer to pay the platform and after the Service Provider has provided his services , the Platform pays the Service Provider, i thought about removing

```<code>  application_fee_amount,
  transfer_data: {
  destination: AccountID,
  }
</code>```

the above parameters in the Charge or Stripe.paymentIntents.create endpoint, and after Service Provider has completed his services i transfer the amount using the Stripe Transfer API

```<code>router.post("/transfer", async (req, res) => {
  try {
    console.log("TRANSFER=");
    const { AccountID, amount } = req.body;
    const transfer = await stripe.transfers.create({
      amount,
      currency: "USD",
      destination: AccountID,
    });
    res.send(transfer);
  } catch (error) {
    res.send(error);
  }
});
</code>```

the issue here is that transfer endpoint returns "Your destination account needs to have at least one of the following capabilities enabled: transfers, legacy_payments" , i have checked the Connected Account in Stripe Dashboard and in the Capabilities section Card_Payment and Transfers are both set to Active, plus Payments and Payouts are both Enabled and the status of the connect account is "Complete"

So if anyone could point in the right direction i would really Appreciate it,Cheers :)

答:
Create a webhook (Stripe config) which includes:

Events sent to the webhook: in this case customer.created, customer.source.created, customer.source.updated

URL = the route that handles the events when they arrive

So you need to store the pending payment in your DB first. Then in the webhook, find it in the DB and complete the transfer.

Body:
BackGround:

What i'm trying to do is set-up a marketplace where the customer can acquire services of a seller,The Project is a MERN Stack Travel Application to be exact. What i would like is for the customer to Pay the Platform(My Website connected with Stripe) when he wishes to acquire a service e.g a hotel Room. The Customer stays at the hotel for the allotted time and when he checksout the platform keeps some of the customers amount as application fee and transfers the rest to the service provider,in this case the hotel.

Current Effort:

I Used STRIPE CONNECT to acheive the required functionality.

(Note: you guys don't need to see all of the code below just the heading and description would give you an idea of what i have done and what i'm trying to ask,but please do read the issue section)

i create a Connect account for the seller when he signs up on my Website

Create Connect Account

const express = require("express");
const router = express.Router();
  router.post("/createAccount", async (req, res) => {
  const { name, email } = req.body; //Data Passed from the FrontEnd
  stripe.accounts.create(
    {
      type: "custom",
      country: "US",
      email: email,
      requested_capabilities: ["card_payments", "transfers"],
    },
    function (err, account) {
      res.json({ account: account });
    }
  );
});

When the Seller Provides the rest of the required details(including bank Account) after logging-in to the Seller Portal i create a bank_account,update the already created Connect Account and link the bank_account with the Connect Account (Hopefully, that somehow makes sense)

Create Bank Account

  router.post("/createBankAccount", async (req, res) => {
  const { account_holder_name, routing_number, account_number } = req.body;
  stripe.tokens.create(
    {
      bank_account: {
        country: "US",
        currency: "USD",
        account_holder_name,
        account_holder_type: "individual",
        routing_number,
        account_number,
      },
    },
    function (err, token) {
      res.send(token);
    }
  );
});

Update Account:

  router.post("/updateAccount", async (req, res) => {
      const {
        AccountID,
        Day,
        Month,
        Year,
        first_name,
        last_name,
        email,
        BankAccountID,
      } = req.body;

      const FrontFilePath = fs.readFileSync("PathToFileHere");
      const FrontPhotoIDUpload = await stripe.files.create({
        file: {
          data: FrontFilePath,
          name: "FrontPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      const BackFilePath = fs.readFileSync("PathToFileHere");
      const BackPhotoIDUpload = await stripe.files.create({
        file: {
          data: BackFilePath,
          name: "BackPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      stripe.accounts.update(
        AccountID,
        {
          business_type: "individual",
          individual: {
            dob: { day: Day, month: Month, year: Year },
            first_name: first_name,
            last_name: last_name,
            id_number: "006-20-8311",
            phone: "605-628-6049",
            address: {
              city: "Half Way",
              line1: "2467  Twin House Lane",
              postal_code: "65663",
              state: "MO",
            },
            email,
            ssn_last_4: "8311",
            verification: {
              document: {
                front: FrontPhotoIDUpload.id,
                back: BackPhotoIDUpload.id,
              },
            },
          },
          business_profile: {
            mcc: "4722",
            url: "http://www.baoisne.com",
          },
          tos_acceptance: {
            date: Math.floor(Date.now() / 1000),
            ip: req.connection.remoteAddress,
          },
        },
        function (err, account) {
          console.log(err);
          console.log(account);
        }
      );
     //Connect External Account
      stripe.accounts.createExternalAccount(
        AccountID,
        {
          external_account: BankAccountID,
        },
        function (err, bankAccount) {
          console.log(err);
          res.send(bankAccount);
        }
      );
    });

Then when the customers provides his account details i charge the customer,keep some money as application fee and move the rest to the Service Providers Connect account.

Charge Customer

  router.post("/charge", async (req, res) => {
  const { TokenID, CustomerID, Amount, AccountID } = req.body;
  let PaymentAmount = Amount * 100;
  let application_fee_amount = 400;
  try {
    const payment = await stripe.paymentIntents.create({
      amount: PaymentAmount,
      currency: "USD",
      description: "We did it boss",
      payment_method_data: {
        type: "card",
        card: {
          token: TokenID,
        },
      },
      receipt_email: "abdullahabid427@gmail.com",
      customer: CustomerID,
      application_fee_amount,
      transfer_data: {
      destination: AccountID,
      },
      confirm: true,
    });
    return res.status(200).json({
      confirm: "Payment Succeeded",
    });
  } catch (error) {
    console.log(error);
    return res.status(400).json({
      message: error.message,
    });
  }
});

By doing the above procedure a connect account is created and the amount is moved into the connected account.

Issue

The Above procedure although works correctly, it moves the amount into the Connected Service Provider Account directly after the customer is charged, what i would like is for the customer to pay the platform and after the Service Provider has provided his services , the Platform pays the Service Provider, i thought about removing

  application_fee_amount,
  transfer_data: {
  destination: AccountID,
  }

the above parameters in the Charge or Stripe.paymentIntents.create endpoint, and after Service Provider has completed his services i transfer the amount using the Stripe Transfer API

router.post("/transfer", async (req, res) => {
  try {
    console.log("TRANSFER=");
    const { AccountID, amount } = req.body;
    const transfer = await stripe.transfers.create({
      amount,
      currency: "USD",
      destination: AccountID,
    });
    res.send(transfer);
  } catch (error) {
    res.send(error);
  }
});

the issue here is that transfer endpoint returns "Your destination account needs to have at least one of the following capabilities enabled: transfers, legacy_payments" , i have checked the Connected Account in Stripe Dashboard and in the Capabilities section Card_Payment and Transfers are both set to Active, plus Payments and Payouts are both Enabled and the status of the connect account is "Complete"

So if anyone could point in the right direction i would really Appreciate it,Cheers :)


来源: stackexchange

问:
I am updating Angular version from 7 to 8. But getting peer dependency error
I tried using --force , but of no use.

enter image description here

error code -

```<code>    Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to   "@angular/common" (requires "^7.0.0" (extended), would install "9.1.9").
 Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/animations" (requires "6.x" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser" (requires "6.x" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser-dynamic" (requires "^6.0.0" (extended), would install "9.1.9").
                  Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to "@angular/forms" (requires "^7.0.0" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "rxjs" (requires "^5.1.0", would install "6.5.5").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "zone.js" (requires "^0.8.4", would install "0.10.3").
</code>```

答:
try adding force flag

```<code>ng update @angular/core --force
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried using --force , but of no use.

enter image description here

error code -

    Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to   "@angular/common" (requires "^7.0.0" (extended), would install "9.1.9").
 Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/animations" (requires "6.x" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/compiler" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser" (requires "6.x" (extended), would install "9.1.9").
                  Package "@swimlane/ngx-charts" has an incompatible peer dependency to "@angular/platform-browser-dynamic" (requires "^6.0.0" (extended), would install "9.1.9").
                  Package "@ng-bootstrap/ng-bootstrap" has an incompatible peer dependency to "@angular/forms" (requires "^7.0.0" (extended), would install "9.1.9").
                  Package "codelyzer" has an incompatible peer dependency to "@angular/core" (requires ">=2.3.1 <8.0.0 || >7.0.0-beta <8.0.0" (extended), would install "9.1.9").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "rxjs" (requires "^5.1.0", would install "6.5.5").
                  Package "ngx-jsoneditor" has an incompatible peer dependency to "zone.js" (requires "^0.8.4", would install "0.10.3").

Body:
try adding force flag

ng update @angular/core --force


问:
socket send part down but receive part Up , possible?
I am wondering if it is possible to have a socket with send which doens't work (because buffer of peer is full maybe) while receive part still working ?

EDIT:

In case of a peer which doesn't perform a half close connection, and which it is too long to process its receive buffer (so its receive buffer is full), can I have an error only on my send part ?

答: Of course it is possible. For example, if you have unix domain socket and no one is reading from it.If you are asking about TCP or UDP sockets, the answer could be more complicated</p>

ContentLicense: CC BY-SA 3.0


问:
Unity 2018.3 android dex merging issue
Before you decide to dismiss this post as "duplicate" without even reading it, understand that I have looked at a TON of posts related to this topic and I can't find a solution for my instance, including all of the ones that StackOverflow suggested. Most of the posts are for Android Studio instead of unity.

My error is given in Unity when trying to build to android, it crashes here.

```<code>CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\OpenJDK\Windows\bin\java.exe -classpath "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-4.6.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleDebug"

stderr[
D8: Program type already present: com.unity3d.ads.BuildConfig

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

I've tried changing stuff with a build.gradle file like a lot of posts suggest, but I can't get anything to work.

The error didn't exist in Unity 2018.2. I checked right before I updated, but the update is now throwing this issue.

Does anyone have any UNITY specific ideas what to do here? I've tried so many things and nobody's post has been able to help me yet.

Thanks for any help

答:
Dex Errors generally occur when you have too many methods imported in a project, not because of a specific package. I assume upgrading to new version made you import new stuff to your project.

You need to enable ProGuard.

Cause: http://twinkfed.homedns.org/Android///tools/building/multidex.html

Fix: https://www.youtube.com/watch?v=va0FQNlBUX0

Title: Unity 2018.3 android dex merging issue

Body:
Before you decide to dismiss this post as "duplicate" without even reading it, understand that I have looked at a TON of posts related to this topic and I can't find a solution for my instance, including all of the ones that StackOverflow suggested. Most of the posts are for Android Studio instead of unity.

My error is given in Unity when trying to build to android, it crashes here.

CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\OpenJDK\Windows\bin\java.exe -classpath "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-4.6.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleDebug"

stderr[
D8: Program type already present: com.unity3d.ads.BuildConfig

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':transformDexArchiveWithExternalLibsDexMergerForDebug'.

I've tried changing stuff with a build.gradle file like a lot of posts suggest, but I can't get anything to work.

The error didn't exist in Unity 2018.2. I checked right before I updated, but the update is now throwing this issue.

Does anyone have any UNITY specific ideas what to do here? I've tried so many things and nobody's post has been able to help me yet.

Thanks for any help


问:
Creating an icon with Users Initials
I am trying to create logos for my system similar to the ones that are created on MS teams. Basically, each users Initials are made into a picture and is displayed throughout the system when referring to that user, instead of showing the users full name. it is also used as the users profile picture. Please note that my system is a K2 developed system

Microsoft teams example

答:
I found a post that explains how to do what i needed fairly well, if anybody was also trying to accomplish this

https://www.c-sharpcorner.com/article/create-default-profile-image-dynamically-from-first-and-last/

Title: Creating an icon with Users Initials


问:
Using GDB in linux if running application from a script
Normally we run gdb with gdb command and our application name. But if we want to run our application from a script eg my_script.sh as ./my_script.sh argument and this starts our application. Then how to use gdb without including any command in script.

I want something like this : gdb ./my_script.sh argument. So that whatever application will be started from script I can debug it.

答:
Normally we run gdb with gdb command and our application name.

This is wrong. You use gdb on some binary executable file (in ELF format) or (with -p) on a running process. For example, you cannot run gdb cd but cd is a shell builtin command (see also this). BTW an executable file can have several names (e.g. /bin/rbash is a symbolic link to /bin/bash on my Debian computer), and programs can be started without being "applications" on your desktop menu. For example, my g++ executable would run /usr/lib/gcc/x86_64-linux-gnu/9/cc1plus. Check with strace(1) or by diving into the source code of GCC, or simply adding -v inside your g++ command.

Read documentation of GDB

and the gdb(1) and gdbserver(1) man page.
Run also in a terminal gdb --help to understand how you could start it.

You might start (or improve your my_script.sh shell script to run) your ELF executable yourprog (obtained by compiling your C++ code) using

```<code> gdb --args yourprog arg1toit arg2toit
</code>```

and you could even use some pipeline (see pipe(7) or even unix(7) sockets) to pour commands into it. Of course yourprog should be compiled with g++ -Wall -g and perhaps also -O (assuming a recent enough GCC).

In addition, recent GDB can be scripted or extended in Python or in Guile. You might need to compile and configure GDB from its source code, which you are allowed to do since it is free software.

If you need to debug a bash shell script, consider using bashdb, a shell script debugger. Of course spend an hour in reading its documentation. But if you want to debug a script coded in bash, why is your question tagged C++ ?

Read also How to debug small programs

However, a process won't be able to debug directly itself without precautions. See ptrace(2) for details.

I want something like this : gdb ./my_script.sh argument.

This is not possible.

GDB can (on recent Linux distributions) only debug an ELF executable (but not a shell script), preferably with DWARF debug information. Design your my_script.sh  to sometimes run gdb. That debugged executable would be often compiled with GCC or Clang compilers (and -g options) from some C++ or C source code. You could find other compilers (Ocaml, Rust, Go, ...) capable (with care) to produce ELF executables with DWARF debug information.

If your my_script.sh  is written for GNU bash (so starts with #!/bin/bash, see execve(2) for details), read the documentation of GNU bash. You might consider rewriting your script in Python or in Guile or in Lua, since all these scripting languages are more expressive than POSIX shells. In all cases, read the documentation of the scripting language you have chosen to use. Most of them have debugging facilities. (you could replace #!/bin/bash with a line like #!/bin/bash -vx as the first line of your shell script).

NB. Notice that  /usr/bin/firefox is often a script starting some /usr/bin/firefox.real ELF executable. You could glance inside it for inspiration.

Body:
Normally we run gdb with gdb command and our application name.

This is wrong. You use gdb on some binary executable file (in ELF format) or (with -p) on a running process. For example, you cannot run gdb cd but cd is a shell builtin command (see also this). BTW an executable file can have several names (e.g. /bin/rbash is a symbolic link to /bin/bash on my Debian computer), and programs can be started without being "applications" on your desktop menu. For example, my g++ executable would run /usr/lib/gcc/x86_64-linux-gnu/9/cc1plus. Check with strace(1) or by diving into the source code of GCC, or simply adding -v inside your g++ command.

Read documentation of GDB

and the gdb(1) and gdbserver(1) man page.
Run also in a terminal gdb --help to understand how you could start it.

You might start (or improve your my_script.sh shell script to run) your ELF executable yourprog (obtained by compiling your C++ code) using

 gdb --args yourprog arg1toit arg2toit

and you could even use some pipeline (see pipe(7) or even unix(7) sockets) to pour commands into it. Of course yourprog should be compiled with g++ -Wall -g and perhaps also -O (assuming a recent enough GCC).

In addition, recent GDB can be scripted or extended in Python or in Guile. You might need to compile and configure GDB from its source code, which you are allowed to do since it is free software.

If you need to debug a bash shell script, consider using bashdb, a shell script debugger. Of course spend an hour in reading its documentation. But if you want to debug a script coded in bash, why is your question tagged C++ ?

Read also How to debug small programs

However, a process won't be able to debug directly itself without precautions. See ptrace(2) for details.

I want something like this : gdb ./my_script.sh argument.

This is not possible.

GDB can (on recent Linux distributions) only debug an ELF executable (but not a shell script), preferably with DWARF debug information. Design your my_script.sh  to sometimes run gdb. That debugged executable would be often compiled with GCC or Clang compilers (and -g options) from some C++ or C source code. You could find other compilers (Ocaml, Rust, Go, ...) capable (with care) to produce ELF executables with DWARF debug information.

If your my_script.sh  is written for GNU bash (so starts with #!/bin/bash, see execve(2) for details), read the documentation of GNU bash. You might consider rewriting your script in Python or in Guile or in Lua, since all these scripting languages are more expressive than POSIX shells. In all cases, read the documentation of the scripting language you have chosen to use. Most of them have debugging facilities. (you could replace #!/bin/bash with a line like #!/bin/bash -vx as the first line of your shell script).

NB. Notice that  /usr/bin/firefox is often a script starting some /usr/bin/firefox.real ELF executable. You could glance inside it for inspiration.


问:
How toIntent Array Object in Android Studio with Kotlin
How to intent data API like this in Android Studio with kotlin language

I Need help for it

答:
If you want to create data class in Kotlin from JSON and you don't know how to do it, there is nice plugin that can help you out.
Go to File -> Settings -> Plugins and search JSON To Kotlin Class

When you are adding new class select Kotlin data class File from JSON

Copy your JSON response in class, set class name and click finish.


问:
Check if module exists, if not install it
I want to check if a module exists, if it doesn't I want to install it.

How should I do this?

So far I have this code which correctly prints f if the module doesn't exist.

```<code>try:
    import keyring
except ImportError:
    print 'f'
</code>```

答:
NOTE: Ipython / Jupyter specific solution.

While using notebooks / online kernels, I usually do it using systems call.

```<code>try:
  import keyring
except:
  !pip install keyring
  import keyring
</code>```

P.S. One may wish to call conda install or mamba install instead.

Body:
I want to check if a module exists, if it doesn't I want to install it.

How should I do this?

So far I have this code which correctly prints f if the module doesn't exist.

try:
    import keyring
except ImportError:
    print 'f'

Body:
NOTE: Ipython / Jupyter specific solution.

While using notebooks / online kernels, I usually do it using systems call.

try:
  import keyring
except:
  !pip install keyring
  import keyring

P.S. One may wish to call conda install or mamba install instead.


问:
Record dynamic instruction trace or histogram in QEMU?

I've written and compiled a RISC-V Linux application.

I want to dump all the instructions that get executed at run-time (which cannot be achieved by static analysis).

Is it possible to get a dynamic assembly instruction execution historgram from QEMU (or other tools)?

答:
It seems you can do something similar with rv8 (https://github.com/rv8-io/rv8), using the command: </p>

```<code>rv-jit -l
</code>```

Body:
It seems you can do something similar with rv8 (https://github.com/rv8-io/rv8), using the command:

rv-jit -l


问:
Detect URL change with Xamarin.Forms Webview and Compare current URL to original URL
So I'm creating an app that uses Xamarin.Forms Webview. I'm trying to detect when the URL changes and if it does then compare the Original URL with the Current URL and then show or hide a button depending. The buttons purpose is to go back to the previous page and keep going until it reaches it's original destination. I only want this "go back" button to show when the user is not on the homescreen. Otherwise, always show.

I've tried everything with if(webview.cangoback...) but that doesn't detect the url change. I've tried setting a string that is equal to the original URL and using .Equals to compare the webview.source (which is where I'm currently at)

I just started looking into webviewNavigating but still nothing.

```<code>namespace Webview_Test
{
    public partial class MainPage : ContentPage
    {
        public static string CurrentUrl { get; set; }
        public MainPage()
        {

            InitializeComponent();

            string CurrentUrl = "https://www.google.com/";

            var _webView = new WebView()
            {
                Source = "https://www.google.com/",
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            Button BackButton = new Button
            {
                Text = "Go Back",
                BackgroundColor = Color.FromHex("990000"),
                TextColor = Color.White
            };
            BackButton.Clicked += OnBackButtonClicked;

            void OnBackButtonClicked(object sender, EventArgs e)
            {
                _webView.GoBack();
            }

            Grid grid = new Grid
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
                {
                    new RowDefinition { Height = GridLength.Auto },
                    new RowDefinition { Height = GridLength.Auto },
                    new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                    new RowDefinition { Height = new GridLength(50, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(15, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(15, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(36, GridUnitType.Absolute) }
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition { Width = GridLength.Auto },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                    new ColumnDefinition { Width = new GridLength(50, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(50, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                    new ColumnDefinition { Width = GridLength.Auto }
                }
            };

            grid.Children.Add(_webView, 0, 6, 0, 7);

            if (_webView.Source.Equals(CurrentUrl))
            {
                grid.Children.Remove(BackButton);
            }
            else
            {
                grid.Children.Add(BackButton, 2, 4, 4, 6);
            }

            Content = grid;
        }
    }
}
</code>```

My expected result is that on the homepage the button that says "go back" doesn't show. But on any page other than the homepage it should show the "go back" button. In logical terms it's if OriginalURL = CurrentURL don't show button. if OriginalURL != CurrentURL show button.

答:
It might be late, but this helps, easy, quick, without any problem.</p>

```<code>var url = await webView.EvaluateJavaScriptAsync("window.location.href");
</code>```

Body:
So I'm creating an app that uses Xamarin.Forms Webview. I'm trying to detect when the URL changes and if it does then compare the Original URL with the Current URL and then show or hide a button depending. The buttons purpose is to go back to the previous page and keep going until it reaches it's original destination. I only want this "go back" button to show when the user is not on the homescreen. Otherwise, always show.

I've tried everything with if(webview.cangoback...) but that doesn't detect the url change. I've tried setting a string that is equal to the original URL and using .Equals to compare the webview.source (which is where I'm currently at)

I just started looking into webviewNavigating but still nothing.

namespace Webview_Test
{
    public partial class MainPage : ContentPage
    {
        public static string CurrentUrl { get; set; }
        public MainPage()
        {

            InitializeComponent();

            string CurrentUrl = "https://www.google.com/";

            var _webView = new WebView()
            {
                Source = "https://www.google.com/",
                HorizontalOptions = LayoutOptions.FillAndExpand,
                VerticalOptions = LayoutOptions.FillAndExpand
            };

            Button BackButton = new Button
            {
                Text = "Go Back",
                BackgroundColor = Color.FromHex("990000"),
                TextColor = Color.White
            };
            BackButton.Clicked += OnBackButtonClicked;

            void OnBackButtonClicked(object sender, EventArgs e)
            {
                _webView.GoBack();
            }

            Grid grid = new Grid
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions =
                {
                    new RowDefinition { Height = GridLength.Auto },
                    new RowDefinition { Height = GridLength.Auto },
                    new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                    new RowDefinition { Height = new GridLength(50, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(15, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(15, GridUnitType.Absolute) },
                    new RowDefinition { Height = new GridLength(36, GridUnitType.Absolute) }
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition { Width = GridLength.Auto },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                    new ColumnDefinition { Width = new GridLength(50, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(50, GridUnitType.Absolute) },
                    new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                    new ColumnDefinition { Width = GridLength.Auto }
                }
            };

            grid.Children.Add(_webView, 0, 6, 0, 7);

            if (_webView.Source.Equals(CurrentUrl))
            {
                grid.Children.Remove(BackButton);
            }
            else
            {
                grid.Children.Add(BackButton, 2, 4, 4, 6);
            }

            Content = grid;
        }
    }
}

My expected result is that on the homepage the button that says "go back" doesn't show. But on any page other than the homepage it should show the "go back" button. In logical terms it's if OriginalURL = CurrentURL don't show button. if OriginalURL != CurrentURL show button.

Body:
It might be late, but this helps, easy, quick, without any problem.

var url = await webView.EvaluateJavaScriptAsync("window.location.href");


问:
in Qt setFocus() for QGraphicsItemGroup
How to be given setFocus() properties into  QGraphicsItemGroup item?
I have 3 GraphicsRectItem in QGraphicsItemGroup with bondingrect()
and I want to give setfocus() preporty this QGraphicsItemGroup to can be controled with keyPressEvent </p>

答:
Although your question does not provide enough details, but it seems that you have some graphics items inside a group, and you want to control the items through the keyboard, right?
If so, let's assume that you have some QGraphicsItem items in a QGraphicItemGroup and you want to change the active item by using the Tab key and then do some actions on the active item by using other keys (e.g., rotate it or so on).
My solution is as follows:

define a QGraphicsItem *activeItem pointer which will point to the active item in the group.

overriding the group's keyPressedEvent function as follows:

```<code>void MainWindow::keyPressEvent(QKeyEvent *event)
{
    //Which key is pressed? ---> <QKeyEvent> must be included
    if (event->key() == Qt::Key_Tab) {

        /* set activeItem as you desire.
         * For example, find the index of the
         * item that currently activeItem is pointing
         * to and then go to the next item.
        */

        //then return
    }

    if (event->key() == Qt::Key::YourDesiredKey) {

        //do your actions and then return
    }

}
</code>```

Title: in Qt setFocus() for QGraphicsItemGroup

Body:
Although your question does not provide enough details, but it seems that you have some graphics items inside a group, and you want to control the items through the keyboard, right?
If so, let's assume that you have some QGraphicsItem items in a QGraphicItemGroup and you want to change the active item by using the Tab key and then do some actions on the active item by using other keys (e.g., rotate it or so on).
My solution is as follows:

define a QGraphicsItem *activeItem pointer which will point to the active item in the group.

overriding the group's keyPressedEvent function as follows:

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    //Which key is pressed? ---> <QKeyEvent> must be included
    if (event->key() == Qt::Key_Tab) {

        /* set activeItem as you desire.
         * For example, find the index of the
         * item that currently activeItem is pointing
         * to and then go to the next item.
        */

        //then return
    }

    if (event->key() == Qt::Key::YourDesiredKey) {

        //do your actions and then return
    }

}


问:
Retry logic with CompletableFuture
I need to submit a task in an async framework I'm working on, but I need to catch for exceptions, and retry the same task multiple times before "aborting".

The code I'm working with is:

```<code>int retries = 0;
public CompletableFuture<Result> executeActionAsync() {

    // Execute the action async and get the future
    CompletableFuture<Result> f = executeMycustomActionHere();

    // If the future completes with exception:
    f.exceptionally(ex -> {
        retries++; // Increment the retry count
        if (retries < MAX_RETRIES)
            return executeActionAsync();  // <--- Submit one more time

        // Abort with a null value
        return null;
    });

    // Return the future
    return f;
}
</code>```

This currently doesn't compile because the return type of the lambda is wrong: it expects a Result, but the executeActionAsync returns a CompletableFuture<Result>.

How can I implement this fully async retry logic?

答:
maybe it's late but hopes someone might find this useful, I recently solved this problem for retrying rest API call on failure. In my case, I have to retry on 500 HTTP status code, below is my rest client code (we are using WSClient from play framework) you can change it to whatever rest-client as per requirement.

```<code> int MAX_RETRY = 3;
 CompletableFuture<WSResponse> future = new CompletableFuture<>();

 private CompletionStage<WSResponse> getWS(Object request,String url, int retry, CompletableFuture future) throws JsonProcessingException {
 ws.url(url)
        .post(Json.parse(mapper.writeValueAsString(request)))
        .whenCompleteAsync((wsResponse, exception) -> {
            if(wsResponse.getStatus() == 500 && retry < MAX_RETRY) {
                try {
                    getWS(request, retry+1, future);
                } catch (IOException e) {
                    throw new Exception(e);
                }
            }else {
                future.complete(wsResponse);
            }
        });

     return future;
}
</code>```

This code will return immediately if the status code is 200 or other than 500 whereas if HTTP status is 500 it will retry 3 times.

Title: Retry logic with CompletableFuture

Body:
I need to submit a task in an async framework I'm working on, but I need to catch for exceptions, and retry the same task multiple times before "aborting".

The code I'm working with is:

int retries = 0;
public CompletableFuture<Result> executeActionAsync() {

    // Execute the action async and get the future
    CompletableFuture<Result> f = executeMycustomActionHere();

    // If the future completes with exception:
    f.exceptionally(ex -> {
        retries++; // Increment the retry count
        if (retries < MAX_RETRIES)
            return executeActionAsync();  // <--- Submit one more time

        // Abort with a null value
        return null;
    });

    // Return the future
    return f;
}

This currently doesn't compile because the return type of the lambda is wrong: it expects a Result, but the executeActionAsync returns a CompletableFuture<Result>.

How can I implement this fully async retry logic?

Body:
maybe it's late but hopes someone might find this useful, I recently solved this problem for retrying rest API call on failure. In my case, I have to retry on 500 HTTP status code, below is my rest client code (we are using WSClient from play framework) you can change it to whatever rest-client as per requirement.

 int MAX_RETRY = 3;
 CompletableFuture<WSResponse> future = new CompletableFuture<>();

 private CompletionStage<WSResponse> getWS(Object request,String url, int retry, CompletableFuture future) throws JsonProcessingException {
 ws.url(url)
        .post(Json.parse(mapper.writeValueAsString(request)))
        .whenCompleteAsync((wsResponse, exception) -> {
            if(wsResponse.getStatus() == 500 && retry < MAX_RETRY) {
                try {
                    getWS(request, retry+1, future);
                } catch (IOException e) {
                    throw new Exception(e);
                }
            }else {
                future.complete(wsResponse);
            }
        });

     return future;
}

This code will return immediately if the status code is 200 or other than 500 whereas if HTTP status is 500 it will retry 3 times.


问:
How to print Radio Control information
I am using mechanize module to retrieve information from a web page. It has a radio control section which I select before moving to the next page. I could easily select the value by assigning value to it. But coulnt retrieve the value of the candidate radio button. RadioSelect part of my form looks like below:

```<code><RadioControl(rdoSelect=[1634,ABX EXPRESS, 16650,XYZ EXP])>
</code>```

I could easily set the values by:

```<code>br.form['txtSource']='1634,ABX EXPRESS'
</code>```

What I want is to retireve the list :

```<code>[1634,ABX EXPRESS, 16650,XYZ EXP]
</code>```

UPDATE:

When I gave

```<code>print br.form['rdoSelect']
</code>```

It gives [] as result

I could get the value using

```<code>print br.form.possible_items("rdoSelect")
</code>```

But its giving me this

```<code>/usr/lib/python2.5/site-packages/ClientForm.py:2984: DeprecationWarning: [item.name for item in self.items]
  return c.possible_items(by_label)
</code>```

答:
First, a deprecation warning is not an error. Usually it means the library or code you are running was written for an earlier version of Python.

I am not sure how txtSource relates to rdoSelect (seems you expect them to contain the same value?). However a radio button usually has a symbolic value rather than the text displayed. Can you provide a sample of the HTML code?

Title: How to print Radio Control information

Body:
I am using mechanize module to retrieve information from a web page. It has a radio control section which I select before moving to the next page. I could easily select the value by assigning value to it. But coulnt retrieve the value of the candidate radio button. RadioSelect part of my form looks like below:

<RadioControl(rdoSelect=[1634,ABX EXPRESS, 16650,XYZ EXP])>

I could easily set the values by:

br.form['txtSource']='1634,ABX EXPRESS'

What I want is to retireve the list :

[1634,ABX EXPRESS, 16650,XYZ EXP]

UPDATE:

When I gave

print br.form['rdoSelect']

It gives [] as result

I could get the value using

print br.form.possible_items("rdoSelect")

But its giving me this

/usr/lib/python2.5/site-packages/ClientForm.py:2984: DeprecationWarning: [item.name for item in self.items]
  return c.possible_items(by_label)


问:
Django CSS changes are not applied
I am new to Django and I am using a CSS file for my styles and for now the styles are applied to my html. Now I have created a new class:

```<code>.post-image {
    height: 500px;
    width: 500px;
  }
</code>```

and have applied the class to the HTML element I want to style like this:

```<code><img class="post-image" src="{{ post.image.url }}" alt="">
</code>```

But the class post-image does not apply somehow. When I change it back to the old class the image gets resized. Also when I tried to edit the old class in my main.css the changes were not applied.

My main.css file is in my static directory and I have added the static directory in my settings.py file like this:

```<code>STATIC_URL = '/static/'
</code>```

and I have imported the stylesheet in my base.html like this:

```<code><link rel="stylesheet" type="text/css" href="{% static 'feed/main.css' %}">
</code>```

答: I had to clear the cache... :)</p>

Title: Django CSS changes are not applied

Body:
I am new to Django and I am using a CSS file for my styles and for now the styles are applied to my html. Now I have created a new class:

.post-image {
    height: 500px;
    width: 500px;
  }

and have applied the class to the HTML element I want to style like this:

But the class post-image does not apply somehow. When I change it back to the old class the image gets resized. Also when I tried to edit the old class in my main.css the changes were not applied.

My main.css file is in my static directory and I have added the static directory in my settings.py file like this:

STATIC_URL = '/static/'

and I have imported the stylesheet in my base.html like this:

<link rel="stylesheet" type="text/css" href="{% static 'feed/main.css' %}">

Body: I had to clear the cache... :)


问:
How to check if flutter toast already on screen?
I want to show a toast message on my app whenever right condition is met based on some integer values calculation. This condition is met often and I want to show a toast message onScreen. I chose flutter toast plugin for this. But sometimes the method is sending too many toast that toast message consists even after the app is closed. So I want to know if a toast message already on screen and cancel if so.

How do I check if flutter toast already on screen?

Alternatively please suggest me other dialogue showing way on flutter.

```<code>//check if exist then cancel. Or show.
Fluttertoast.showToast(
        msg: "This is condition met Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );
</code>```

答:
you can modify the FluttertoastPlugin.java https://github.com/PonnamKarthik/FlutterToast/blob/master/android/src/main/java/io/github/ponnamkarthik/toast/fluttertoast/FluttertoastPlugin.java

add the cancel method before showToast

Body:
I want to show a toast message on my app whenever right condition is met based on some integer values calculation. This condition is met often and I want to show a toast message onScreen. I chose flutter toast plugin for this. But sometimes the method is sending too many toast that toast message consists even after the app is closed. So I want to know if a toast message already on screen and cancel if so.

How do I check if flutter toast already on screen?

Alternatively please suggest me other dialogue showing way on flutter.

//check if exist then cancel. Or show.
Fluttertoast.showToast(
        msg: "This is condition met Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );


问:
Connection String and Datacontext in LINQ
I am developing a site using ASP.NET, SQL 2008 and LINQ. I want to ask about the connection string. I have made a class like that to get the datacontext in each page:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DatabaseConnection
{
    static DataClassesDataContext datacontext;
    public static DataClassesDataContext getConnection()
    {
       datacontext = new DataClassesDataContext(@"Data Source=localhost;Initial Catalog=dbname; Integrated Security=True");
        return datacontext;
    }
}
</code>```

Is that a correct way to get the connection in each page?

Also about 'Data Source', when I deploy the site what will it be? And what is the difference between data source and address keywords?

答:
That is a valid way of getting the data context instance, yes.  You can use Data Source or Server I believe.

Please be aware that DataContext is IDisposable, so make sure it's not left hanging around after usage, I tend to do:

```<code>using (var context = DataHelper.GetContext())
{
   // Stuff.
}
</code>```

Also, you should really put your connection strings in the configuration file:

```<code><connectionStrings>
   <add name="Live" connectionString="blah;"/>
</connectionStrings>
</code>```

Body:
I am developing a site using ASP.NET, SQL 2008 and LINQ. I want to ask about the connection string. I have made a class like that to get the datacontext in each page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public static class DatabaseConnection
{
    static DataClassesDataContext datacontext;
    public static DataClassesDataContext getConnection()
    {
       datacontext = new DataClassesDataContext(@"Data Source=localhost;Initial Catalog=dbname; Integrated Security=True");
        return datacontext;
    }
}

Is that a correct way to get the connection in each page?

Also about 'Data Source', when I deploy the site what will it be? And what is the difference between data source and address keywords?

Body:
That is a valid way of getting the data context instance, yes.  You can use Data Source or Server I believe.

Please be aware that DataContext is IDisposable, so make sure it's not left hanging around after usage, I tend to do:

using (var context = DataHelper.GetContext())
{
   // Stuff.
}

Also, you should really put your connection strings in the configuration file:

<connectionStrings>
   <add name="Live" connectionString="blah;"/>
</connectionStrings>


问:
flutter - how to show a CircularProgressIndicator within a rflutter_alert dialog
I have the following code. When the user clicks the Save button, a web service is run. How would I show the CircularProgressIndicator inside the rflutter_alert dialog while the service is running? If the web service fails, I would like the alert dialog to remain open so they can try again.

Thanks,

Paul

```<code>Future<bool> saveRequest({context, int rId}) {
  String _reason = '';
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController reasonController = TextEditingController();

  TextStyle _style = TextStyle(
      fontFamily: 'Montserrat', fontSize: 18.0, fontWeight: FontWeight.normal);

  InputDecoration _textFormFieldDecoration({String hintText, double padding}) =>
      InputDecoration(
        //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
        contentPadding: EdgeInsets.all(padding),
        isDense: true,
        hintText: hintText,
        hintStyle: TextStyle(color: kHintText),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
      );

  return Alert(
    context: context,
    title: 'New Request',
    //desc: 'Reason',
    content: Form(
     key: _formKey,
     child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 20.0),
        Text('Reason', textAlign: TextAlign.left, style: _style),
        SizedBox(height: 10.0),
        TextFormField(
          validator: (value) {
            if (value.isEmpty) {
              return "please enter reason";
            }
            return null;
          },
          onSaved: (value) {
            _reason = value;
          },
          decoration: _textFormFieldDecoration(
            hintText: 'reason for request',
            padding: 8.0,
          ),
          controller: reasonController,
        ),
        SizedBox(height: 10.0),
      ],
     ),
    ),
    buttons: [
      DialogButton(
        child:
            Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () async {
          if (_formKey.currentState.validate()) {
            _formKey.currentState.save();
            var saved = await doSaveRequest(pReason: _reason);
            Navigator.pop(context, false);
            if (saved.savedOK) {
              Navigator.of(context).pop();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UserRequests(
                    rId: rId,
                  ),
                ),
              );
            } else {
              Navigator.pop(context, false);
            }
          }
        },
      ),
      DialogButton(
        child:
            Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () {
          Navigator.pop(context, false);
        },
      ),
    ],
  ).show();
}
</code>```

答:
You can copy paste run full code below

Step 1: The following code use 3 seconds delay to simulate doSaveRequest()

Step 2: You can use StreamBuilder<bool> and use _events.add(true); before doSaveRequest() to show CircularProgressIndicator()

Step 3: back to Form screen with _events.add(false);

code snippet

```<code>Future<bool> doSaveRequest({String pReason}) async {
    await Future.delayed(const Duration(seconds: 3), () {});
    print("3 secs");
    return false;
  }

return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: StreamBuilder<bool>(
          initialData: false,
          stream: _events.stream,
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            print(" ${snapshot.data.toString()}");
            return snapshot.data
                ? CircularProgressIndicator()
                : Form(
                    key: _formKey,
    ...
    onPressed: () async {
                if (_formKey.currentState.validate()) {
                  ...
                  _events.add(true);

                  var saved = await doSaveRequest(pReason: _reason);
                  if (saved) {
                    Navigator.pop(context, false);
                  } else {
                    _events.add(false);
                  }
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Color kMainColor = Colors.blue;
  Color kHintText = Colors.blue;
  StreamController<bool> _events;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  initState() {
    super.initState();
    _events = new StreamController<bool>();
  }

  Future<bool> doSaveRequest({String pReason}) async {
    await Future.delayed(const Duration(seconds: 3), () {});
    print("3 secs");
    return false;
  }

  Future<bool> saveRequest({context, int rId}) {
    String _reason = '';
    GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    TextEditingController reasonController = TextEditingController();

    TextStyle _style = TextStyle(
        fontFamily: 'Montserrat',
        fontSize: 18.0,
        fontWeight: FontWeight.normal);

    InputDecoration _textFormFieldDecoration(
            {String hintText, double padding}) =>
        InputDecoration(
          //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
          contentPadding: EdgeInsets.all(padding),
          isDense: true,
          hintText: hintText,
          hintStyle: TextStyle(color: kHintText),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
        );

    return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: StreamBuilder<bool>(
          initialData: false,
          stream: _events.stream,
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            print(" ${snapshot.data.toString()}");
            return snapshot.data
                ? CircularProgressIndicator()
                : Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        SizedBox(height: 20.0),
                        Text('Reason',
                            textAlign: TextAlign.left, style: _style),
                        SizedBox(height: 10.0),
                        TextFormField(
                          validator: (value) {
                            if (value.isEmpty) {
                              return "please enter reason";
                            }
                            return null;
                          },
                          onSaved: (value) {
                            _reason = value;
                          },
                          decoration: _textFormFieldDecoration(
                            hintText: 'reason for request',
                            padding: 8.0,
                          ),
                          controller: reasonController,
                        ),
                        SizedBox(height: 10.0),
                      ],
                    ),
                  );
          }),
      buttons: [
        DialogButton(
          child:
              Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              print(_reason);

              _events.add(true);

              var saved = await doSaveRequest(pReason: _reason);
              if (saved) {
                Navigator.pop(context, false);
              } else {
                _events.add(false);
              }
              /*if (saved.savedOK) {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => UserRequests(
                      rId: rId,
                    ),
                  ),
                );
              } else {
                Navigator.pop(context, false);
              }*/
            }
          },
        ),
        DialogButton(
          child: Text('Cancel',
              style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
      ],
    ).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Alert'),
              onPressed: () {
                saveRequest(context: context, rId: 123);
              },
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I have the following code. When the user clicks the Save button, a web service is run. How would I show the CircularProgressIndicator inside the rflutter_alert dialog while the service is running? If the web service fails, I would like the alert dialog to remain open so they can try again.

Thanks,

Paul

Future<bool> saveRequest({context, int rId}) {
  String _reason = '';
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController reasonController = TextEditingController();

  TextStyle _style = TextStyle(
      fontFamily: 'Montserrat', fontSize: 18.0, fontWeight: FontWeight.normal);

  InputDecoration _textFormFieldDecoration({String hintText, double padding}) =>
      InputDecoration(
        //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
        contentPadding: EdgeInsets.all(padding),
        isDense: true,
        hintText: hintText,
        hintStyle: TextStyle(color: kHintText),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
      );

  return Alert(
    context: context,
    title: 'New Request',
    //desc: 'Reason',
    content: Form(
     key: _formKey,
     child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 20.0),
        Text('Reason', textAlign: TextAlign.left, style: _style),
        SizedBox(height: 10.0),
        TextFormField(
          validator: (value) {
            if (value.isEmpty) {
              return "please enter reason";
            }
            return null;
          },
          onSaved: (value) {
            _reason = value;
          },
          decoration: _textFormFieldDecoration(
            hintText: 'reason for request',
            padding: 8.0,
          ),
          controller: reasonController,
        ),
        SizedBox(height: 10.0),
      ],
     ),
    ),
    buttons: [
      DialogButton(
        child:
            Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () async {
          if (_formKey.currentState.validate()) {
            _formKey.currentState.save();
            var saved = await doSaveRequest(pReason: _reason);
            Navigator.pop(context, false);
            if (saved.savedOK) {
              Navigator.of(context).pop();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UserRequests(
                    rId: rId,
                  ),
                ),
              );
            } else {
              Navigator.pop(context, false);
            }
          }
        },
      ),
      DialogButton(
        child:
            Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () {
          Navigator.pop(context, false);
        },
      ),
    ],
  ).show();
}

Body:
You can copy paste run full code below

Step 1: The following code use 3 seconds delay to simulate doSaveRequest()

Step 2: You can use StreamBuilder<bool> and use _events.add(true); before doSaveRequest() to show CircularProgressIndicator()

Step 3: back to Form screen with _events.add(false);

code snippet

Future<bool> doSaveRequest({String pReason}) async {
    await Future.delayed(const Duration(seconds: 3), () {});
    print("3 secs");
    return false;
  }

return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: StreamBuilder<bool>(
          initialData: false,
          stream: _events.stream,
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            print(" ${snapshot.data.toString()}");
            return snapshot.data
                ? CircularProgressIndicator()
                : Form(
                    key: _formKey,
    ...
    onPressed: () async {
                if (_formKey.currentState.validate()) {
                  ...
                  _events.add(true);

                  var saved = await doSaveRequest(pReason: _reason);
                  if (saved) {
                    Navigator.pop(context, false);
                  } else {
                    _events.add(false);
                  }

working demo

full code

import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Color kMainColor = Colors.blue;
  Color kHintText = Colors.blue;
  StreamController<bool> _events;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  initState() {
    super.initState();
    _events = new StreamController<bool>();
  }

  Future<bool> doSaveRequest({String pReason}) async {
    await Future.delayed(const Duration(seconds: 3), () {});
    print("3 secs");
    return false;
  }

  Future<bool> saveRequest({context, int rId}) {
    String _reason = '';
    GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    TextEditingController reasonController = TextEditingController();

    TextStyle _style = TextStyle(
        fontFamily: 'Montserrat',
        fontSize: 18.0,
        fontWeight: FontWeight.normal);

    InputDecoration _textFormFieldDecoration(
            {String hintText, double padding}) =>
        InputDecoration(
          //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
          contentPadding: EdgeInsets.all(padding),
          isDense: true,
          hintText: hintText,
          hintStyle: TextStyle(color: kHintText),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
        );

    return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: StreamBuilder<bool>(
          initialData: false,
          stream: _events.stream,
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            print(" ${snapshot.data.toString()}");
            return snapshot.data
                ? CircularProgressIndicator()
                : Form(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        SizedBox(height: 20.0),
                        Text('Reason',
                            textAlign: TextAlign.left, style: _style),
                        SizedBox(height: 10.0),
                        TextFormField(
                          validator: (value) {
                            if (value.isEmpty) {
                              return "please enter reason";
                            }
                            return null;
                          },
                          onSaved: (value) {
                            _reason = value;
                          },
                          decoration: _textFormFieldDecoration(
                            hintText: 'reason for request',
                            padding: 8.0,
                          ),
                          controller: reasonController,
                        ),
                        SizedBox(height: 10.0),
                      ],
                    ),
                  );
          }),
      buttons: [
        DialogButton(
          child:
              Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              print(_reason);

              _events.add(true);

              var saved = await doSaveRequest(pReason: _reason);
              if (saved) {
                Navigator.pop(context, false);
              } else {
                _events.add(false);
              }
              /*if (saved.savedOK) {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => UserRequests(
                      rId: rId,
                    ),
                  ),
                );
              } else {
                Navigator.pop(context, false);
              }*/
            }
          },
        ),
        DialogButton(
          child: Text('Cancel',
              style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
      ],
    ).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Alert'),
              onPressed: () {
                saveRequest(context: context, rId: 123);
              },
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
Program to print all the bits of one byte union without using bitwise operators
I have to make a program which prints all the bits of one byte union (which can't be any bigger than that), without using bitwise operators. I got a problem to build suitable union which has only one byte because to my knowledge I can't use struct now, because struct has 4 bytes. This is what I've done already:</p>

```<code>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%hhu", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    printf("%u %u %u %u %u %u %u %u", word.a+0, word.a+1, word.a+2, word.a+3, word.a+4, word.a+5, word.a+6, word.a+7);
    return 0;
}

</code>```

```<code>#ifndef bit_set
#define bit_set
typedef unsigned char byte;
byte x;

union bit {
    unsigned int i : 1;
}foo;
union bit_set
{
    union bit a[8];
    byte x;
}word;

#endif

</code>```

答:
To print a byte in binary wit the most significant bit first you can do something like this:

```<code>void print_bits (unsigned char x)
{
  int i;
  for (i = 0; i < 8; i++) {
    if (x >= 0x80)
      printf("1");
    else
      printf("0");
    x = x / 2;
  }
}
</code>```

Though in general I would advise to use bitwise operators as they translate better to machine code resulting in better performance. The same function looks something like this:

```<code>void print_bits (unsigned char x)
{
  int i;
  for (i = 0; i < 8; i++) {
    if (x & 0x80 != 0)
      printf("1");
    else
      printf("0");
    x = x << 1;
  }
}
</code>```

Note that your code prints the least significant bit first, which is not how binary is usually represented.

Body:
I have to make a program which prints all the bits of one byte union (which can't be any bigger than that), without using bitwise operators. I got a problem to build suitable union which has only one byte because to my knowledge I can't use struct now, because struct has 4 bytes. This is what I've done already:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%hhu", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    printf("%u %u %u %u %u %u %u %u", word.a+0, word.a+1, word.a+2, word.a+3, word.a+4, word.a+5, word.a+6, word.a+7);
    return 0;
}

#ifndef bit_set
#define bit_set
typedef unsigned char byte;
byte x;

union bit {
    unsigned int i : 1;
}foo;
union bit_set
{
    union bit a[8];
    byte x;
}word;

#endif

Body:
To print a byte in binary wit the most significant bit first you can do something like this:

void print_bits (unsigned char x)
{
  int i;
  for (i = 0; i < 8; i++) {
    if (x >= 0x80)
      printf("1");
    else
      printf("0");
    x = x / 2;
  }
}

Though in general I would advise to use bitwise operators as they translate better to machine code resulting in better performance. The same function looks something like this:

void print_bits (unsigned char x)
{
  int i;
  for (i = 0; i < 8; i++) {
    if (x & 0x80 != 0)
      printf("1");
    else
      printf("0");
    x = x << 1;
  }
}

Note that your code prints the least significant bit first, which is not how binary is usually represented.


问:
Convert numbers to strings when reading an excel spreadsheet into a pandas DataFrame
I'm reading some excel spreadsheets (xlsx format) into pandas using read_excel, which generally works great. The problem I have is that when a column contains numbers, pandas converts these to float64 type, and I would like them to be treated as strings. After reading them in, I can convert the column to str:

```<code>my_frame.my_col = my_frame.my_col.astype('str')
</code>```

This works as far as assigning the right type to the column, but when I view the values in this column, the strings are formatted in scientific-format e.g. 8.027770e+14, which is not what I want. I'd like to work out how to tell pandas to read columns as strings, or do the conversion later so that I get values in their original (non-scientific) format.

答: I solve it with round, if you do round(number,5) in most case you will not lose data and you will get zero in the case of 8.027770e+14</p>

Body:
I'm reading some excel spreadsheets (xlsx format) into pandas using read_excel, which generally works great. The problem I have is that when a column contains numbers, pandas converts these to float64 type, and I would like them to be treated as strings. After reading them in, I can convert the column to str:

my_frame.my_col = my_frame.my_col.astype('str')

This works as far as assigning the right type to the column, but when I view the values in this column, the strings are formatted in scientific-format e.g. 8.027770e+14, which is not what I want. I'd like to work out how to tell pandas to read columns as strings, or do the conversion later so that I get values in their original (non-scientific) format.


问:
Declare a variable as Decimal
I'm optimizing a macro in VBA which had none of the data types declared, so everything was clumsily treated by the compiler as a variant. I'm dealing with scientific measurements, so I need precision.

How do I declare Dim decAsdf as Decimal (not like that but the proper way)?

答:
To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

```<code>Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub
</code>```

Title: Declare a variable as Decimal

Body:
To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub


问:
OpenFire server does not work with websockets
I am not able to use OpenFire server through WebSockets. This is the code client side I use to connect to the server:

```<code>    var ws = new WebSocket('ws://35.228.94.32:7070/ws-xmpp');

    ws.onopen = () => {
        // connection opened
        console.log('open')
    };

    ws.onmessage = (e) => {
        // a message was received
        console.log(e.data);
    };

    ws.onerror = (e) => {
        // an error occurred
        console.log("Error occured", e, e.message);
    };

    ws.onclose = (e) => {
        // connection closed
        console.log("Closing: ", e);
    };
</code>```

This is the error I receive:

Error occured {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"} failed to connect to /35.228.94.32 (port 7070) from
  /192.168.232.2 (port 54028) after 10000ms

Closing:  {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"}

I think it is a problem of OpenFire with websockets because if I try using xmpp protocol, it works. Can you help me?

答:
Your endpoint does not seem correct. Try this instead:

```<code>ws://35.228.94.32:7070/ws
</code>```

Optionally, if you want to use encryption, use:

```<code>wss://35.228.94.32:7443/ws
</code>```

You will need to have set up proper certificates for that to work though.

Body:
I am not able to use OpenFire server through WebSockets. This is the code client side I use to connect to the server:

    var ws = new WebSocket('ws://35.228.94.32:7070/ws-xmpp');

    ws.onopen = () => {
        // connection opened
        console.log('open')
    };

    ws.onmessage = (e) => {
        // a message was received
        console.log(e.data);
    };

    ws.onerror = (e) => {
        // an error occurred
        console.log("Error occured", e, e.message);
    };

    ws.onclose = (e) => {
        // connection closed
        console.log("Closing: ", e);
    };

This is the error I receive:

Error occured {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"} failed to connect to /35.228.94.32 (port 7070) from
  /192.168.232.2 (port 54028) after 10000ms

Closing:  {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"}

I think it is a problem of OpenFire with websockets because if I try using xmpp protocol, it works. Can you help me?

Body:
Your endpoint does not seem correct. Try this instead:

ws://35.228.94.32:7070/ws

Optionally, if you want to use encryption, use:

wss://35.228.94.32:7443/ws

You will need to have set up proper certificates for that to work though.


问:
Can't access v4beta1 APis of Google cloud talent solution
I am trying to use the new version v4beta1 of Google Cloud talent solution, but I am getting the permission error, have tried with all the required permissions using the JSON file, using the API key, but to no success.

Constantly getting this error -

PERMISSION_DENIED: The caller does not have permission

答:
You should export the path to JSON file with the key as GOOGLE_APPLICATION_CREDENTIALS env variable:</p>

```<code>export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
</code>```

Body:
You should export the path to JSON file with the key as GOOGLE_APPLICATION_CREDENTIALS env variable:

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"


Title: Create column of start date and end date from given date record

Body:
supposed my dataset

Name date
A    15-01-01
A    15-01-31
A    16-02-02
A    16-03-04
B    17-04-05
B    17-05-08
B    17-07-09
C    18-01-02
C    18-02-03

I want to add each person's first and last dates to a new column..

result what I want

Name date     startdate enddate
A    15-01-01 15-01-01  16-03-04
A    15-01-31 15-01-01  16-03-04
A    16-02-02 15-01-01  16-03-04
A    16-03-04 15-01-01  16-03-04
B    17-04-05 17-04-05  17-07-09
B    17-05-08 17-04-05  17-07-09
B    17-07-09 17-04-05  17-07-09
C    18-01-02 18-01-02  18-02-03
C    18-02-03 18-01-02  18-02-03

Is there a method to make this possible? I would appreciate it if you let me know.

thank you for reading

Body:
Use GroupBy.transform with GroupBy.first or GroupBy.last and add to new columns:

g = df.groupby('Name')['date']
df = df.assign(startdate = g.transform('first'), enddate = g.transform('last'))
print (df)
  Name      date startdate   enddate
0    A  15-01-01  15-01-01  16-03-04
1    A  15-01-31  15-01-01  16-03-04
2    A  16-02-02  15-01-01  16-03-04
3    A  16-03-04  15-01-01  16-03-04
4    B  17-04-05  17-04-05  17-07-09
5    B  17-05-08  17-04-05  17-07-09
6    B  17-07-09  17-04-05  17-07-09
7    C  18-01-02  18-01-02  18-02-03
8    C  18-02-03  18-01-02  18-02-03

Or if need minimal and maximal with GroupBy.min and GroupBy.max:

df['date'] = pd.to_datetime(df['date'], format='%y-%m-%d')
g = df.groupby('Name')['date']
df = df.assign(startdate = g.transform('min'), enddate = g.transform('max'))
print (df)
  Name       date  startdate    enddate
0    A 2015-01-01 2015-01-01 2016-03-04
1    A 2015-01-31 2015-01-01 2016-03-04
2    A 2016-02-02 2015-01-01 2016-03-04
3    A 2016-03-04 2015-01-01 2016-03-04
4    B 2017-04-05 2017-04-05 2017-07-09
5    B 2017-05-08 2017-04-05 2017-07-09
6    B 2017-07-09 2017-04-05 2017-07-09
7    C 2018-01-02 2018-01-02 2018-02-03
8    C 2018-02-03 2018-01-02 2018-02-03

Alternative with GroupBy.agg with DataFrame.join:

df1 = df.groupby('Name').agg(startdate = ('date','first'), lastdate = ('date','last'))
df = df.join(df1, on='Name')


问:
Missing values of map(key, value) in Freemarker when access randomly?
I'm having a strange problem with Freemarker map. My example is meant to display a list of cars with the associated owners' name:

Car(id,name,ownerId)

User(id,name)

Notice that the ownerId is the only bridge I can access owner from car. For some reasons, we don't create hibernate relation for these domains.

I added to model a list carList of Car(id,name,ownerId) and a Map<String, String> map which contains (userId, name) of all users.. It's because Freemarker only accept Map with key of type String.

While looping through the carList, I try to get the owner name through the map.

```<code><#list carList as car>
  ${map?values[car.ownerId]} - ${car.ownerId}<br/>
</#list>
</code>```

But the strange thing is that the result I got:

```<code>Tom - 1
Jerry - 2
Jerry - 2
David - 4
- 5
- 5
</code>```

The name of user "5" is missing, but it exists in the database. Besides, when I loop through the map the result is right:

```<code><#list map?keys as key>
  ${key} - ${map[key]}
</#list>
</code>```

The results:

```<code>1 - Tom
2 - Jerry
3 - Mickey
4 - David
5 - Mike
</code>```

The missing name happens for only a specific user. Do anyone know what is missing here?

答:
Warning: contains some speculation!

I believe that part of your problem is that you use map?values[car.ownerId] in order to retrieve the user's names. map?values gives you the sequence of values of your map hash (see FreeMarker documentation), which happens to be the sequence of usernames. Then you access its elements by index (not by userId!), which returns usernames for most of the cases, but not when the userId reaches the size of your map, because in your map hash with 5 elements, the value sequence can only be indexed from 0 to 4, and your userId has values 1 to 5.

If my theory is correct, then maybe using map[car.ownerId?c] will solve your problem (note: I assumed that car.ownerId is something numeric, and because the keys in your map hash are strings I used the ?c built-in to convert the numbers into an unformatted strings).

Body:
I'm having a strange problem with Freemarker map. My example is meant to display a list of cars with the associated owners' name:

Car(id,name,ownerId)

User(id,name)

Notice that the ownerId is the only bridge I can access owner from car. For some reasons, we don't create hibernate relation for these domains.

I added to model a list carList of Car(id,name,ownerId) and a Map<String, String> map which contains (userId, name) of all users.. It's because Freemarker only accept Map with key of type String.

While looping through the carList, I try to get the owner name through the map.

<#list carList as car>
  ${map?values[car.ownerId]} - ${car.ownerId}

</#list>

But the strange thing is that the result I got:

Tom - 1
Jerry - 2
Jerry - 2
David - 4
- 5
- 5

The name of user "5" is missing, but it exists in the database. Besides, when I loop through the map the result is right:

<#list map?keys as key>
  ${key} - ${map[key]}
</#list>

The results:

1 - Tom
2 - Jerry
3 - Mickey
4 - David
5 - Mike

The missing name happens for only a specific user. Do anyone know what is missing here?


问:
Angular 2/4 String Comparison with Ignore Case
I'm comparing a number of fields in an Angular 2 template and it works for same case properties but returns false for the same string on different cases. Is there a way to make it case insensitive perhaps through a simple pipe?

```<code><div *ngIf="query?.firstName == address.foreName"></div>
</code>```

答:
If you are doing lot of string operations in your application, I suggest using a third party library like this one -

How to install

```<code>npm install --save string
</code>```

Import

```<code>var S = require('string');
</code>```

Ignorecase Compare String

```<code>var isEqual = S('ignoreCase').equalsIgnoreCase('IGNORECASE')
</code>```

Body:
If you are doing lot of string operations in your application, I suggest using a third party library like this one -

How to install

npm install --save string

Import

var S = require('string');

Ignorecase Compare String

var isEqual = S('ignoreCase').equalsIgnoreCase('IGNORECASE')


问:
how to prevent recyclerView auto scroll?
I have a recyclerView with chat message and open it will scroll to the latest position,but i update item's height in onBindViewHolder and recyclerView will auto scroll to incorrect position,how to pin item position after update item's height?</p>

答:
into getMessages method add this below code </p>

```<code> layoutManager.smoothScrollToPosition(messagesRecycler, null, chatAdapter.getItemCount());
 chatAdapter.notifyDataSetChanged();
</code>```

Body:
into getMessages method add this below code

 layoutManager.smoothScrollToPosition(messagesRecycler, null, chatAdapter.getItemCount());
 chatAdapter.notifyDataSetChanged();


问:
Why result of put() from HashMap is compared with null when add into a HashSet in Java?
I try to understand the implementation of HashSet and I see that it uses the HashMap internally.
And when you add in an HashSet, internally you put in an HashMap like below:

```<code>private transient HashMap<E,Object> map;

private static final Object PRESENT = new Object();

public boolean add(E e) {
   return map.put(e, PRESENT)==null;
}
</code>```

But what I don't understand is why they use this ==null.

This is the signature oh put method:

```<code>public V put(K key, V value)
</code>```

I don't understand why the result of put is compared with null.

答:
The Javadoc of Set.add says:

Returns:
  true if this set did not already contain the specified element

The Javadoc of Map.put says:

Returns:
  the previous value associated with key, or null if there was no mapping for key.

So, whether or not null is returned by the put indicates whether or not the key/value pair was already in the map, and thus the key was "in the set".

Body:
I try to understand the implementation of HashSet and I see that it uses the HashMap internally.
And when you add in an HashSet, internally you put in an HashMap like below:

private transient HashMap<E,Object> map;

private static final Object PRESENT = new Object();

public boolean add(E e) {
   return map.put(e, PRESENT)==null;
}

But what I don't understand is why they use this ==null.

This is the signature oh put method:

public V put(K key, V value)

I don't understand why the result of put is compared with null.


问:
Using Java Stream API, finding highest value of variable, with the stream of the changes made to the variable

Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

```<code>enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}
</code>```

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

```<code>// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0
</code>```

Bob's highest balance is 1700.

答:
Cumulative Sum of each position can be computed like this:

List<Integer> integers = Arrays.asList(1200, 500, -700, 300, -800, -500);

Stream<Integer[]> cumulativeSum = Stream.iterate(
        new Integer[]{0, integers.get(0)},
        p -> new Integer[]{p[0] + 1, p[1] + integers.get(p[0] + 1)}
        )
        .limit(integers.size());
```

<p>With this you can get the max balance in this way:</p>

<pre class="lang-java prettyprint-override"><code>Integer[] max = cumulativeSum
        .max(Comparator.comparing(p -> p[1]))
        .get();
System.out.println("Position: " + max[0]);
System.out.println("Value: " + max[1]);
</code>```

Or with iterator but here is problem that last sum wouldn't be computed:

```<code>Stream<Integer> integerStream = Arrays.stream(new Integer[]{
        1200, 500, -700, 300, -800, -500});
Iterator<Integer> iterator = integerStream.iterator();
Integer maxCumulativeSum = Stream.iterate(iterator.next(), p -> p + iterator.next())
        .takeWhile(p -> iterator.hasNext())
        .max(Integer::compareTo).get();
System.out.println(maxCumulativeSum);
</code>```

Problem is with takeWhile and it may be solved with takeWhileInclusive (from external library).

Body:
Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0

Bob's highest balance is 1700.

Body:
Cumulative Sum of each position can be computed like this:

List<Integer> integers = Arrays.asList(1200, 500, -700, 300, -800, -500);

Stream<Integer[]> cumulativeSum = Stream.iterate(
        new Integer[]{0, integers.get(0)},
        p -> new Integer[]{p[0] + 1, p[1] + integers.get(p[0] + 1)}
        )
        .limit(integers.size());

With this you can get the max balance in this way:

Integer[] max = cumulativeSum
        .max(Comparator.comparing(p -> p[1]))
        .get();
System.out.println("Position: " + max[0]);
System.out.println("Value: " + max[1]);

Or with iterator but here is problem that last sum wouldn't be computed:

Stream<Integer> integerStream = Arrays.stream(new Integer[]{
        1200, 500, -700, 300, -800, -500});
Iterator<Integer> iterator = integerStream.iterator();
Integer maxCumulativeSum = Stream.iterate(iterator.next(), p -> p + iterator.next())
        .takeWhile(p -> iterator.hasNext())
        .max(Integer::compareTo).get();
System.out.println(maxCumulativeSum);

Problem is with takeWhile and it may be solved with takeWhileInclusive (from external library).