问:
.NET Core Docker Image for SPA Applications
What is the correct Docker image to use when creating a new ASP.NET Core MVC app, specifically with the React/Redux (or other Node.js required) template? If not a specific image, what commands or process should be followed in the Dockerfile for a Node.js app backed by ASP.NET Core MVC?

I don't require the SDK version of the framework for anything other than running the backing MVC site.

dotnet new reactredux

The runtime image does not have Node.js installed, and will error when trying to run the container.

Dockerfile:

```<code>FROM microsoft/aspnetcore:latest

ARG source=./bin/Debug/netcoreapp2.0/publish/
WORKDIR /app
COPY $source .

EXPOSE 80
ENTRYPOINT ["dotnet", "Project.dll"]
</code>```

Error:

```<code>Unhandled Exception: System.AggregateException: One or more errors occurred. (Failed to start Node process. To resolve this:.

[1] Ensure that Node.js is installed and can be found in one of the PATH directories.
    Current PATH enviroment variable is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    Make sure the Node executable is in one of those directories, or update your PATH.
</code>```

The project I am working with is being upgraded from ASP.NET MVC for .NET Standard 1.1 (standalone), to a new .NET Standard 2.0 React/Redux project.

答:
Even if you're running ASP.NET Core 3.0 the base images from Microsoft still does not contain NodeJS. You must install NodeJS by yourself. Luckily it's not that hard.

Here's how I solved it recently. Please note the Dockerfile is more like pseudo-code than fully functional, I stripped away most noise. It's installing version 10 of NodeJS, you can of course change that. Here are different node distributions you can install.

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build

# Install NodeJS 10
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install -y nodejs

RUN npm install
RUN npm run test-docker
RUN npm run build

RUN dotnet restore...

RUN dotnet test...

FROM build AS publish
RUN dotnet publish "Collector.Forms.Autogiro.Web.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Your.Web.dll"]
</code>```

Body:
What is the correct Docker image to use when creating a new ASP.NET Core MVC app, specifically with the React/Redux (or other Node.js required) template? If not a specific image, what commands or process should be followed in the Dockerfile for a Node.js app backed by ASP.NET Core MVC?

I don't require the SDK version of the framework for anything other than running the backing MVC site.

dotnet new reactredux

The runtime image does not have Node.js installed, and will error when trying to run the container.

Dockerfile:

FROM microsoft/aspnetcore:latest

ARG source=./bin/Debug/netcoreapp2.0/publish/
WORKDIR /app
COPY $source .

EXPOSE 80
ENTRYPOINT ["dotnet", "Project.dll"]

Error:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Failed to start Node process. To resolve this:.

[1] Ensure that Node.js is installed and can be found in one of the PATH directories.
    Current PATH enviroment variable is: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    Make sure the Node executable is in one of those directories, or update your PATH.

The project I am working with is being upgraded from ASP.NET MVC for .NET Standard 1.1 (standalone), to a new .NET Standard 2.0 React/Redux project.

Body:
Even if you're running ASP.NET Core 3.0 the base images from Microsoft still does not contain NodeJS. You must install NodeJS by yourself. Luckily it's not that hard.

Here's how I solved it recently. Please note the Dockerfile is more like pseudo-code than fully functional, I stripped away most noise. It's installing version 10 of NodeJS, you can of course change that. Here are different node distributions you can install.

FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build

# Install NodeJS 10
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install -y nodejs

RUN npm install
RUN npm run test-docker
RUN npm run build

RUN dotnet restore...

RUN dotnet test...

FROM build AS publish
RUN dotnet publish "Collector.Forms.Autogiro.Web.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Your.Web.dll"]


来源: stackexchange

问:
How to know asynchronously detect if async subprocess has terminated
I'm trying to use asyncio.create_subprocess_exec to launch a long-running process (a daemon sort of).

However I cannot await on it to know if the process has succeeded/failed. I have to asynchronously detect if the process has failed and handle it at that point. Otherwise I leave the subprocess daemon running and communicate with it over TCP/IP.

I could use a signal handler on SIGCHLD, but does asyncio have some built-in functionality to create a handler for the subprocess?

```<code>import asyncio
import subprocess

async def main():
    command = ["./some-long-running-daemon"]
    process = await asyncio.create_subprocess_exec(*command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(process.returncode) # this is None

if __name__ == "__main__":
    asyncio.run(main())
</code>```

I discovered that async create subprocess doesn't seem to behave well with the SIGCHILD at all (the handler doesn't even run). Whereas subprocess.Popen does. The Popen also has a poll() method whereas the async subprocess doesn't. It seems Popen is the right thing to use.

答:
If you're happy to write a signal handler, why not just create a new task that waits on the process to finish? You can then have your main task continue on doing whatever it wants.

```<code>import asyncio
import subprocess

async def child_done(proc):
    stdout, stderr = await proc.communicate()
    print('child done. output:', stdout, '-- return code was:', proc.returncode)

async def main():
    proc = await asyncio.create_subprocess_exec('ls', stdout=subprocess.PIPE)
    asyncio.create_task(child_done(proc))
    # do other stuff
    await asyncio.sleep(1)
    print('main done')

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

Which gives you output like:

```<code>child done. output: b'asyncio-test.py\n' -- return code was: 0
main done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use asyncio.create_subprocess_exec to launch a long-running process (a daemon sort of).

However I cannot await on it to know if the process has succeeded/failed. I have to asynchronously detect if the process has failed and handle it at that point. Otherwise I leave the subprocess daemon running and communicate with it over TCP/IP.

I could use a signal handler on SIGCHLD, but does asyncio have some built-in functionality to create a handler for the subprocess?

import asyncio
import subprocess

async def main():
    command = ["./some-long-running-daemon"]
    process = await asyncio.create_subprocess_exec(*command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(process.returncode) # this is None

if __name__ == "__main__":
    asyncio.run(main())

I discovered that async create subprocess doesn't seem to behave well with the SIGCHILD at all (the handler doesn't even run). Whereas subprocess.Popen does. The Popen also has a poll() method whereas the async subprocess doesn't. It seems Popen is the right thing to use.

Body:
If you're happy to write a signal handler, why not just create a new task that waits on the process to finish? You can then have your main task continue on doing whatever it wants.

import asyncio
import subprocess

async def child_done(proc):
    stdout, stderr = await proc.communicate()
    print('child done. output:', stdout, '-- return code was:', proc.returncode)

async def main():
    proc = await asyncio.create_subprocess_exec('ls', stdout=subprocess.PIPE)
    asyncio.create_task(child_done(proc))
    # do other stuff
    await asyncio.sleep(1)
    print('main done')

if __name__ == '__main__':
    asyncio.run(main())

Which gives you output like:

child done. output: b'asyncio-test.py\n' -- return code was: 0
main done


问:
Maven skipping dependency files?
I am using maven for my project. I have 5 local jar files as dependent files which i have specified in pom.xml as follows:

```<code>    <dependency>
    <groupId>EWSAPI</groupId>
    <artifactId>EWSAPI</artifactId>
    <version>1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/EWSAPI1.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.15</version>
    <scope>system</scope>
    <systemPath>${basedir}/jcifs-1.3.15.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.4</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-codec-1.4.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-httpclient-3.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-logging-1.1.1.jar</systemPath>
    </dependency>
</code>```

Now, when i try mvn install in command prompt to install the dependencies. I get the following message

```<code>The following files where skipped:
   EWSAPI:EWSAPI:java-source:sources:1.1
   commons-codec:commons-codec:java-source:sources:1.4
   commons-httpclient:commons-httpclient:java-source:sources:3.1
   commons-logging:commons-logging:java-source:sources:1.1.1
</code>```

and also one file jfis was skipped(the same that was mentioned above as a dependency)

I do not understand why maven is doing so? I appreciate your help on this. Thanks

答:
From the question, it is not clear what you are trying to do.

On one hand you mention I have 5 local jar files as dependent files and you have specified them with <system> scope in pom.xml.  On the other hand you mention running mvn install to install the dependencies.

You should avoid <system> scope unless there is a compelling reason, especially for third-party dependencies (like commons-codec).

mvn install builds the specified project and installs the same in the local repository. It does not install dependencies.

You can use mvn install:install-file <params> to install the dependencies to the local repository after downloading them separately.  They do not get installed in ${basedir}.

Do update your question suitably if the above does not help.

ContentLicense: CC BY-SA 3.0

Title: Maven skipping dependency files?

Body:
I am using maven for my project. I have 5 local jar files as dependent files which i have specified in pom.xml as follows:

    <dependency>
    <groupId>EWSAPI</groupId>
    <artifactId>EWSAPI</artifactId>
    <version>1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/EWSAPI1.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>jcifs</groupId>
    <artifactId>jcifs</artifactId>
    <version>1.3.15</version>
    <scope>system</scope>
    <systemPath>${basedir}/jcifs-1.3.15.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.4</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-codec-1.4.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-httpclient-3.1.jar</systemPath>
    </dependency>

    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
    <scope>system</scope>
    <systemPath>${basedir}/commons-logging-1.1.1.jar</systemPath>
    </dependency>

Now, when i try mvn install in command prompt to install the dependencies. I get the following message

The following files where skipped:
   EWSAPI:EWSAPI:java-source:sources:1.1
   commons-codec:commons-codec:java-source:sources:1.4
   commons-httpclient:commons-httpclient:java-source:sources:3.1
   commons-logging:commons-logging:java-source:sources:1.1.1

and also one file jfis was skipped(the same that was mentioned above as a dependency)

I do not understand why maven is doing so? I appreciate your help on this. Thanks


问:
Swift 5, iOS 13.3.1 FBSDKCoreKit error (Derived Data deletion doesn't help)
Have updated sudo gem install cocoapods --pre, iOS 13.3.1 on my iPhone 7, and Podfile.
After that FBSDKCoreKit error has appeared.

```<code>Thread 1 (0 __abort_with_payload):
    dyld`__abort_with_payload:
        0x10251f5dc <+0>:  mov    x16, #0x209
        0x10251f5e0 <+4>:  svc    #0x80
    ->  0x10251f5e4 <+8>:  b.lo   0x10251f600               ; <+36>
        0x10251f5e8 <+12>: stp    x29, x30, [sp, #-0x10]!
        0x10251f5ec <+16>: mov    x29, sp
        0x10251f5f0 <+20>: bl     0x10251dbe8               ; cerror_nocancel
        0x10251f5f4 <+24>: mov    sp, x29
        0x10251f5f8 <+28>: ldp    x29, x30, [sp], #0x10
        0x10251f5fc <+32>: ret
        0x10251f600 <+36>: ret
</code>```

Console:

```<code>dyld: Library not loaded: @rpath/FBSDKCoreKit.framework/FBSDKCoreKit
  Referenced from: /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/112:UA
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: code signature invalid for '/private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'

    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: code signature invalid for '/private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'

    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: stat() failed with errno=1
    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: code signature invalid for '/private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'

    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: stat() failed with errno=1
(lldb)
</code>```

To make this faster:

Already tried to clean the build folder, derived data;

Cleaned Pods and all pods references;

Tried to launch previous versions of the project;

Tried to install an exactly previous version of FacebookSDK.

All work if I launch the application on previous iOS firmware. iPhone 6/7/8 goes well it's firmware is below 13.3.1.

Deprecated methods for FacebookSDK? If there is no update for this framework, what's next?

答:
apple blocked load external library for free account from 13.3.1

use use_modular_headers! instead of useframework

solution

Body:
Have updated sudo gem install cocoapods --pre, iOS 13.3.1 on my iPhone 7, and Podfile.
After that FBSDKCoreKit error has appeared.

Thread 1 (0 __abort_with_payload):
    dyld`__abort_with_payload:
        0x10251f5dc <+0>:  mov    x16, #0x209
        0x10251f5e0 <+4>:  svc    #0x80
    ->  0x10251f5e4 <+8>:  b.lo   0x10251f600               ; <+36>
        0x10251f5e8 <+12>: stp    x29, x30, [sp, #-0x10]!
        0x10251f5ec <+16>: mov    x29, sp
        0x10251f5f0 <+20>: bl     0x10251dbe8               ; cerror_nocancel
        0x10251f5f4 <+24>: mov    sp, x29
        0x10251f5f8 <+28>: ldp    x29, x30, [sp], #0x10
        0x10251f5fc <+32>: ret
        0x10251f600 <+36>: ret

Console:

dyld: Library not loaded: @rpath/FBSDKCoreKit.framework/FBSDKCoreKit
  Referenced from: /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/112:UA
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: code signature invalid for '/private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'

    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: code signature invalid for '/private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'

    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: stat() failed with errno=1
    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: code signature invalid for '/private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'

    /private/var/containers/Bundle/Application/8A12DD33-F4BE-41BA-97AF-B6B112E40362/112:UA.app/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit: stat() failed with errno=1
(lldb)

To make this faster:

Already tried to clean the build folder, derived data;

Cleaned Pods and all pods references;

Tried to launch previous versions of the project;

Tried to install an exactly previous version of FacebookSDK.

All work if I launch the application on previous iOS firmware. iPhone 6/7/8 goes well it's firmware is below 13.3.1.

Deprecated methods for FacebookSDK? If there is no update for this framework, what's next?


问:
TestNG run the test several times conditionally
I want to run the test below 2 times(or more) first time the  Table.getTables() returns the list of tables which should contain 20 items, but when the tests runs second time it will not return any item. So, I want to check to see if it is first run then check to see if it has 20 items and if it is second run I want to check to see if it does not contain any item. I do not think invocationCount will work for me. Please see below. Thanks

Java 8 and TestNG 6.14.

    //Run this test twice
    @Test
    public void repeatTest() {
        List<String> tables = Table.getTables();
        //if it is 1st run then check this
        Assert.assertEquals(tables.size(), 20);

        //if it is second run then check this
        Assert.assertEquals(tables.size(), 0);
    }

```

答:
You can just call it twice:</p>

```<code>@Test
public void repeatTest() {
    List<String> firstList = Table.getTables();
    //if it is 1st run then check this
    Assert.assertEquals(firstList.size(), 20);

    List<String> secondList = Table.getTables();
    //if it is second run then check this
    Assert.assertEquals(secondList.size(), 0);
}
</code>```

Body:
You can just call it twice:

@Test
public void repeatTest() {
    List<String> firstList = Table.getTables();
    //if it is 1st run then check this
    Assert.assertEquals(firstList.size(), 20);

    List<String> secondList = Table.getTables();
    //if it is second run then check this
    Assert.assertEquals(secondList.size(), 0);
}


问:
Inserting date formula in excel getting #name? error after inserting with python
```<code>  for i,cellObj in enumerate(sheet_formula['R'],1):
       cellObj.value='= days($AG$1,C{0})'.format(i)
       sheet_formula.cell(row=1, column=18).value = 'Days Since'
</code>```

using this concept to enter the excel formula  in excel
after entering excel formula in excel i am getting "#NAME?" in excel column i don't know where i am doing wrong

答:
open-pyxl does not work with some of the excel  function. add the full name as such:

= days($AG$1,C{0})'.format(i)
change to = _xlfn.days($AG$1,C{0})'.format(i)
And it will be working correctly.

If you’re trying to use a formula that isn’t known this could be because you’re using a formula that was not included in the initial specification. Such formulae must be prefixed with xlfn. to work.

To check if a formula is included you can use:

from openpyxl.utils import FORMULAE

print "DAYS" in FORMULAE
if it false then _xlfn prefixed before the function

Body:
  for i,cellObj in enumerate(sheet_formula['R'],1):
       cellObj.value='= days($AG$1,C{0})'.format(i)
       sheet_formula.cell(row=1, column=18).value = 'Days Since'

using this concept to enter the excel formula  in excel
after entering excel formula in excel i am getting "#NAME?" in excel column i don't know where i am doing wrong


问:
mail send message display but mail is not coming
i have sendnewmail function using it send mail,in mail message is send message dispaly but in gmail its not coming ,this is the code</p>

```<code>function sendnewmail($msgnew,$emailidnew,$subjectnew){
   require_once("class.phpmailer.php");
      require_once("class.smtp.php");
         $mail = new PHPMailer();
      $mail->IsSMTP();     // set mailer to use SMTP
      $mail->Host = "mail.domain.com"; // specify main and backup server
      $mail->SMTPAuth = true;     // turn on SMTP authentication
      $mail->Username ="user";  // SMTP username
      $mail->Password ="password"; // SMTP password
      $mail->From = "abcds@gmail.com";
      $mail->FromName = "name";
      $mail->AddAddress($emailidnew,"sudeshna");
      $mail->WordWrap = 50;                                 // set word wrap to 50 characters
      $mail->IsHTML(true);                                  // set email format to HTML
          $mail->Subject = $subjectnew;
      $mail->Body    = $msgnew;
          if(!$mail->Send())      {
        echo "Message could not be sent. <p>";
         echo "Mailer Error: " . $mail->ErrorInfo;
         exit;
  }else{
          echo 'Message send ok';
      }
}
$htmldetails ="Welcome to World";
$email = "abc@gmail.com";
$subject = "Sample welcome message";
sendnewmail($htmldetails,$email,$subject);

</code>```

答:
hope this work</p>

```<code>  function sendnewmail($msgnew,$emailidnew,$subjectnew){
  require_once("PHPMailer/class.phpmailer.php");
  require_once("PHPMailer/class.smtp.php");
  $mail = new PHPMailer();
  $mail->isSMTP();
  $mail->Host = "mail.domain.com"; // specify main and backup server
  $mail->Port = 465;

  $mail->SMTPSecure = 'ssl';

  $mail->SMTPAuth = true;
  $mail->Username ="user";  // SMTP username
  $mail->Password ="password"; // SMTP password
  $mail->From = "abc@domain.com";
  $mail->FromName = "name";
  $mail->AddAddress($emailidnew,"sudeshna");
  $mail->WordWrap = 50;
  $mail->IsHTML(true);
      $mail->Subject = $subjectnew;
  $mail->Body    = $msgnew;
      if(!$mail->Send())      {
    echo "Message could not be sent. <p>";
     echo "Mailer Error: " . $mail->ErrorInfo;
     exit;
  }else{
      echo 'Message send ok';
  }
 }
 $htmldetails ="Welcome to World";
 $email = "tausifahmad810@gmail.com";
 $subject = "Sample welcome message";
 sendnewmail($htmldetails,$email,$subject);
</code>```

Body:
i have sendnewmail function using it send mail,in mail message is send message dispaly but in gmail its not coming ,this is the code

function sendnewmail($msgnew,$emailidnew,$subjectnew){
   require_once("class.phpmailer.php");
      require_once("class.smtp.php");
         $mail = new PHPMailer();
      $mail->IsSMTP();     // set mailer to use SMTP
      $mail->Host = "mail.domain.com"; // specify main and backup server
      $mail->SMTPAuth = true;     // turn on SMTP authentication
      $mail->Username ="user";  // SMTP username
      $mail->Password ="password"; // SMTP password
      $mail->From = "abcds@gmail.com";
      $mail->FromName = "name";
      $mail->AddAddress($emailidnew,"sudeshna");
      $mail->WordWrap = 50;                                 // set word wrap to 50 characters
      $mail->IsHTML(true);                                  // set email format to HTML
          $mail->Subject = $subjectnew;
      $mail->Body    = $msgnew;
          if(!$mail->Send())      {
        echo "Message could not be sent.
";
         echo "Mailer Error: " . $mail->ErrorInfo;
         exit;
  }else{
          echo 'Message send ok';
      }
}
$htmldetails ="Welcome to World";
$email = "abc@gmail.com";
$subject = "Sample welcome message";
sendnewmail($htmldetails,$email,$subject);

Body:
hope this work

  function sendnewmail($msgnew,$emailidnew,$subjectnew){
  require_once("PHPMailer/class.phpmailer.php");
  require_once("PHPMailer/class.smtp.php");
  $mail = new PHPMailer();
  $mail->isSMTP();
  $mail->Host = "mail.domain.com"; // specify main and backup server
  $mail->Port = 465;

  $mail->SMTPSecure = 'ssl';

  $mail->SMTPAuth = true;
  $mail->Username ="user";  // SMTP username
  $mail->Password ="password"; // SMTP password
  $mail->From = "abc@domain.com";
  $mail->FromName = "name";
  $mail->AddAddress($emailidnew,"sudeshna");
  $mail->WordWrap = 50;
  $mail->IsHTML(true);
      $mail->Subject = $subjectnew;
  $mail->Body    = $msgnew;
      if(!$mail->Send())      {
    echo "Message could not be sent. <p>";
     echo "Mailer Error: " . $mail->ErrorInfo;
     exit;
  }else{
      echo 'Message send ok';
  }
 }
 $htmldetails ="Welcome to World";
 $email = "tausifahmad810@gmail.com";
 $subject = "Sample welcome message";
 sendnewmail($htmldetails,$email,$subject);


问:
How to encrypt a text
I need to implement a simple text encryption in C++ without using any existing framworks. This is purely for educational purpose to learn the in-and-outs and to learn the way to implement such a system. I am not planning to implement this in production code. I can use Windows APIs but it won't be cross platform. I am trying to learn something can work across multiple platforms. the best way to implement this is implement using C/C++. Please share good resources or links in this regard.</p>

答:
Depending on what you actually want, you could look at the CipherSaber project: instructions to implement your own RC4 encryption code for a simple IV+text format.

However this is an academic exercise only: you should never use your own crypto code in production unless you really know what you're doing. You could also read Schneier's Applied Cryptography for a good introduction to all of this stuff.

Title: How to encrypt a text


问:
What is "?." operator in flutter
I am using a library and in many places ?.
operator is used i am unable to understand it's purpose.</p>

```<code>Timer _debounceTimer;
  @override
  initState() {
    _textController.addListener(() {
      // We debounce the listener as sometimes the caret position is updated after the listener
      // this assures us we get an accurate caret position.
      if (_debounceTimer?.isActive ?? false) _debounceTimer.cancel();
</code>```

答:
?. [Conditional member access] - Like ., but the leftmost operand can be
  null; example: foo?.bar selects property bar from expression foo
  unless foo is null (in which case the value of foo?.bar is null)

from Dart Language Tour (Other Operators)

TLDR: It is simply does a null check before accessing member. If left hand side of the operator is not null then it works simply as . and if it is null value then the whole thing is null.

In your example: _debounceTimer?.isActive - if _debounceTimer is null then _debounceTimer?.isActive <-> null and if _debounceTimer is not null  then _debounceTimer?.isActive <-> _debounceTimer.isActive.

Also check: Dart Language tour (Conditional Expressions) for ?? and ? operator.

Title: What is "?." operator in flutter

Body:
I am using a library and in many places ?.
operator is used i am unable to understand it's purpose.

Timer _debounceTimer;
  @override
  initState() {
    _textController.addListener(() {
      // We debounce the listener as sometimes the caret position is updated after the listener
      // this assures us we get an accurate caret position.
      if (_debounceTimer?.isActive ?? false) _debounceTimer.cancel();


问:
Java Example: Dynamic Job Scheduling with Quartz
I want to expose an user interface to define Quartz JOBs dynamically. Where user should have facility to define JOBs properties like JOB name, cron expression or time interval, specific java class for task etc.

Is there any Open Source that facilitates this feature? Or, If I want to create my own module for dynamic Quartz Scheduler, what should be the way to do so?

答:
I have similar issue where I want to update the cron expression in JOB_DETAILS table of quartz(2.3.2 version).
The scenario is like, I have already a scheduled job running and I want to update it and run it on different frequency.
Rest of the things I managed but the update on the table won't happen. So after reading the documentation I found out that you can update the details of the job using add method.

```<code>// store, and set overwrite flag to 'true'
scheduler.addJob(jobDetail, true);
</code>```

The things I am doing with Java only.

Body:
I have similar issue where I want to update the cron expression in JOB_DETAILS table of quartz(2.3.2 version).
The scenario is like, I have already a scheduled job running and I want to update it and run it on different frequency.
Rest of the things I managed but the update on the table won't happen. So after reading the documentation I found out that you can update the details of the job using add method.

// store, and set overwrite flag to 'true'
scheduler.addJob(jobDetail, true);

The things I am doing with Java only.


问:
Google Maps Android API: Authorization failure
Android Studio 3.6

I added the following in my app/build.gradle file:

```<code>implementation 'com.google.android.gms:play-services-maps:17.0.0'
</code>```

In google_maps_api.xml, I've added my API key like this:

```<code>    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyAu_1111111</string>
</code>```

In manifest file:

```<code>  <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAu_1111111" />
</code>```

On google console my API key is ENABLED

Here's my layout:

```<code>        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/profileDetailsToolbar"
tools:context=".ui.activity.MapActivity" />
</code>```

Here's my actvity:

```<code>class MapActivity : RootActivity(), OnMapReadyCallback {

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dataBinding =
            DataBindingUtil.setContentView(this, R.layout.map_activity)
        dataBinding.setHandler(this)

        init()
    }

    private fun init() {
        setSupportActionBar(findViewById(R.id.toolBar))
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true)
        getSupportActionBar()?.setHomeButtonEnabled(true)
        getSupportActionBar()?.setDisplayShowTitleEnabled(false)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}
</code>```

But when I start my activity the map is not show.
In logcat I get the next error:

```<code>12-20 09:59:10.675 E/Google Maps Android API( 5153): Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
12-20 09:59:10.676 E/Google Maps Android API( 5153): In the Google Developer Console (https://console.developers.google.com)
12-20 09:59:10.676 E/Google Maps Android API( 5153): Ensure that the "Google Maps Android API v2" is enabled.
12-20 09:59:10.676 E/Google Maps Android API( 5153): Ensure that the following Android Key exists:
12-20 09:59:10.676 E/Google Maps Android API( 5153):    API Key: YOUR_API_KEY
12-20 09:59:10.676 E/Google Maps Android API( 5153):    Android Application (<cert_fingerprint>;<package_name>): some_hex_value;com.myproject
</code>```

答:
Since you are already using an API key, the error could be caused by any of the following:

using an API key but from a project without a valid billing account

using an invalid/incorrect/malformed API key

using an API key which is restricted to other applications aside from your own

Maps SDK for Android is not enabled on your project

Make sure you are using an API key from a project that has a valid billing account since it is  stated in Maps SDK for Android documentation that before you can start using the Google Maps Platform APIs and SDKs, you must sign up and create a billing account.

Also, if your API key has restrictions, make sure that it is properly restricted according to the API key best Practices. And lastly, make sure that you have enabled Maps SDK for Android for your maps project in the GCP console.

Body:
Android Studio 3.6

I added the following in my app/build.gradle file:

implementation 'com.google.android.gms:play-services-maps:17.0.0'

In google_maps_api.xml, I've added my API key like this:

    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyAu_1111111</string>

In manifest file:

  <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAu_1111111" />

On google console my API key is ENABLED

Here's my layout:

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/profileDetailsToolbar"
tools:context=".ui.activity.MapActivity" />

Here's my actvity:

class MapActivity : RootActivity(), OnMapReadyCallback {

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dataBinding =
            DataBindingUtil.setContentView(this, R.layout.map_activity)
        dataBinding.setHandler(this)

        init()
    }

    private fun init() {
        setSupportActionBar(findViewById(R.id.toolBar))
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true)
        getSupportActionBar()?.setHomeButtonEnabled(true)
        getSupportActionBar()?.setDisplayShowTitleEnabled(false)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

But when I start my activity the map is not show.
In logcat I get the next error:

12-20 09:59:10.675 E/Google Maps Android API( 5153): Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
12-20 09:59:10.676 E/Google Maps Android API( 5153): In the Google Developer Console (https://console.developers.google.com)
12-20 09:59:10.676 E/Google Maps Android API( 5153): Ensure that the "Google Maps Android API v2" is enabled.
12-20 09:59:10.676 E/Google Maps Android API( 5153): Ensure that the following Android Key exists:
12-20 09:59:10.676 E/Google Maps Android API( 5153):    API Key: YOUR_API_KEY
12-20 09:59:10.676 E/Google Maps Android API( 5153):    Android Application (<cert_fingerprint>;<package_name>): some_hex_value;com.myproject


问:
mysql array of objects compare items
I have problem in mysql json that I want to compare one item of object in json array.
example:
in my table i have column aJson that is array :

```<code>[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":2}]
</code>```

I want to find the records where Code is greater than 3

output:

```<code>[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":8}]
</code>```

same for equal,less,like ...

答:
thanks it works as this ...

```<code>> mysql> SELECT mycolumn
>      > FROM mytable
>      > WHERE mycolumn->"$[*].Code" > 3
</code>```

but what about this sample

```<code>[
  {
    "Name": "Mohsen",
    "Code": 10,
    "Arrays": [
      {
        "Name": "Mohsen",
        "Code": 6
      },
      {
        "Name": "Ali",
        "Code": 7
      },
      {
        "Name": "Reza",
        "Code": 8
      }
    ]
  },
  {
    "Name": "Ali",
    "Code": 11,
    "Arrays": [
      {
        "Name": "Mohsen",
        "Code": 6
      },
      {
        "Name": "Ali",
        "Code": 7
      },
      {
        "Name": "Reza",
        "Code": 8
      }
    ]
  },
  {
    "Name": "Reza",
    "Code": 12,
    "Arrays": [
      {
        "Name": "Mohsen",
        "Code": 6
      },
      {
        "Name": "Ali",
        "Code": 7
      },
      {
        "Name": "Reza",
        "Code": 8
      }
    ]
  }
]
</code>```

find records that Arrays.Code > 3

the follow query did not work ...

```<code>SELECT * from table WHERE aJson->"$[*].Arrays[*].Code" > 7
</code>```

return all records

Title: mysql array of objects compare items

Body:
I have problem in mysql json that I want to compare one item of object in json array.
example:
in my table i have column aJson that is array :

[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":2}]

I want to find the records where Code is greater than 3

output:

[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":8}]

same for equal,less,like ...

Body:
thanks it works as this ...

> mysql> SELECT mycolumn
>      > FROM mytable
>      > WHERE mycolumn->"$[*].Code" > 3

but what about this sample

[
  {
    "Name": "Mohsen",
    "Code": 10,
    "Arrays": [
      {
        "Name": "Mohsen",
        "Code": 6
      },
      {
        "Name": "Ali",
        "Code": 7
      },
      {
        "Name": "Reza",
        "Code": 8
      }
    ]
  },
  {
    "Name": "Ali",
    "Code": 11,
    "Arrays": [
      {
        "Name": "Mohsen",
        "Code": 6
      },
      {
        "Name": "Ali",
        "Code": 7
      },
      {
        "Name": "Reza",
        "Code": 8
      }
    ]
  },
  {
    "Name": "Reza",
    "Code": 12,
    "Arrays": [
      {
        "Name": "Mohsen",
        "Code": 6
      },
      {
        "Name": "Ali",
        "Code": 7
      },
      {
        "Name": "Reza",
        "Code": 8
      }
    ]
  }
]

find records that Arrays.Code > 3

the follow query did not work ...

SELECT * from table WHERE aJson->"$[*].Arrays[*].Code" > 7

return all records


问:
Invoking a component method from a service fails due to null error
I am trying to invoke a dialog box from my authentication service. I am basically trying to invoke it as soon as the user is authenticated. I have created a dialog component called shared-modal.component.
This component is injected in agreement component html. Agreement component exposes a load method that will try to open the shared modal.

At the moment I am getting agreement instance of the view child null in the service hence unable to call. Could somebody tell me how else i can invoke the dialog box

Share modal component

```<code>import { Component, Input} from '@angular/core';
declare var $: any;
@Component({
    selector: 'shared-modal',
    templateUrl: './shared-modal.component.html'
})
export class SharedModalComponent {
    _isopen = false;
    private _modalSize = 1; // 1:normal, 2: medium, 3: large, 4: extra large
    public get modalSize() {
        return this._modalSize;
    }

    @Input()
    public set modalSize(value) {
        this._modalSize = value;
    }

    get open(): boolean {
        return this._isopen;
    }

    @Input()
    set open(val: boolean) {
        this._isopen = val;
    }
    getModalDialogClass() {
        if (this.modalSize == null || this.modalSize <= 1 || this.modalSize > 4) {
            return 'modal-dialog modal-sm';
        } else if (this.modalSize <= 2) {
            return 'modal-dialog modal-md';
        } else if (this.modalSize <= 3) {
            return 'modal-dialog modal-lg';
        }  else if (this.modalSize <= 4) {
            return 'modal-dialog modal-xl';
        }
    }
}
</code>```

shared modal html

```<code><div id="modal_container">
        <div id="shared_modal" class="modal fade show" data-backdrop="static" data-keyboard="false" role="dialog" [ngStyle]="{'display': _isopen ? 'block' : 'none','z-index':'1050' }">
            <div [ngClass] = "getModalDialogClass()">
                <div class="modal-content">
                    <div class="modal-header">
                        <ng-content select=[header]></ng-content>
                    </div>
                    <div class="modal-body">
                        <ng-content select=[body]></ng-content>
                    </div>
                    <div class="modal-footer">
                        <ng-content select=[footer]></ng-content>
                    </div>

                </div>
            </div>
        </div>
        <div class="modal-backdrop fade show" *ngIf="_isopen" style="display: block; z-index: 1040;"></div>
        <div class="modal-backdrop fade show" *ngIf="!_isopen" style="display: none; z-index: 1040;"></div>
    </div>
</code>```

Agreement  html

```<code><shared-modal [modalSize]="4" [open]="agreementWindowOpened">
    <div style="width: 100%;" header>
        <div style="text-align: right">
            <div class="etp-close pull-right" (click)="dismissAgreementWindow()"></div>
        </div>
        <h4 class="modal-title">Agreement</h4>
    </div>
    <div body>
                Hello World

    </div>
    <div footer>
    </div>
</shared-modal>
</code>```

Agreement component

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-agreement',
  templateUrl: './agreement.component.html',
  styleUrls: ['./agreement.component.scss']
})
export class AgreementComponent implements OnInit {

  agreementWindowOpened: boolean;

  constructor() { }

  ngOnInit() {
  }

 Load() {
    this.agreementWindowOpened = true;
  }

  dismissAgreementWindow() {
    this.agreementWindowOpened = false;
}
}
</code>```

Service

```<code>@ViewChild(AgreementComponent, { static: false }) agreement: AgreementComponent;

    authCallback = (errorDesc: any, token: any, error: any, tokenType: any) => {

    if (this.userTryingToResetPassword(token, errorDesc)) {

      const passResetApplication = this.createUserAgentApplication(this.passwordResetAuthority);
      passResetApplication.loginRedirect(this.settings.aad.b2cScopes);
    }
    if (!errorDesc) {
      this.cacheUserPermissions();
      // Call the agreement dialog box here
      if (this.agreement) {
       this.agreement.Load();
      }
    }

  }
</code>```

答: @ViewChild is only meant to work with Components and Directives that's why it returns null. What you probably need is to create your modal component dynamically. There is a pretty good tutorial on how to do it in the official docs https://angular.io/guide/dynamic-component-loader </p>

Body:
I am trying to invoke a dialog box from my authentication service. I am basically trying to invoke it as soon as the user is authenticated. I have created a dialog component called shared-modal.component.
This component is injected in agreement component html. Agreement component exposes a load method that will try to open the shared modal.

At the moment I am getting agreement instance of the view child null in the service hence unable to call. Could somebody tell me how else i can invoke the dialog box

Share modal component

import { Component, Input} from '@angular/core';
declare var $: any;
@Component({
    selector: 'shared-modal',
    templateUrl: './shared-modal.component.html'
})
export class SharedModalComponent {
    _isopen = false;
    private _modalSize = 1; // 1:normal, 2: medium, 3: large, 4: extra large
    public get modalSize() {
        return this._modalSize;
    }

    @Input()
    public set modalSize(value) {
        this._modalSize = value;
    }

    get open(): boolean {
        return this._isopen;
    }

    @Input()
    set open(val: boolean) {
        this._isopen = val;
    }
    getModalDialogClass() {
        if (this.modalSize == null || this.modalSize <= 1 || this.modalSize > 4) {
            return 'modal-dialog modal-sm';
        } else if (this.modalSize <= 2) {
            return 'modal-dialog modal-md';
        } else if (this.modalSize <= 3) {
            return 'modal-dialog modal-lg';
        }  else if (this.modalSize <= 4) {
            return 'modal-dialog modal-xl';
        }
    }
}

shared modal html

                        <ng-content select=[header]></ng-content>

                        <ng-content select=[body]></ng-content>

                        <ng-content select=[footer]></ng-content>

Agreement  html

<shared-modal [modalSize]="4" [open]="agreementWindowOpened">

Agreement

                Hello World

</shared-modal>

Agreement component

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-agreement',
  templateUrl: './agreement.component.html',
  styleUrls: ['./agreement.component.scss']
})
export class AgreementComponent implements OnInit {

  agreementWindowOpened: boolean;

  constructor() { }

  ngOnInit() {
  }

 Load() {
    this.agreementWindowOpened = true;
  }

  dismissAgreementWindow() {
    this.agreementWindowOpened = false;
}
}

Service

@ViewChild(AgreementComponent, { static: false }) agreement: AgreementComponent;

    authCallback = (errorDesc: any, token: any, error: any, tokenType: any) => {

    if (this.userTryingToResetPassword(token, errorDesc)) {

      const passResetApplication = this.createUserAgentApplication(this.passwordResetAuthority);
      passResetApplication.loginRedirect(this.settings.aad.b2cScopes);
    }
    if (!errorDesc) {
      this.cacheUserPermissions();
      // Call the agreement dialog box here
      if (this.agreement) {
       this.agreement.Load();
      }
    }

  }


问:
Can't connect redux store to sematic ui dimmer components
I am using React with semantic-ui-react library. The problem is when i use semantic-ui Dimmer and try to connect a component inside it to redux i get the error: Uncaught Invariant Violation: Could not find "store" in the context of "Connect(myComp)".
I managed to get over this error by wrapping the inner component in Provider like this:

```<code>import { Dimmer } from 'semantic-ui-react'
import { Provider } from 'react-redux'
import store from '../storelocation/store'
import SubComp from './subComp'

class App extends React.Component{
    render(){
        return(
            <div>
                <Dimmer>
                    <Provider store={store}>
                        <SubComp/>
                    </Provider>
                </Dimmer>
            </div>
        )
    }
}
</code>```

Doing this, my SubComp is now able to connect(mstp,mdtp).

Such problem is not showing up in any other part of the app. I have wrapped my root component in Provider in my index.js like this:

```<code>ReactDom.render(
    <Provider store={store}>
        <App/>
    </Provider>, document.getElementById('root')
);
</code>```

Now since wrapping my SubComp in provider each time i use it, fades the smile from my face, i am looking for a better option and maybe a correction if i am doing something terribly wrong here. tnx.

答:
The problem here occurs because Semantic-UI-React uses React Portals for components like Modal, Confirm, Dimmer, Popup etc.

For more information about Portals and why this problem occurs, you may refer to this comment.

Unfortunately there seems to be no better way than wrapping your own components under Portal with a Provider via extracting store (as you have done) as of now.

Body:
I am using React with semantic-ui-react library. The problem is when i use semantic-ui Dimmer and try to connect a component inside it to redux i get the error: Uncaught Invariant Violation: Could not find "store" in the context of "Connect(myComp)".
I managed to get over this error by wrapping the inner component in Provider like this:

import { Dimmer } from 'semantic-ui-react'
import { Provider } from 'react-redux'
import store from '../storelocation/store'
import SubComp from './subComp'

class App extends React.Component{
    render(){
        return(

                <Dimmer>
                    <Provider store={store}>
                        <SubComp/>
                    </Provider>
                </Dimmer>

        )
    }
}

Doing this, my SubComp is now able to connect(mstp,mdtp).

Such problem is not showing up in any other part of the app. I have wrapped my root component in Provider in my index.js like this:

ReactDom.render(
    <Provider store={store}>
        <App/>
    </Provider>, document.getElementById('root')
);

Now since wrapping my SubComp in provider each time i use it, fades the smile from my face, i am looking for a better option and maybe a correction if i am doing something terribly wrong here. tnx.


问:
javascript while loop problem,break doesn't stop the loop
I built a simple number guessing game with javascript.
After the computer guess the correct answer it should break the loop.
What I am wondering is that even though I break the loop at Line 18
It still execute the code on Line 20(console.log(text)).
The funny thing is that after the break. Only console.log() get executed,L21 & L22 don't do anything,which they are supposed to be that way.
Can't really figure out why. I hope I make the question clear!

Executes last console.log() in repl example

But doesn't in the below snippet (the exact same code)..

let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (true){
  let text = `#${i}: computer guess ${guess}.`
  if (guess > answer){
    text += 'TOO BIG!'
    max = guess
  } else if (guess < answer){
    text += 'TOO Small!'
    min = guess
  } else{
    text += 'win!'
    break
  }
  console.log(text)
  guess = Math.floor((max + min) / 2)
  i++
}```

答:
My guess is that because the REPL tool tries to display a return value for the code you run, it's using the last value before the code exits, which is text += "win!". So it's not actually executing your console.log(text), it just looks like it is.

For example, if you change your code to the following, the REPL tool spits out a number (the value of i before the postfix). Because it's the last value it saw before the while loop exited.

REPL example showing a different "return" value, logging as expected

let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (guess !== answer){
  let text = `#${i}: computer guess ${guess}.`
  if (guess > answer){
    text += 'TOO BIG!'
    max = guess
  } else if (guess < answer){
    text += 'TOO Small!'
    min = guess
  }
  console.log(text)
  guess = Math.floor((max + min) / 2)
  i++
}

// console.log(`#${i}: computer guess ${guess}. Win!`);```

This is not normal JS behavior, and should be taken with a grain of salt when reading "return" values in the REPL tool.Hope this helps!

Body:
My guess is that because the REPL tool tries to display a return value for the code you run, it's using the last value before the code exits, which is text += "win!". So it's not actually executing your console.log(text), it just looks like it is.

For example, if you change your code to the following, the REPL tool spits out a number (the value of i before the postfix). Because it's the last value it saw before the while loop exited.

REPL example showing a different "return" value, logging as expected

let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (guess !== answer){
  let text = `#${i}: computer guess ${guess}.`
  if (guess > answer){
    text += 'TOO BIG!'
    max = guess
  } else if (guess < answer){
    text += 'TOO Small!'
    min = guess
  }
  console.log(text)
  guess = Math.floor((max + min) / 2)
  i++
}

// console.log(`#${i}: computer guess ${guess}. Win!`);

This is not normal JS behavior, and should be taken with a grain of salt when reading "return" values in the REPL tool.Hope this helps!


问:
Can't I use the mixins function of parent component in child component?
I am using the mixins function in the vuejs to code efficiently.
And then, I had a question.
I have imported mixins 'TTS' in the parent component.
And then the child component called the function of the tts.
However, the function was not called.
Is the parent component mixtns function not available in the child component?

```<code>import { tts } from "../components/mixins/tts/tts";

export default {
  mixins: [tts]
}
</code>```

This is importing mixins in the parent component.

```<code>    <ion-row
      class="drawer_middle_menu ion-align-items-center ion-justify-content-center"
      @click="trySpeak($t('timeOut'))"
    >{{$t('timeOut')}}</ion-row>
</code>```

And this is a child component.
The 'trySpeak' function is a function in TTS that was imported by the parent component.

答:
No, you would need to either pass as a prop or import directly into child component. With that said there are not recommended ways such as $parent but I would stay away from that.
See here for more info:
https://v2.vuejs.org/v2/guide/components-edge-cases.html

Body:
I am using the mixins function in the vuejs to code efficiently.
And then, I had a question.
I have imported mixins 'TTS' in the parent component.
And then the child component called the function of the tts.
However, the function was not called.
Is the parent component mixtns function not available in the child component?

import { tts } from "../components/mixins/tts/tts";

export default {
  mixins: [tts]
}

This is importing mixins in the parent component.

    <ion-row
      class="drawer_middle_menu ion-align-items-center ion-justify-content-center"
      @click="trySpeak($t('timeOut'))"
    >{{$t('timeOut')}}</ion-row>

And this is a child component.
The 'trySpeak' function is a function in TTS that was imported by the parent component.


问:
Adding function parameters using a single variable in jQuery
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

```<code>function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);
</code>```

Problem demo

Thanks in advance

答:
You can use function.apply(). Pass your list of parameters in as an array and you can even set a scope if you wish to do so:

```<code>function myFunc(a,b){
    alert(a+", "+b);
}

var args = ["one", "two"];
var func = myFunc;

$('button').click(function(){
    func.apply(this, args);
});
</code>```

Body:
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);

Problem demo

Thanks in advance

Body:
You can use function.apply(). Pass your list of parameters in as an array and you can even set a scope if you wish to do so:

function myFunc(a,b){
    alert(a+", "+b);
}

var args = ["one", "two"];
var func = myFunc;

$('button').click(function(){
    func.apply(this, args);
});


问:
Overriding Dart methods with Generics arguments
I have this case where I am extending from a super class with methods being typed using Generics as the following:

Models

abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}
```

<h2>Controllers</h2>

<pre class="lang-dart prettyprint-override"><code>abstract class A {
   T getDoc<T extends SuperClass>(T doc);
}

class B extends A {
   T getDoc<T extends SubClass>(T doc) {     //<================ Error
       //....
    }
}

</code>```

Basically class B will only deal with a SubClass model and any class that extends it. Extending SuperClass is not enough. It's a way to enforce the type usage. I could add a helper function that will check the type for each method within class B (doc is SubClass) but seems like a lot repetition.

But the above architecture fails when overriding the method getDoc in class B saying that it isn't a valid override although SubClass is a SuperClass. How can I achieve something like this? Or is there a better way of doing it? Appreciate any pointers :)

答:
You can not narrow the generic type argument. Class B guaranties (by extending class A), that it will/can handle all type arguments (and sub types!), that class A can handle. Consider the following situation:

```<code>class OtherSubClass extends SuperClass {
  //....
}

void main() {
  var b = B();
  b.getDoc(OtherSubClass());
}
</code>```

What would you expect to happen? Class B is not able to handle objects of type OtherSubClass, so it breaks the contract with class A.

Body:
I have this case where I am extending from a super class with methods being typed using Generics as the following:

Models

abstract class SuperClass {

   //.....
}

class SubClass extends SuperClass {
  int a;
  int b;
  String c;
  //....
}

Controllers

abstract class A {
   T getDoc<T extends SuperClass>(T doc);
}

class B extends A {
   T getDoc<T extends SubClass>(T doc) {     //<================ Error
       //....
    }
}

Basically class B will only deal with a SubClass model and any class that extends it. Extending SuperClass is not enough. It's a way to enforce the type usage. I could add a helper function that will check the type for each method within class B (doc is SubClass) but seems like a lot repetition.

But the above architecture fails when overriding the method getDoc in class B saying that it isn't a valid override although SubClass is a SuperClass. How can I achieve something like this? Or is there a better way of doing it? Appreciate any pointers :)

Body:
You can not narrow the generic type argument. Class B guaranties (by extending class A), that it will/can handle all type arguments (and sub types!), that class A can handle. Consider the following situation:

class OtherSubClass extends SuperClass {
  //....
}

void main() {
  var b = B();
  b.getDoc(OtherSubClass());
}

What would you expect to happen? Class B is not able to handle objects of type OtherSubClass, so it breaks the contract with class A.


问:
IsDigit() in c reading char as digit in C
I am trying to check if a char is upper case, lower case or a digit without using the library functions. I wrote my own functions but when I enter a character, my IsDigit() returns true and says that it is a digit rather than saying it is not. </p>

<p>I can't seem to find out where the bug is in my code. </p>

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

int isLower(char ch)
{
   if (ch >= 'a' && ch <= 'z')
   {
       return true;
   }
   else
   {
       return false;
   }
}
int isUpper(char ch)
{
    if(ch>='A' && ch<='Z')
    {
       return true;
    }
    else
    {
        return false;
    }
}
int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)
    {
        return true;
    }
    else{
        return false;
    }
}

int main() {
   char ch='L';

   if(isLower(ch))
   {
       printf("%c is lower case.\n", ch);
   }
   else
   {
        printf("%c is not lower case.\n",ch);
   }

   if(isUpper(ch))
   {
       printf("%c is upper case.\n",ch);
   }
   else{
        printf("%c is not upper case.\n", ch);
   }

   if(isDigit(ch))
   {
       printf("%c is a digit.\n",ch);
   }
   else{
       printf("%c is not a digit.\n",ch);
   }

   return (0);
  }
Output:
d is lower case.
d is not upper case.
d is a digit.
</code>```

答:
Kindly check,

The size of your used data type (e.g.: char - Sizeof char is 1 byte) and whether signed or unsigned data type.

return type of your function.

Reason for saying is,
In your code, two minor issues.

return type is int but you are returning either true/false. But it should be a value.

Size of char is 1 byte (0-255 bits). since you had declared char (signed by default), the bit range from (-128 - 0 - 127). but you are checking the value in if condition is 47876

```<code>int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)     // **Reason for checking the value upto 47876?**
    {
       return true;       // return value should be integer value.
    }
    return false;
}
</code>```

Body:
I am trying to check if a char is upper case, lower case or a digit without using the library functions. I wrote my own functions but when I enter a character, my IsDigit() returns true and says that it is a digit rather than saying it is not.

I can't seem to find out where the bug is in my code.

#include<stdio.h>
#include <stdbool.h>

int isLower(char ch)
{
   if (ch >= 'a' && ch <= 'z')
   {
       return true;
   }
   else
   {
       return false;
   }
}
int isUpper(char ch)
{
    if(ch>='A' && ch<='Z')
    {
       return true;
    }
    else
    {
        return false;
    }
}
int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)
    {
        return true;
    }
    else{
        return false;
    }
}

int main() {
   char ch='L';

   if(isLower(ch))
   {
       printf("%c is lower case.\n", ch);
   }
   else
   {
        printf("%c is not lower case.\n",ch);
   }

   if(isUpper(ch))
   {
       printf("%c is upper case.\n",ch);
   }
   else{
        printf("%c is not upper case.\n", ch);
   }

   if(isDigit(ch))
   {
       printf("%c is a digit.\n",ch);
   }
   else{
       printf("%c is not a digit.\n",ch);
   }

   return (0);
  }
Output:
d is lower case.
d is not upper case.
d is a digit.

Body:
Kindly check,

The size of your used data type (e.g.: char - Sizeof char is 1 byte) and whether signed or unsigned data type.

return type of your function.

Reason for saying is,
In your code, two minor issues.

return type is int but you are returning either true/false. But it should be a value.

Size of char is 1 byte (0-255 bits). since you had declared char (signed by default), the bit range from (-128 - 0 - 127). but you are checking the value in if condition is 47876

int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)     // **Reason for checking the value upto 47876?**
    {
       return true;       // return value should be integer value.
    }
    return false;
}


问:
Access element from external XML file in Android
I am developing an Android Application.I have create an another XML file for layout:-

Chatfile.XML

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/suitableblack"
    android:orientation="vertical">

    <Button
    android:id="@+id/signout"
    android:layout_width="422dp"
    android:layout_height="64dp"
    android:text="Button" />

<ListView
    android:id="@+id/Msgdisplay"
    android:layout_width="374dp"
    android:layout_height="593dp"
    android:layout_below="@id/signout"
    android:layout_marginLeft="20dp"
    android:forceDarkAllowed="false" />

<LinearLayout
    android:layout_width="390dp"
    android:layout_height="83dp"
    android:layout_below="@id/Msgdisplay"
    android:layout_marginLeft="20dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/Msginput"
        android:layout_width="482dp"
        android:layout_height="67dp"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <Button
        android:id="@+id/Sendbtn"
        android:layout_width="match_parent"
        android:layout_height="68dp"
        android:layout_weight="1"
        android:text="Button" />
</LinearLayout>
</code>```

So I want to access the button with ID-Sendbtn in  my MainActivity.java file and the code for that part is here:-

```<code>    Button sendbtn=findViewById(R.id.Sendbtn);
    sendbtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          String msg=message.getText().toString();
          if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
            FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
        }

    }
  });
</code>```

But whenever I run this code it gives me following error:-

```<code> Process: com.example.anochatzone, PID: 18398
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anochatzone/com.example.anochatzone.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.anochatzone.MainActivity.onCreate(MainActivity.java:87)
    at android.app.Activity.performCreate(Activity.java:6679)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

My main question is how can I access the button from chatfile.xml in my MainActivity.java

Update
MainActivity.java

```<code>  package com.example.anochatzone;

    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.text.Layout;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.*;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.database.FirebaseDatabase;

    import java.util.Objects;

    public class MainActivity extends AppCompatActivity {
    private FirebaseAuth authenticate;
        private String email_str="";
     private String password_str="";
    private EditText email,password,message;
    private Button loginbtn,resetbtn,sendbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
            Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title bar
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
            setContentView(R.layout.activity_main);
           email=findViewById(R.id.EmailInput);
           password=findViewById(R.id.Passwordinput);
           message=findViewById(R.id.Msginput);

    loginbtn=findViewById(R.id.Loginbtn);
           resetbtn= findViewById(R.id.ResetBtn);
       sendbtn=findViewById(R.id.Sendbtn);

        authenticate=FirebaseAuth.getInstance();

       loginbtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
     Toast.makeText(getApplicationContext(),"Please wait while we are processing your request........",Toast.LENGTH_SHORT).show();
                email_str=email.getText().toString();
                password_str=password.getText().toString();
            if(email_str.length()==0||password_str.length()==0)
            {
                Toast.makeText(getBaseContext(),"Please check email and password",Toast.LENGTH_LONG).show();
            }
            else
            {
                authenticate.signInWithEmailAndPassword(email_str,password_str).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                       if(task.isSuccessful()){
    Log.d("User display name" , FirebaseAuth . getInstance() . getCurrentUser().getDisplayName());
                         Toast.makeText(getApplicationContext(),"Welcome "+email_str+" you have sucessfully logged in",Toast.LENGTH_LONG).show();
                         setContentView(R.layout.chatfile);

                       }
                       else
                       {
                           Toast.makeText(getApplicationContext(),"Failed to sign in .Please check internet connection or try again later",Toast.LENGTH_SHORT).show();
                       }

                    }
                });
            }
           }
       });

    sendbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String msg=message.getText().toString();
        if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
             FirebaseDatabase.getInstance().getReference().push().setValue(new        chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()))    ;
        }
    }
    });
    }
}
</code>```

答:
According to your purpose, when you launch or start the app, login page will appear. If login success, the chat page will appear.

So, you need to separate your activity to two activity such as LoginActivity as a launcher activity and ChatActivity(MainActivity) as follow.

For login page, may be one activity_login.xml and LoginActivity.java

In activity_login.xml

```<code>   <!-- You need one button for login action. -->
   <Button
      android:id="@+id/btnLogin"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:text="Login"
      />
</code>```

In LoginActivity.java

```<code>@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This line is important to access your resource id
    setContentView(R.layout.activity_login);

    findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        // isLoginSuccess is an example condition for you
        if (isLoginSuccess) {
          // Navigate to mainpage
          startActivity(new Intent(LoginActivity.this, MainActivity.class));

          // Terminate the login activity for one time show.
          finish();
        } else {
          // TODO: Try again implementations
        }
      }
    });
  }
</code>```

For main page, like above, you need one activity_main.xml and one MainActivity.java

In Chatfile.xml

```<code>      // other codes....
      <Button
        android:id="@+id/Sendbtn"
        android:layout_width="match_parent"
        android:layout_height="68dp"
        android:layout_weight="1"
        android:text="Button" />
      // other codes....
</code>```

In MainActivity.java

```<code>@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // This line is important for your 'chatfile.xml'
    setContentView(R.layout.Chatfile);

    // You can access id `SendBtn` right now.
    findViewById(R.id.SendBtn).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
          // TODO: implement something here.
      }
    });
  }
</code>```

In AndroidManifest.xml, you need to change launcher activity as LoginActivity.

```<code><application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
    <activity android:name=".LoginActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"/>
  </application>
</code>```

According to my solution, you don't have to consider that what the ui element should be hidden when login success or fail.

If anything wrong in my answer, please let me free to know.

Body:
I am developing an Android Application.I have create an another XML file for layout:-

Chatfile.XML

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/suitableblack"
    android:orientation="vertical">

    <Button
    android:id="@+id/signout"
    android:layout_width="422dp"
    android:layout_height="64dp"
    android:text="Button" />

<ListView
    android:id="@+id/Msgdisplay"
    android:layout_width="374dp"
    android:layout_height="593dp"
    android:layout_below="@id/signout"
    android:layout_marginLeft="20dp"
    android:forceDarkAllowed="false" />

<LinearLayout
    android:layout_width="390dp"
    android:layout_height="83dp"
    android:layout_below="@id/Msgdisplay"
    android:layout_marginLeft="20dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/Msginput"
        android:layout_width="482dp"
        android:layout_height="67dp"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name" />

    <Button
        android:id="@+id/Sendbtn"
        android:layout_width="match_parent"
        android:layout_height="68dp"
        android:layout_weight="1"
        android:text="Button" />
</LinearLayout>

So I want to access the button with ID-Sendbtn in  my MainActivity.java file and the code for that part is here:-

    Button sendbtn=findViewById(R.id.Sendbtn);
    sendbtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          String msg=message.getText().toString();
          if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
            FirebaseDatabase.getInstance().getReference().push().setValue(new chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
        }

    }
  });

But whenever I run this code it gives me following error:-

 Process: com.example.anochatzone, PID: 18398
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anochatzone/com.example.anochatzone.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.example.anochatzone.MainActivity.onCreate(MainActivity.java:87)
    at android.app.Activity.performCreate(Activity.java:6679)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

My main question is how can I access the button from chatfile.xml in my MainActivity.java

Update
MainActivity.java

  package com.example.anochatzone;

    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.text.Layout;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.*;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.AuthResult;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.database.FirebaseDatabase;

    import java.util.Objects;

    public class MainActivity extends AppCompatActivity {
    private FirebaseAuth authenticate;
        private String email_str="";
     private String password_str="";
    private EditText email,password,message;
    private Button loginbtn,resetbtn,sendbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
            Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title bar
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
            setContentView(R.layout.activity_main);
           email=findViewById(R.id.EmailInput);
           password=findViewById(R.id.Passwordinput);
           message=findViewById(R.id.Msginput);

    loginbtn=findViewById(R.id.Loginbtn);
           resetbtn= findViewById(R.id.ResetBtn);
       sendbtn=findViewById(R.id.Sendbtn);

        authenticate=FirebaseAuth.getInstance();

       loginbtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
     Toast.makeText(getApplicationContext(),"Please wait while we are processing your request........",Toast.LENGTH_SHORT).show();
                email_str=email.getText().toString();
                password_str=password.getText().toString();
            if(email_str.length()==0||password_str.length()==0)
            {
                Toast.makeText(getBaseContext(),"Please check email and password",Toast.LENGTH_LONG).show();
            }
            else
            {
                authenticate.signInWithEmailAndPassword(email_str,password_str).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                       if(task.isSuccessful()){
    Log.d("User display name" , FirebaseAuth . getInstance() . getCurrentUser().getDisplayName());
                         Toast.makeText(getApplicationContext(),"Welcome "+email_str+" you have sucessfully logged in",Toast.LENGTH_LONG).show();
                         setContentView(R.layout.chatfile);

                       }
                       else
                       {
                           Toast.makeText(getApplicationContext(),"Failed to sign in .Please check internet connection or try again later",Toast.LENGTH_SHORT).show();
                       }

                    }
                });
            }
           }
       });

    sendbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String msg=message.getText().toString();
        if(msg.length()==0)
        {
            Toast.makeText(getApplicationContext(),"Blank message detected",Toast.LENGTH_SHORT);
        }
        else
        {
             FirebaseDatabase.getInstance().getReference().push().setValue(new        chatcolumns(msg,FirebaseAuth.getInstance().getCurrentUser().getDisplayName()))    ;
        }
    }
    });
    }
}

Body:
According to your purpose, when you launch or start the app, login page will appear. If login success, the chat page will appear.

So, you need to separate your activity to two activity such as LoginActivity as a launcher activity and ChatActivity(MainActivity) as follow.

For login page, may be one activity_login.xml and LoginActivity.java

In activity_login.xml

   <!-- You need one button for login action. -->
   <Button
      android:id="@+id/btnLogin"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:text="Login"
      />

In LoginActivity.java

@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // This line is important to access your resource id
    setContentView(R.layout.activity_login);

    findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        // isLoginSuccess is an example condition for you
        if (isLoginSuccess) {
          // Navigate to mainpage
          startActivity(new Intent(LoginActivity.this, MainActivity.class));

          // Terminate the login activity for one time show.
          finish();
        } else {
          // TODO: Try again implementations
        }
      }
    });
  }

For main page, like above, you need one activity_main.xml and one MainActivity.java

In Chatfile.xml

      // other codes....
      <Button
        android:id="@+id/Sendbtn"
        android:layout_width="match_parent"
        android:layout_height="68dp"
        android:layout_weight="1"
        android:text="Button" />
      // other codes....

In MainActivity.java

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // This line is important for your 'chatfile.xml'
    setContentView(R.layout.Chatfile);

    // You can access id `SendBtn` right now.
    findViewById(R.id.SendBtn).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
          // TODO: implement something here.
      }
    });
  }

In AndroidManifest.xml, you need to change launcher activity as LoginActivity.

<application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
    <activity android:name=".LoginActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"/>
  </application>

According to my solution, you don't have to consider that what the ui element should be hidden when login success or fail.

If anything wrong in my answer, please let me free to know.


问:
Android Studio keeps importing import sun.jvm.hotspot.utilities.IntArray
Every time I copy a piece of code in Java and paste it in my android studio, and it converts this code to Kotlin code, it keeps automatically importing this:

```<code>import sun.jvm.hotspot.utilities.IntArray
</code>```

And every time android studio makes this import, it gives an error Unresolved reference: sun.

Does anyone know how to fix this?...it is very annoying.

答:
To Disable Auto Imports:

File --> Settings ---> Editor --> General --> Auto Import --> Optimize imports on
  the fly.

If Optimize imports on the fly is checked then uncheck it.

Body:
Every time I copy a piece of code in Java and paste it in my android studio, and it converts this code to Kotlin code, it keeps automatically importing this:

import sun.jvm.hotspot.utilities.IntArray

And every time android studio makes this import, it gives an error Unresolved reference: sun.

Does anyone know how to fix this?...it is very annoying.


问:
Adding 12 months to February 29
I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

```<code>$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));
</code>```

Output:

```<code>03/01/2021
</code>```

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.

答:
```<code>$startdate = '02/29/2020';
$date = date('m/d/Y', strtotime($startdate . '+365 days'));
</code>```

Title: Adding 12 months to February 29

Body:
I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));

Output:

03/01/2021

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.


问:
Adding submodule to non empty path with JGit
I am trying to add a submodule to a non empty folder using the JGit API class SubmoduleAddCommand and this is my code:

SubmoduleAddCommand submoduleAddCommand = new SubmoduleAddCommand(repository);
submoduleAddCommand.setPath(path);
submoduleAddCommand.setName(name);
submoduleAddCommand.setURI(uri);
submoduleAddCommand.call().close();
repository.close();
```

Destination folder contains: Folder1, Folder2, ... and so on, and none of the previous folders is a submodule however they must not be removed. My target is to add the submodule and clone it to the Destination folder alongside the non-submodule folders. This results in an exception being thrown:

org.eclipse.jgit.api.errors.JGitInternalException: Destination path "Target_Submodule" already exists and is not an empty directory

and the submodule is neither added to the .gitmodules file nor cloned into the Destination folder.

Is there a way to add this submodule to the non-empty Destination folder and the .gitmodules file?

答:
Git does not allow to add a submodule into a non-empty directory.

The SubmoduleAddCommand will clone and checkout the specified repository into the destination path. And cloning a repository requires the destination path to be empty.

Cloning into a non-empty directory could lead to all sorts of trouble if there exist files in the destination directory that also need to be created while adding the module.

Body:
I am trying to add a submodule to a non empty folder using the JGit API class SubmoduleAddCommand and this is my code:

SubmoduleAddCommand submoduleAddCommand = new SubmoduleAddCommand(repository);
submoduleAddCommand.setPath(path);
submoduleAddCommand.setName(name);
submoduleAddCommand.setURI(uri);
submoduleAddCommand.call().close();
repository.close();

Destination folder contains: Folder1, Folder2, ... and so on, and none of the previous folders is a submodule however they must not be removed. My target is to add the submodule and clone it to the Destination folder alongside the non-submodule folders. This results in an exception being thrown:

org.eclipse.jgit.api.errors.JGitInternalException: Destination path "Target_Submodule" already exists and is not an empty directory

and the submodule is neither added to the .gitmodules file nor cloned into the Destination folder.

Is there a way to add this submodule to the non-empty Destination folder and the .gitmodules file?


问:
What's the Nodejs backend routine for "Register / Signin with Google"?
I'm using a Express Nodejs backend + React frontend set up and tried to implement a "Register / Signin with Google" function, but I do not understand what to store in the database after the user is authenticated. In the ordinary register with email approach, I send the email + password to the backend when I register and check if both the email & password match when the user login.

However, I don't know what to store in the db if one is registered with Google. I have already implement part of the google auth with google by following this tutorial in the frontend side, here's my code:

```<code>import * as queryString from 'query-string';

const stringifiedParams = queryString.stringify({
  client_id: 'MY_CLIENT_ID'
  redirect_uri: 'http://localhost:8000/protected_home',
  scope: [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
  ].join(' '), // space seperated string
  response_type: 'code',
  access_type: 'offline',
  prompt: 'consent'
});

const googleLoginUrl = `https://accounts.google.com/o/oauth2/v2/auth?${stringifiedParams}`;

return (
  <a href={googleLoginUrl}>Login with Google</a>
)
</code>```

But then what's next? I've successfully pass through the auth process and redirected back to the protected_home page. But this only means that this user is a google user, what kind of information should I store their information in backend so that it indicated that the user has registered an account in my backend with this google account?

Also, is is possible to move the logic above to backend? Since google will redirect back to my redirect_urilike this http://localhost:8000/protected_home?code=CODE_IS_HERE, I need to browser to extract the information in CODE_IS_HERE. So it seems impossible to move the login logic to backend, any solution?

答:
What you need to save is user's unique id, his email or phone, and some other user data for your project.
This is just to know if the user already registered or to know the current user in backend.

From backend, you can just set a middleware to verify the token assigned from google.
Then you will get the user's id and you can find a user from your database, if exists, the user is authenticated.

Signin with google.

Get redirected with CODE

Send CODE to backend

Backend will get user id and email with the CODE using google api.

Save user and generate token.

Send the token back to your frontend.

Then the login or signup process is finished.

Body:
I'm using a Express Nodejs backend + React frontend set up and tried to implement a "Register / Signin with Google" function, but I do not understand what to store in the database after the user is authenticated. In the ordinary register with email approach, I send the email + password to the backend when I register and check if both the email & password match when the user login.

However, I don't know what to store in the db if one is registered with Google. I have already implement part of the google auth with google by following this tutorial in the frontend side, here's my code:

import * as queryString from 'query-string';

const stringifiedParams = queryString.stringify({
  client_id: 'MY_CLIENT_ID'
  redirect_uri: 'http://localhost:8000/protected_home',
  scope: [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
  ].join(' '), // space seperated string
  response_type: 'code',
  access_type: 'offline',
  prompt: 'consent'
});

const googleLoginUrl = `https://accounts.google.com/o/oauth2/v2/auth?${stringifiedParams}`;

return (
  Login with Google
)

But then what's next? I've successfully pass through the auth process and redirected back to the protected_home page. But this only means that this user is a google user, what kind of information should I store their information in backend so that it indicated that the user has registered an account in my backend with this google account?

Also, is is possible to move the logic above to backend? Since google will redirect back to my redirect_urilike this http://localhost:8000/protected_home?code=CODE_IS_HERE, I need to browser to extract the information in CODE_IS_HERE. So it seems impossible to move the login logic to backend, any solution?