问:
Dart: PointyCastle compute asynchronous
currently I'm trying to send credential Data to my Backend, therefore I want to hash the password for security purposes.

But when I use the method PassCrypt().hashPass("", passwd, 48), the complete App freezes for nearly 1-2 seconds. Is there a way to await the input asynchronously?

Thanks :)

答:
You can copy paste run full code below

You can use compute and get result with then

In demo, you can see Floating action button is not blocked

code snippet

```<code>Future<String> hashJob(String password) async {
      return compute(hashPassword, password);
    }

String hashPassword(String password) {
      return PassCrypt().hashPass("", password, 48);
    }

hashJob("password test").then((value) {
          hashedPassword = value;
          print(hashedPassword);
        });
</code>```

working demo

output

```<code>I/flutter ( 9820): 2020-02-20 09:06:53.904373
I/flutter ( 9820): 2020-02-20 09:06:54.559547
I/flutter ( 9820): 2020-02-20 09:06:54.560054
I/flutter ( 9820): J434csHIYPm0NfSJJolyuq6ykTF+x3sswIi/x9ayMAxTTE63fG63BndBCafIgN6w
I/flutter ( 9820): J434csHIYPm0NfSJJolyuq6ykTF+x3sswIi/x9ayMAxTTE63fG63BndBCafIgN6w
I/flutter ( 9820): J434csHIYPm0NfSJJolyuq6ykTF+x3sswIi/x9ayMAxTTE63fG63BndBCafIgN6w
</code>```

full code

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

void main() => runApp(MyApp());

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

Future<String> hashJob(String password) async {
  return compute(hashPassword, password);
}

String hashPassword(String password) {
  return PassCrypt().hashPass("", password, 48);
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String hashedPassword;

  void _incrementCounter() {
    /*print(DateTime.now());
    var passHash = PassCrypt().hashPass("", "password test", 48);
    print(DateTime.now());
    print(passHash);*/

    print(DateTime.now());
    hashJob("password test").then((value) {
      hashedPassword = value;
      print(hashedPassword);
    });

    print(DateTime.now());
    setState(() {
      _counter++;
    });
  }

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

Title: Dart: PointyCastle compute asynchronous

Body:
You can copy paste run full code below

You can use compute and get result with then

In demo, you can see Floating action button is not blocked

code snippet

Future<String> hashJob(String password) async {
      return compute(hashPassword, password);
    }

String hashPassword(String password) {
      return PassCrypt().hashPass("", password, 48);
    }

hashJob("password test").then((value) {
          hashedPassword = value;
          print(hashedPassword);
        });

working demo

output

I/flutter ( 9820): 2020-02-20 09:06:53.904373
I/flutter ( 9820): 2020-02-20 09:06:54.559547
I/flutter ( 9820): 2020-02-20 09:06:54.560054
I/flutter ( 9820): J434csHIYPm0NfSJJolyuq6ykTF+x3sswIi/x9ayMAxTTE63fG63BndBCafIgN6w
I/flutter ( 9820): J434csHIYPm0NfSJJolyuq6ykTF+x3sswIi/x9ayMAxTTE63fG63BndBCafIgN6w
I/flutter ( 9820): J434csHIYPm0NfSJJolyuq6ykTF+x3sswIi/x9ayMAxTTE63fG63BndBCafIgN6w

full code

import 'package:flutter/material.dart';
import 'package:steel_crypt/steel_crypt.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';

void main() => runApp(MyApp());

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

Future<String> hashJob(String password) async {
  return compute(hashPassword, password);
}

String hashPassword(String password) {
  return PassCrypt().hashPass("", password, 48);
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String hashedPassword;

  void _incrementCounter() {
    /*print(DateTime.now());
    var passHash = PassCrypt().hashPass("", "password test", 48);
    print(DateTime.now());
    print(passHash);*/

    print(DateTime.now());
    hashJob("password test").then((value) {
      hashedPassword = value;
      print(hashedPassword);
    });

    print(DateTime.now());
    setState(() {
      _counter++;
    });
  }

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


来源: stackexchange

问:
How to move view for value in UISlider in Swift?
I have a UISlider with 50 values. How to move different UIView, when value in slider changes?

I've tried this:

```<code>if oldValue < Int(sender.value) {
        viewToMove.center.y = viewToMove.center.y - heightOfDay
        print(viewToMove.center.y)
        oldValue = Int(sender.value)
         print(oldValue)
    } else if oldValue > Int(sender.value) {
        viewToMove.center.y = viewToMove.center.y + heightOfDay
        print(viewToMove.center.y)
        oldValue = Int(sender.value)
        print(oldValue)
    }
</code>```

Slider's value changing but viewToMove.center.y isn't.

答:
The most probably is the viewToMove layout added with auto layout.
If so, then you need to update the constant of the NSLayoutConstraint which holds the centerY position of the viewToMove

ContentLicense: CC BY-SA 4.0

Body:
I have a UISlider with 50 values. How to move different UIView, when value in slider changes?

I've tried this:

if oldValue < Int(sender.value) {
        viewToMove.center.y = viewToMove.center.y - heightOfDay
        print(viewToMove.center.y)
        oldValue = Int(sender.value)
         print(oldValue)
    } else if oldValue > Int(sender.value) {
        viewToMove.center.y = viewToMove.center.y + heightOfDay
        print(viewToMove.center.y)
        oldValue = Int(sender.value)
        print(oldValue)
    }

Slider's value changing but viewToMove.center.y isn't.


问:
2D ArrayList In Java find object in column
I have 2D ArrayList and I want to find the index of a String located in the 1st Column.

arraylist.get(0).indexOf("My String") returns the index of a string located at first row.
But I want something like this

```<code>arraylist.indexOf("MyString").get(0)
</code>```

答:
If I understood you correct, you want to find the row, in which a column has a given value.

One thing you could do is to transpose the complete table, meaning rows become columns and columns become rows. Then you could access everything with standard Java functionality. But that's probably overkill and would assume that each row has the same amount of columns.

Instead I would recommend to just search for it like so:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JustADemo {

    public static void main(String[] args) {
        final List<List<String>> table = new ArrayList<>();
        table.add(Arrays.asList("R1 C1", "R1 C2", "R1 C3"));
        table.add(Arrays.asList("R2 C1", "R2 C2", "R2 C3"));
        table.add(Arrays.asList("R3 C1", "R3 C2", "R3 C3"));
        int i = findRowWhereColumnEquals(table, "R3 C2");
        if (i != -1) {
            System.out.println("R3 C2 can be found in row " + i + ".");
        } else {
            System.out.println("R3 C2 cound not be found.");
        }
    }

    private static int findRowWhereColumnEquals(List<List<String>> table, String value) {
        int i = 0;
        for (List<String> row : table) {
            if (row.contains(value)) {
                return i;
            }
            i++;
        }
        return -1;
    }
}
```

Body:
I have 2D ArrayList and I want to find the index of a String located in the 1st Column.

arraylist.get(0).indexOf("My String") returns the index of a string located at first row.
But I want something like this

arraylist.indexOf("MyString").get(0)


问:
Set up Azure Pipeline for Test Automation Framework
I need assistance in running my test scripts built-in Java platform with selenium webdriver using Eclipse IDE for my repo and used git to push my repo to Azure DevOps. The project is set up in Maven. How do I run my test scripts using pipelines in Azure DevOps?  </p>

答:
Not sure get more details from you. So here just share my suggestion on how to run Selenium tests in the release pipeline for Java application.

In my scenario, I deploy my Java application to azure web app service then run it. If you don't want, you can also deploy to local tomcat by using this extension.

1) After the Java application build, copy the project to the artifact of the release during Build pipeline via copy files and publish artifact task.

2) Create release pipeline, then add Azure app service task to deploy my Java application to azure.

3) Add a Maven task to the release pipeline, configure the task to make it point to pom.xml file which located in artifact.

4) Trigger the Selenium tests in pom.xml.

Now you can run browser to view the test.

You can check this lab blog to get more details. Just focus on the design logic of pipeline execution, because the sample in that blog is running with vstest.exe.


问:
Getting the entire List of Stock Symbols that the getSymbols function will contain
```<code>library(quantmod)
</code>```

For example:

```<code>> getSymbols("BRK.B",from="2010-01-01",to="2020-02-17")
</code>```

will give me an error:

```<code>Warning: BRK.B download failed; trying again.
Error in getSymbols.yahoo(Symbols = "BRK.B", env = <environment>, verbose = FALSE,  :
  Unable to import “BRK.B”.
BRK.B download failed after two attempts. Error message:
HTTP error 404.
</code>```

I don't know why it doesn't contain Berkshire Hathaway.

But my question is, where can I get the complete list of stock symbols that the function, getSymbols, will return data for for the past 5 years or so?

答:
getSymbols doesn't contain any symbols. You need to specify which symbols you want. And the return will be dependent on the source you choose. Default is yahoo. But there are a few others, like tiingo, alphavantage, bloomberg, etc., but need api's to connect to.

In case of BRK B, you made a typo, it should be BRK-B, not BRK.B (at least for the yahoo source).

```<code>getSymbols("BRK-B",from="2010-01-01",to="2020-02-17")
</code>```

Body:
library(quantmod)

For example:

> getSymbols("BRK.B",from="2010-01-01",to="2020-02-17")

will give me an error:

Warning: BRK.B download failed; trying again.
Error in getSymbols.yahoo(Symbols = "BRK.B", env = <environment>, verbose = FALSE,  :
  Unable to import “BRK.B”.
BRK.B download failed after two attempts. Error message:
HTTP error 404.

I don't know why it doesn't contain Berkshire Hathaway.

But my question is, where can I get the complete list of stock symbols that the function, getSymbols, will return data for for the past 5 years or so?

Body:
getSymbols doesn't contain any symbols. You need to specify which symbols you want. And the return will be dependent on the source you choose. Default is yahoo. But there are a few others, like tiingo, alphavantage, bloomberg, etc., but need api's to connect to.

In case of BRK B, you made a typo, it should be BRK-B, not BRK.B (at least for the yahoo source).

getSymbols("BRK-B",from="2010-01-01",to="2020-02-17")


问:
How to get display this javascript returned value in html input field?
I want the result of JavaScript in my input field so that it will push the value to my server while clicking submit.

In this code I am able to get the Javascript result in HTML but I don't know how to display it in the input field.

My code is below. It will return the local LAN IP.

I am creating this page to fetch the local IPs from our office pc. Now the IP is displayed in the web page but I want it to be displayed in input box so that when user clicks on submit, the result is pushed to the server / database.

This when used in HTML body will display in  web page. This class='ipAdd' should be displayed in input field by setting its value.

$(document).ready(function ubsrt() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new RTCPeerConnection({
      iceServers: []
    }),
    noop = function() {};

  pc.createDataChannel("");
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return;

    var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

    console.log('my IP: ', myIP);
    $('.ipAdd').text(myIP);

    pc.onicecandidate = noop;

  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="formGroup">
  <label for="address">IP Address</label> <br>
  <input type="text" class="one" id="address" name="address" size="50px" id="" Value="id=" list "">
</div>

<h3 class='ipAdd'>
  <h3></code>```

答:
If you want to display write something to a textbox, you can use jQuery's .val() function to set the value of the textbox. In your case, you can use the ID of the textbox to identify it. Therefore

```<code>$('#address').val(myIP);
</code>```

will work.

Run this demo to see it:

$(document).ready(function ubsrt() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new RTCPeerConnection({
      iceServers: []
    }),
    noop = function() {};

  pc.createDataChannel("");
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return;

    var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

    console.log('my IP: ', myIP);
    $('#address').val(myIP);
    $('.ipAdd').text(myIP);

    pc.onicecandidate = noop;

  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="formGroup">
  <label for="address">IP Address</label> <br>
  <input type="text" class="one" id="address" name="address" size="50px" id="" Value="id=" list "">
</div>

<h3 class='ipAdd'></h3></code>```

(N.B. Friendly hint: The above is some of the most basic jQuery syntax. If you're unsure about this kind of thing then it might be time to improve your jQuery skills by studying some tutorials etc.

Body:
I want the result of JavaScript in my input field so that it will push the value to my server while clicking submit.

In this code I am able to get the Javascript result in HTML but I don't know how to display it in the input field.

My code is below. It will return the local LAN IP.

I am creating this page to fetch the local IPs from our office pc. Now the IP is displayed in the web page but I want it to be displayed in input box so that when user clicks on submit, the result is pushed to the server / database.

This when used in HTML body will display in  web page. This class='ipAdd' should be displayed in input field by setting its value.

$(document).ready(function ubsrt() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new RTCPeerConnection({
      iceServers: []
    }),
    noop = function() {};

  pc.createDataChannel("");
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return;

    var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

    console.log('my IP: ', myIP);
    $('.ipAdd').text(myIP);

    pc.onicecandidate = noop;

  };
});

  IP Address

  <input type="text" class="one" id="address" name="address" size="50px" id="" Value="id=" list "">

Body:
If you want to display write something to a textbox, you can use jQuery's .val() function to set the value of the textbox. In your case, you can use the ID of the textbox to identify it. Therefore

$('#address').val(myIP);

will work.

Run this demo to see it:

$(document).ready(function ubsrt() {
  window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new RTCPeerConnection({
      iceServers: []
    }),
    noop = function() {};

  pc.createDataChannel("");
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate) return;

    var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];

    console.log('my IP: ', myIP);
    $('#address').val(myIP);
    $('.ipAdd').text(myIP);

    pc.onicecandidate = noop;

  };
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="formGroup">
  <label for="address">IP Address</label> <br>
  <input type="text" class="one" id="address" name="address" size="50px" id="" Value="id=" list "">
</div>

<h3 class='ipAdd'></h3>

(N.B. Friendly hint: The above is some of the most basic jQuery syntax. If you're unsure about this kind of thing then it might be time to improve your jQuery skills by studying some tutorials etc.


问:
Run batch script in windows scheduler with jar
I am running the batch file from windows scheduler , when I execute batch file directly it works, but when added in scheduler , it is not running.
 Run.bat contains

```<code>java -cp D:\Test_Automation\LocalExecutable\TestAutomation-1.0-fat-tests.jar my.com.testauto.TestRunner
</code>```

Should I set anything in batch file.

答:
Just to clarify, Scheduled tasks are not visible to the user, if you were expecting something to happen on screen, then that is one of the reasons you might think it did not happen. I am not able to see what your Java program is built to do. If however it is a path issue, there are manual ways and automated ways. here are some examples.

Either put the full path of the java instance into the batch file.

```<code>c:\apps\jdk\bin\java.exe -cp D:\Test_Automation\LocalExecutable\TestAutomation-1.0-fat-tests.jar my.com.testauto.TestRunner
</code>```

or if you are unsure of the location of java, run a loop to find it for you.

```<code>for /f "delims=" %%a in ('where /r c:\ java.exe') do set "fnd=%%~a" & goto init
:init
"%fnd" -cp D:\Test_Automation\LocalExecutable\TestAutomation-1.0-fat-tests.jar my.com.testauto.TestRunner
</code>```

Body:
I am running the batch file from windows scheduler , when I execute batch file directly it works, but when added in scheduler , it is not running.
 Run.bat contains

java -cp D:\Test_Automation\LocalExecutable\TestAutomation-1.0-fat-tests.jar my.com.testauto.TestRunner

Should I set anything in batch file.

Body:
Just to clarify, Scheduled tasks are not visible to the user, if you were expecting something to happen on screen, then that is one of the reasons you might think it did not happen. I am not able to see what your Java program is built to do. If however it is a path issue, there are manual ways and automated ways. here are some examples.

Either put the full path of the java instance into the batch file.

c:\apps\jdk\bin\java.exe -cp D:\Test_Automation\LocalExecutable\TestAutomation-1.0-fat-tests.jar my.com.testauto.TestRunner

or if you are unsure of the location of java, run a loop to find it for you.

for /f "delims=" %%a in ('where /r c:\ java.exe') do set "fnd=%%~a" & goto init
:init
"%fnd" -cp D:\Test_Automation\LocalExecutable\TestAutomation-1.0-fat-tests.jar my.com.testauto.TestRunner


问:
Is there a way to color boxplots based on group in hcboxplot()?
I am trying to make boxplots using highcharter in R that all have distinct colors based on their group. I cannot figure out how to make all the boxes have distinct colors. What should I do to resolve this?</p>

```<code>library(highcharter)
library(viridisLite)
library(dplyr)
hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>%
  hc_chart(type = "column") %>%
  hc_colors(viridis(15))
</code>```

答:
It works by setting hc_plotOptions(series=list(colorByPoint=TRUE)):

```<code>library(viridisLite)
library(dplyr)
library(ggplot2)

hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>%
  hc_chart(type = "column") %>%
  hc_colors(viridis(15)) %>%
  hc_plotOptions(series=list(colorByPoint=TRUE))
</code>```

Body:
I am trying to make boxplots using highcharter in R that all have distinct colors based on their group. I cannot figure out how to make all the boxes have distinct colors. What should I do to resolve this?

library(highcharter)
library(viridisLite)
library(dplyr)
hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>%
  hc_chart(type = "column") %>%
  hc_colors(viridis(15))

Body:
It works by setting hc_plotOptions(series=list(colorByPoint=TRUE)):

library(viridisLite)
library(dplyr)
library(ggplot2)

hcboxplot(x = mpg$cty, var = mpg$manufacturer, outliers = FALSE) %>%
  hc_chart(type = "column") %>%
  hc_colors(viridis(15)) %>%
  hc_plotOptions(series=list(colorByPoint=TRUE))


问:
django-rest-auth handling expired confirmation email
I am using django-rest-auth and django-allauth to handle user authentication in my rest api. When a user tries to verify their email after the link has expired, I get an unpleasant error page.

Please, how can I display a better error page or send a message telling them it wasn't successful because the link had expired?

答:
As far as I can understand, your error is coming from django-allauth, not from your project. Reason for the error is that you did not include allauth.url in your main urls.py(will explain more in later section).

Possible solutions

First Solution

Add allauth.urls in your urls.py:

```<code>urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),
    ...
]
</code>```

Second Solution

If you go deep into the problem, you will see the error is saying NoReverseMatch error, which occurs when there is a url name which is not found in project ie account_login. Now this error is coming from template at at allauth base template.

Judging by your code, this error is occurring due to these line:
(I took the liberty to check your github codebase as it was opensource.)

```<code>if not email_confirmation:
    if queryset is None:
        queryset = self.get_queryset()
    try:
        email_confirmation = queryset.get(key=key.lower())
    except EmailConfirmation.DoesNotExist:
        # A React/Vue Router Route will handle the failure scenario
        return HttpResponseRedirect('/login/failure/')  # <-- Here
</code>```

It is pointing to a wrong url which does not exist in system. Please check django-rest-auth urls.

So one fix here is to provide a template response here with a view like this:

```<code># in accounts/api/urls.py
path('failure/', TemplateView.as_view(template_name='api_failure.html'))
</code>```

Another solution is to provide custom 404 template like this:

```<code># accounts/api/views.py
def handler404(request, exception, template_name="your_custom_404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

# root urls.py

 handler404 = 'accounts.api.views.handler404'
</code>```

Body:
As far as I can understand, your error is coming from django-allauth, not from your project. Reason for the error is that you did not include allauth.url in your main urls.py(will explain more in later section).

Possible solutions

First Solution

Add allauth.urls in your urls.py:

urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),
    ...
]

Second Solution

If you go deep into the problem, you will see the error is saying NoReverseMatch error, which occurs when there is a url name which is not found in project ie account_login. Now this error is coming from template at at allauth base template.

Judging by your code, this error is occurring due to these line:
(I took the liberty to check your github codebase as it was opensource.)

if not email_confirmation:
    if queryset is None:
        queryset = self.get_queryset()
    try:
        email_confirmation = queryset.get(key=key.lower())
    except EmailConfirmation.DoesNotExist:
        # A React/Vue Router Route will handle the failure scenario
        return HttpResponseRedirect('/login/failure/')  # <-- Here

It is pointing to a wrong url which does not exist in system. Please check django-rest-auth urls.

So one fix here is to provide a template response here with a view like this:

# in accounts/api/urls.py
path('failure/', TemplateView.as_view(template_name='api_failure.html'))

Another solution is to provide custom 404 template like this:

# accounts/api/views.py
def handler404(request, exception, template_name="your_custom_404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

# root urls.py

 handler404 = 'accounts.api.views.handler404'


问:
Create a typescript function returning react component class
I need to create an utility function, which will be returning one of react component classes (not instances) depending on some condition. So the return type of the function should be generic (React.PureComponent)

import React from 'react';
class FooOne extends React.PureComponent {
    render(): React.ReactElement {
        return null;
    }
}
class FooTwo extends React.PureComponent {
    render(): React.ReactElement {
        return null;
    }
}
function getFooClass(condition: boolean): typeof React.PureComponent {
    return condition ? FooOne : FooTwo;
}
const SomeFooClass = getFooClass(true);
const instance: React.PureComponent = new SomeFooClass();
```

<p>code above is tended to be working (I still not understand why I need to use <strong>typeof React.PureComponent</strong> as return type for getFooClass, this was found experimentally),
but typescript generates the following error for getFooClass:</p>

```Type 'typeof FooOne' is not assignable to type 'typeof PureComponent'.
  Construct signature return types 'FooOne' and 'PureComponent
' are incompatible.
    The types of 'props' are incompatible between these types.
      Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly<{ children?: ReactNode; }> & Readonly
'.
        Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly
'.
```

Maybe this is kind of typescript bug or limitation?

答:
React.ReactNode should work in this case:</p>

```<code>function getFooClass(condition: boolean): React.ReactNode {
  return condition ? FooOne : FooTwo;
}
</code>```

Body:
I need to create an utility function, which will be returning one of react component classes (not instances) depending on some condition. So the return type of the function should be generic (React.PureComponent)

import React from 'react';
class FooOne extends React.PureComponent {
    render(): React.ReactElement {
        return null;
    }
}
class FooTwo extends React.PureComponent {
    render(): React.ReactElement {
        return null;
    }
}
function getFooClass(condition: boolean): typeof React.PureComponent {
    return condition ? FooOne : FooTwo;
}
const SomeFooClass = getFooClass(true);
const instance: React.PureComponent = new SomeFooClass();

code above is tended to be working (I still not understand why I need to use typeof React.PureComponent as return type for getFooClass, this was found experimentally),
but typescript generates the following error for getFooClass:

Type 'typeof FooOne' is not assignable to type 'typeof PureComponent'.
  Construct signature return types 'FooOne' and 'PureComponent
' are incompatible.
    The types of 'props' are incompatible between these types.
      Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly<{ children?: ReactNode; }> & Readonly
'.
        Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly
'.

Maybe this is kind of typescript bug or limitation?

Body:
React.ReactNode should work in this case:

function getFooClass(condition: boolean): React.ReactNode {
  return condition ? FooOne : FooTwo;
}


问:
AppBar Layout Expands Automatically when View visibility is changed from Gone to Visible on runtime
As we can see from the below sample, on changing the visibility of the view from gone to visible and vice versa, the appbar automatically expands and scrim drawn is shown as well.

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/crl_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fillViewport="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/abl_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="@drawable/shape_rectangle_grdient_red_yellow"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax">

                <FrameLayout
                    android:id="@+id/fl_class"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/d_280dp"
                    android:background="@color/colorPlaceholderBg">

                    <ImageView
                        android:id="@+id/iv_class"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:adjustViewBounds="true"
                        android:scaleType="centerCrop"
                        android:src="@color/colorPlaceholderBg" />

                    <ProgressBar
                        android:id="@+id/pb_dp_progress"
                        android:layout_width="@dimen/d_20dp"
                        android:layout_height="@dimen/d_20dp"
                        android:layout_gravity="center"
                        android:visibility="visible" />

                </FrameLayout>

                <RelativeLayout
                    android:id="@+id/rl_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/toolbar_default_height"
                    android:background="@drawable/shape_rectangle_transparent_grey_gradient">

                    <ImageView
                        android:id="@+id/iv_back"
                        ... />

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/tl_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                android:minHeight="@dimen/toolbar_default_height"
                android:visibility="visible"
                app:contentInsetStart="@dimen/d_0dp"
                app:layout_collapseMode="pin">

                <include layout="@layout/view_toolbar" />

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/fragment_class_details_content" />

    </android.support.design.widget.CoordinatorLayout>
</code>```

This the code for the outer layout. As can be seen from the above layout that the pattern is mostly standard. I have tried replicating the bug in new sample but of no use. The initial problem seem to be changing the height of nested scroll view on runtime seems to be the problem but that is not the case. I tried to setExpand(false) on the click of the button but that is not working as well.

```

Link to demo gif is here: https://i.imgur.com/YGTT3oL.gif

答:
Extract your gone/visible layout from android.support.design.widget.CollapsingToolbarLayout.

Too much nesting you did so avoid nesting and Use constraint layout

Body:
As we can see from the below sample, on changing the visibility of the view from gone to visible and vice versa, the appbar automatically expands and scrim drawn is shown as well.

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/crl_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:fillViewport="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/abl_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="@drawable/shape_rectangle_grdient_red_yellow"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax">

                <FrameLayout
                    android:id="@+id/fl_class"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/d_280dp"
                    android:background="@color/colorPlaceholderBg">

                    <ImageView
                        android:id="@+id/iv_class"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:adjustViewBounds="true"
                        android:scaleType="centerCrop"
                        android:src="@color/colorPlaceholderBg" />

                    <ProgressBar
                        android:id="@+id/pb_dp_progress"
                        android:layout_width="@dimen/d_20dp"
                        android:layout_height="@dimen/d_20dp"
                        android:layout_gravity="center"
                        android:visibility="visible" />

                </FrameLayout>

                <RelativeLayout
                    android:id="@+id/rl_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/toolbar_default_height"
                    android:background="@drawable/shape_rectangle_transparent_grey_gradient">

                    <ImageView
                        android:id="@+id/iv_back"
                        ... />

            </RelativeLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/tl_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                android:minHeight="@dimen/toolbar_default_height"
                android:visibility="visible"
                app:contentInsetStart="@dimen/d_0dp"
                app:layout_collapseMode="pin">

                <include layout="@layout/view_toolbar" />

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/fragment_class_details_content" />

    </android.support.design.widget.CoordinatorLayout>

This the code for the outer layout. As can be seen from the above layout that the pattern is mostly standard. I have tried replicating the bug in new sample but of no use. The initial problem seem to be changing the height of nested scroll view on runtime seems to be the problem but that is not the case. I tried to setExpand(false) on the click of the button but that is not working as well.

Link to demo gif is here: https://i.imgur.com/YGTT3oL.gif


问:
I have created a Fragment but don't know what to put inside
I have realised an NFC (to scan tags) application, but now I have to create fragment who works with my MainActivity because I'd like to implement ViewPager in future.

Problem is that i'm really beginner and my code became too big to know what I have to put in Activity and what I have to put in Fragment

One week that I'm trying to understand...

Here is my code

```<code>public class MainActivity extends FragmentActivity {
    ObjectAnimator anim;
    ObjectAnimator anim2;
    private int display, result, detect = 0;
    private NfcAdapter nfcAdapter;
    private ImageButton nfcButton;
    private PendingIntent pendingIntent;
    private ImageButton qrButton;
    private TextView text;
    private ImageButton webButton;
    String link = null;
    public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        slidr = Slidr.attach(this);
        setDetect(1);
        setContentView((int) R.layout.activity_main);
        this.text = (TextView) findViewById(R.id.text);
        this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        IntentIntegrator integrator = new IntentIntegrator(this);
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setDisplay(1);
                manageBlinkEffect();
            }
        });
        this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                   // RESULTAT DU SCAN QR CODE
        if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case CUSTOMIZED_REQUEST_CODE: {
                Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
                break;
            }
            default:
                break;
        }

        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if (result.getContents() != null) {
            Log.d("MainActivity", "Scanned");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Résultat du scan :");
            if (URLUtil.isValidUrl(result.getContents())) {                                                                      // si url...
                builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
                builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
            } else {                                                                                // si plain text...
                builder.setNeutralButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
            }
            builder.setMessage(result.getContents().toString());
            builder.create().show();
        }
    }

    public void manageBlinkEffect() {                                                                           // ANIMATION DU LOGO SENZU SUITE A UN CLIC
        anim.setDuration(1000);
        anim.setRepeatMode(ValueAnimator.REVERSE);
        anim.setRepeatCount(9);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationCancel(animation);
                if (getRes() != 1){
                    Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
                    Toast.makeText(getApplicationContext(), "Aucun badge n'a été détécté !", Toast.LENGTH_SHORT).show();
                    nfcButton.startAnimation(shake);
                }
            }
        });
        anim2.setDuration(1000);
        anim2.setRepeatMode(ValueAnimator.REVERSE);
        anim2.setRepeatCount(9);
        anim2.start();
    }

    public void onResume() {
        super.onResume();

        Intent intent = getIntent(); // Recuperer l'intent actuel
        NdefMessage[] msgs;
        if (getDetect() == 1 && (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))) { // si l'application a ete lancee via une detection NFC du device  (ACTION_NDEF_DISCOVERED, voir AndroidManifest)
            Parcelable[] rawMessages =
                    intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMessages != null) { // si NDEF dans le scan
                setDisplay(1);
                resolveIntent(intent); // parser le scan NFC
            }  else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
                setDetect(0);
                getResult(msgs);
            }
        }
        NfcAdapter nfcAdapter2 = this.nfcAdapter;
        if (nfcAdapter2 != null) {
            if (!nfcAdapter2.isEnabled()) {
                showWirelessSettings();
            }
            this.nfcAdapter.enableForegroundDispatch(this, this.pendingIntent, (IntentFilter[]) null, (String[][]) null);
        }
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "Veuillez activer le service NFC", Toast.LENGTH_SHORT).show();
        startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
    }

    public void onPause() {
        setDetect(0);
        super.onPause();
    }

    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getDetect() != 1) {
            resolveIntent(intent);
        }
    }

    private void resolveIntent(Intent intent) {                                                                 // DETECTION NFC ET PARSING NDEF
        NdefMessage[] msgs;
        String action = intent.getAction();
        Log.d("Infos", getIntent().toString());
        Log.d("Infos", "display = " + display);
        if (getDisplay() != 1) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            nfcButton.startAnimation(shake);
            Toast.makeText(this, "Veuillez lancer un scan", Toast.LENGTH_LONG).show();
            return;
        }
        else if ("android.nfc.action.TAG_DISCOVERED".equals(action) || "android.nfc.action.TECH_DISCOVERED".equals(action) || "android.nfc.action.NDEF_DISCOVERED".equals(action)) {
            setRes(1);
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (getDisplay() == 1) {
                getResult(msgs);
            }
        }
    }

    private void getResult(NdefMessage[] msgs) {                                                            // MODAL AVEC RESULTAT DU SCAN NFC
        if (msgs != null && msgs.length != 0) {
            final StringBuilder tmp_builder = new StringBuilder();
            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
            int size = records.size();
            for (int i = 0; i < size; i++) {
                tmp_builder.append(records.get(i).str());
                tmp_builder.append("\n");
            }
            System.out.println(tmp_builder.toString());
            this.anim.cancel();
            this.anim2.cancel();
            setDisplay(0);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Resultat du scan :");
            builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                 /*  Intent i = new Intent(MainActivity.this, RightActivity.class);
                    link = tmp_builder.toString();
                    i.putExtra("url", link);
                    startActivity(i);*/
                }
            });
            builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Texte copié", link);
                    clipboard.setPrimaryClip(clip);
                }
            });
            builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {}
            });
            builder.setMessage(tmp_builder.toString());
            builder.create().show();
        }
    }
</code>```

I don't know if I have to transfert my onResume, onPause etc. in my Fragment

Really lost...

答:
First of all you should add ViewPager in XML;

Then;

In your activity define your viewpager like that;

```<code>viewPager = findViewById(R.id.viewpager_main)
</code>```

Then use this for setup viewpager

```<code>setupViewPager(viewPager)
</code>```

Create setupViewPager function like that;

```<code>private fun setupViewPager(viewPager: ViewPager) {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(
            MainFragment(),
            "Fragment1"
        )
adapter.addFragment(
            SecondFragment(),
            "Fragment2"
        )
        viewPager.adapter = adapter}
</code>```

Simple example of fragments;

```<code>class MainFragment() : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    retainInstance = true
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? =
    inflater.inflate(R.layout.info_screen_fragment, container, false)

/* info_screen_fragment is your xml for this fragment */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
}
</code>```

My codes written with Kotlin. But i used to this codes. Simple and flex.

Body:
I have realised an NFC (to scan tags) application, but now I have to create fragment who works with my MainActivity because I'd like to implement ViewPager in future.

Problem is that i'm really beginner and my code became too big to know what I have to put in Activity and what I have to put in Fragment

One week that I'm trying to understand...

Here is my code

public class MainActivity extends FragmentActivity {
    ObjectAnimator anim;
    ObjectAnimator anim2;
    private int display, result, detect = 0;
    private NfcAdapter nfcAdapter;
    private ImageButton nfcButton;
    private PendingIntent pendingIntent;
    private ImageButton qrButton;
    private TextView text;
    private ImageButton webButton;
    String link = null;
    public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        slidr = Slidr.attach(this);
        setDetect(1);
        setContentView((int) R.layout.activity_main);
        this.text = (TextView) findViewById(R.id.text);
        this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        IntentIntegrator integrator = new IntentIntegrator(this);
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setDisplay(1);
                manageBlinkEffect();
            }
        });
        this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                   // RESULTAT DU SCAN QR CODE
        if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case CUSTOMIZED_REQUEST_CODE: {
                Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
                break;
            }
            default:
                break;
        }

        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if (result.getContents() != null) {
            Log.d("MainActivity", "Scanned");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Résultat du scan :");
            if (URLUtil.isValidUrl(result.getContents())) {                                                                      // si url...
                builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
                builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
            } else {                                                                                // si plain text...
                builder.setNeutralButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
            }
            builder.setMessage(result.getContents().toString());
            builder.create().show();
        }
    }

    public void manageBlinkEffect() {                                                                           // ANIMATION DU LOGO SENZU SUITE A UN CLIC
        anim.setDuration(1000);
        anim.setRepeatMode(ValueAnimator.REVERSE);
        anim.setRepeatCount(9);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationCancel(animation);
                if (getRes() != 1){
                    Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
                    Toast.makeText(getApplicationContext(), "Aucun badge n'a été détécté !", Toast.LENGTH_SHORT).show();
                    nfcButton.startAnimation(shake);
                }
            }
        });
        anim2.setDuration(1000);
        anim2.setRepeatMode(ValueAnimator.REVERSE);
        anim2.setRepeatCount(9);
        anim2.start();
    }

    public void onResume() {
        super.onResume();

        Intent intent = getIntent(); // Recuperer l'intent actuel
        NdefMessage[] msgs;
        if (getDetect() == 1 && (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))) { // si l'application a ete lancee via une detection NFC du device  (ACTION_NDEF_DISCOVERED, voir AndroidManifest)
            Parcelable[] rawMessages =
                    intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMessages != null) { // si NDEF dans le scan
                setDisplay(1);
                resolveIntent(intent); // parser le scan NFC
            }  else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
                setDetect(0);
                getResult(msgs);
            }
        }
        NfcAdapter nfcAdapter2 = this.nfcAdapter;
        if (nfcAdapter2 != null) {
            if (!nfcAdapter2.isEnabled()) {
                showWirelessSettings();
            }
            this.nfcAdapter.enableForegroundDispatch(this, this.pendingIntent, (IntentFilter[]) null, (String[][]) null);
        }
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "Veuillez activer le service NFC", Toast.LENGTH_SHORT).show();
        startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
    }

    public void onPause() {
        setDetect(0);
        super.onPause();
    }

    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getDetect() != 1) {
            resolveIntent(intent);
        }
    }

    private void resolveIntent(Intent intent) {                                                                 // DETECTION NFC ET PARSING NDEF
        NdefMessage[] msgs;
        String action = intent.getAction();
        Log.d("Infos", getIntent().toString());
        Log.d("Infos", "display = " + display);
        if (getDisplay() != 1) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            nfcButton.startAnimation(shake);
            Toast.makeText(this, "Veuillez lancer un scan", Toast.LENGTH_LONG).show();
            return;
        }
        else if ("android.nfc.action.TAG_DISCOVERED".equals(action) || "android.nfc.action.TECH_DISCOVERED".equals(action) || "android.nfc.action.NDEF_DISCOVERED".equals(action)) {
            setRes(1);
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (getDisplay() == 1) {
                getResult(msgs);
            }
        }
    }

    private void getResult(NdefMessage[] msgs) {                                                            // MODAL AVEC RESULTAT DU SCAN NFC
        if (msgs != null && msgs.length != 0) {
            final StringBuilder tmp_builder = new StringBuilder();
            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
            int size = records.size();
            for (int i = 0; i < size; i++) {
                tmp_builder.append(records.get(i).str());
                tmp_builder.append("\n");
            }
            System.out.println(tmp_builder.toString());
            this.anim.cancel();
            this.anim2.cancel();
            setDisplay(0);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Resultat du scan :");
            builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                 /*  Intent i = new Intent(MainActivity.this, RightActivity.class);
                    link = tmp_builder.toString();
                    i.putExtra("url", link);
                    startActivity(i);*/
                }
            });
            builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Texte copié", link);
                    clipboard.setPrimaryClip(clip);
                }
            });
            builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {}
            });
            builder.setMessage(tmp_builder.toString());
            builder.create().show();
        }
    }

I don't know if I have to transfert my onResume, onPause etc. in my Fragment

Really lost...

Body:
First of all you should add ViewPager in XML;

Then;

In your activity define your viewpager like that;

viewPager = findViewById(R.id.viewpager_main)

Then use this for setup viewpager

setupViewPager(viewPager)

Create setupViewPager function like that;

private fun setupViewPager(viewPager: ViewPager) {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(
            MainFragment(),
            "Fragment1"
        )
adapter.addFragment(
            SecondFragment(),
            "Fragment2"
        )
        viewPager.adapter = adapter}

Simple example of fragments;

class MainFragment() : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    retainInstance = true
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? =
    inflater.inflate(R.layout.info_screen_fragment, container, false)

/* info_screen_fragment is your xml for this fragment */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
}

My codes written with Kotlin. But i used to this codes. Simple and flex.


问:
dd/mm/yyyy vs dd/MM/yyyy?
```<code>SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String date = sdf.format(new Date());
        System.out.println(date);
</code>```

Result is todays date i.e 23/03/2014

But when i do

```<code> SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
</code>```

result can be 23/05/2014, 23/05/2014, 23/06/2014  and son with each run of prgram. Why so?

答:
Yes it is because mm represents minutes

```<code> Date date=new Date();
    System.out.println(date);
    System.out.println("Date: "+new SimpleDateFormat("dd/MM/yyyy").format(date));
    System.out.println("Date: "+new SimpleDateFormat("dd/mm/yyyy").format(date));
</code>```

if you observed the output you will find  when we print date object, there is value of minutes, month, etc and in 2nd line and 3rd line same minute is printed corresponding to mm and month value is printed
  corresponding to MM

```<code>Thu Feb 20 14:33:00 IST 2020
20/02/2020
20/33/2020
</code>```

ContentLicense: CC BY-SA 3.0

Title: dd/mm/yyyy vs dd/MM/yyyy?

Body:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String date = sdf.format(new Date());
        System.out.println(date);

Result is todays date i.e 23/03/2014

But when i do

 SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");

result can be 23/05/2014, 23/05/2014, 23/06/2014  and son with each run of prgram. Why so?

Body:
Yes it is because mm represents minutes

 Date date=new Date();
    System.out.println(date);
    System.out.println("Date: "+new SimpleDateFormat("dd/MM/yyyy").format(date));
    System.out.println("Date: "+new SimpleDateFormat("dd/mm/yyyy").format(date));

if you observed the output you will find  when we print date object, there is value of minutes, month, etc and in 2nd line and 3rd line same minute is printed corresponding to mm and month value is printed
  corresponding to MM

Thu Feb 20 14:33:00 IST 2020
20/02/2020
20/33/2020


问:
Angular: How to set downloading spinner when there can be n-number of items that can be downloaded
I have n-number of items that can be downloaded dependent on the user. Normally when I have one item I would create a variable set that one to false and when the subscribe starts set it to true and when it finishes back to false. Now I have to do it for multiple items that the user self can download so setting the variables in the component is not an option. What would be the right way to implement this?</p>

答:
I would bind the download event of each item to a boolean array, set to false.
Once the user select what to download, set it to true, and when finished back to false.

Then you can bind the spinner to a method that checks any of the array elements is true.


问:
OpenCV via python: Is there a fast way to zero pixels outside a set of rectangles?
I have an image of a face and I have used haar cascades to detect the locations (x,y,width,height) of the mouth, nose and each eye. I would like to set all pixels outside these regions to zero. What would be the fastest (computationally) way to do this? I'll eventually be doing it to video frames in real time.</p>

答:
If a polygon ROI is to be made.
Create the polygon and make a mask for it. Multiply the image with the created frame.</p>

```<code>    ret,frame = cv2.imread()
    xr=1
    yr=1
    # y,x
    pts = np.array([[int(112*yr),int(32*xr)],[int(0*yr),int(623*xr)],[int(789*yr),int(628*xr)],[int(381*yr),int(4*xr)]], np.int32)
    pts = pts.reshape((-1,1,2))
    cv2.polylines(frame,[pts],True,(0,255,255))

    mask = np.zeros(frame.shape[:2],np.uint8)
    cv2.fillPoly(mask,[pts],(255,255,255))
    frame = cv2.bitwise_and(frame,frame,mask = mask)
    cv2.imshow("masked frame", frame)
</code>```

Body:
If a polygon ROI is to be made.
Create the polygon and make a mask for it. Multiply the image with the created frame.

    ret,frame = cv2.imread()
    xr=1
    yr=1
    # y,x
    pts = np.array([[int(112*yr),int(32*xr)],[int(0*yr),int(623*xr)],[int(789*yr),int(628*xr)],[int(381*yr),int(4*xr)]], np.int32)
    pts = pts.reshape((-1,1,2))
    cv2.polylines(frame,[pts],True,(0,255,255))

    mask = np.zeros(frame.shape[:2],np.uint8)
    cv2.fillPoly(mask,[pts],(255,255,255))
    frame = cv2.bitwise_and(frame,frame,mask = mask)
    cv2.imshow("masked frame", frame)


问:
Scala: How serialize data in JSON?
I recently started to learn Scala. I need an EASY way to SERIALIZE my data in Json. Below I will give an example of data. I tried several popular libraries: GSON, Play JSON, Circe, but did not get the result! GSON does not know how to work with Option (eg Option [String]), in Play JSON and Circe they need to describe serialization and deserialization of an abstract class (I don’t know how to get around this).</p>

```<code>// Test data

  abstract class Base(id: Long, descr: Option[String])
  case class A(id: Long, descr: Option[String], a: Option[Long]) extends Base(id, descr)
  case class B(id: Long, descr: Option[String], b: Option[Double]) extends Base(id, descr)

  case class Data(id: Long, user: Option[String], data: Option[Array[Base]])

  val test: Array[Data] = Array(
    Data(1, Some("Qqq"), None),
    Data(2, None, None),
    Data(3, Some("Zzz"), Some(
      Array(
        A(1, Some("a1"), Some(111)),
        A(2, Some("a2"), None),
        A(3, None, Some(333)),
        B(4, Some("b1"), Some(444.444)),
        B(5, Some("b2"), None),
        B(6, None, Some(666.666))
      )
    ))   )
</code>```

答:
You need to create a companion object for your case class as:

```<code>object Data {
  import play.api.libs.json._
  implicit val read = Json.reads[Data]
  implicit val write = Json.writes[Data]
  implicit val dataFormat = Json.format[Data]

  def tupled = (Data.apply _).tupled
}
</code>```

Both case class and object must be placed in same file.

Then, when you need to use it, import play.api.libs.json._:

```<code>   val myObject = new Data(100, None, None)
   val myJson = Json.toJson(myObject)
</code>```

Obs: this is a Play framework library, if you not use this fw, I'm not sure that you can use it.

Another obs ... when you convert an object into a json, all optional parameters, if are None, will not appear into your json value. So, for my example, result will not contain user and data parameters:

```<code>{
   "id": 100
}
</code>```

Title: Scala: How serialize data in JSON?

Body:
I recently started to learn Scala. I need an EASY way to SERIALIZE my data in Json. Below I will give an example of data. I tried several popular libraries: GSON, Play JSON, Circe, but did not get the result! GSON does not know how to work with Option (eg Option [String]), in Play JSON and Circe they need to describe serialization and deserialization of an abstract class (I don’t know how to get around this).

// Test data

  abstract class Base(id: Long, descr: Option[String])
  case class A(id: Long, descr: Option[String], a: Option[Long]) extends Base(id, descr)
  case class B(id: Long, descr: Option[String], b: Option[Double]) extends Base(id, descr)

  case class Data(id: Long, user: Option[String], data: Option[Array[Base]])

  val test: Array[Data] = Array(
    Data(1, Some("Qqq"), None),
    Data(2, None, None),
    Data(3, Some("Zzz"), Some(
      Array(
        A(1, Some("a1"), Some(111)),
        A(2, Some("a2"), None),
        A(3, None, Some(333)),
        B(4, Some("b1"), Some(444.444)),
        B(5, Some("b2"), None),
        B(6, None, Some(666.666))
      )
    ))   )

Body:
You need to create a companion object for your case class as:

object Data {
  import play.api.libs.json._
  implicit val read = Json.reads[Data]
  implicit val write = Json.writes[Data]
  implicit val dataFormat = Json.format[Data]

  def tupled = (Data.apply _).tupled
}

Both case class and object must be placed in same file.

Then, when you need to use it, import play.api.libs.json._:

   val myObject = new Data(100, None, None)
   val myJson = Json.toJson(myObject)

Obs: this is a Play framework library, if you not use this fw, I'm not sure that you can use it.

Another obs ... when you convert an object into a json, all optional parameters, if are None, will not appear into your json value. So, for my example, result will not contain user and data parameters:

{
   "id": 100
}


问:
CSS "and" and "or"
I've got quite big trouble, because i need to anathematise from styling some input types. I had something like:

```<code>.registration_form_right input:not([type="radio")
{
 //Nah.
}
</code>```

But i don't want to style checkboxes too.

I've tried:

```<code>.registration_form_right input:not([type="radio" && type="checkbox"])
.registration_form_right input:not([type="radio" && "checkbox"])
.registration_form_right input:not([type="radio") && .registration_form_right input:not(type="checkbox"])
</code>```

How to use &&? And I'll need to use || soon, and I think that usage will be same.

Update:

I still don't know how to use || and && correctly. I couldn't find anything in W3 docs.

答:
A word of caution. Stringing together several not selectors increases the specificity of the resulting selector, which makes it harder to override: you'll basically need to find the selector with all the nots and copy-paste it into your new selector.

A not(X or Y) selector would be great to avoid inflating specificity, but I guess we'll have to stick to combining the opposites, like in this answer.

Title: CSS "and" and "or"

Body:
I've got quite big trouble, because i need to anathematise from styling some input types. I had something like:

.registration_form_right input:not([type="radio")
{
 //Nah.
}

But i don't want to style checkboxes too.

I've tried:

.registration_form_right input:not([type="radio" && type="checkbox"])
.registration_form_right input:not([type="radio" && "checkbox"])
.registration_form_right input:not([type="radio") && .registration_form_right input:not(type="checkbox"])

How to use &&? And I'll need to use || soon, and I think that usage will be same.

Update:

I still don't know how to use || and && correctly. I couldn't find anything in W3 docs.


问:
Gwt: CellTable CSS removes all other CSS files
I am having a problem, when I override the CellTable CSS file with mine (a different one), then all other CSS files get disappear and changes the styles etc. on page.
What could be the problem?

Can I add more styles (other than CellTable's) into celltable CSS file that I override?

答:
CellTable's styling works differently than most other widgets in GWT. It uses a ClientBUndle to inject its styling information. This bundle is injected last, so it overrides any styling you may have already done.

Look at the CellTable class' code to see how it extends the ClientBundle with its "Resources" interface and how it then extends that with "BasicResources".

To override this default behavior, I had to:

1. create my own css file with different stying

2. create my own interface that extends CellTable.Resource, much the same way that BasicResource does in CellTable.java

3. instantiate my CellTable object with my resource

If you would like, I can email you some source code.


问:
How to calculate an average number of an action per week having logins of users and time and date of the action using pandas?
I have a dataset with logins and date and time of users' posts.

```<code>posts = {'Login':['User1', 'User2', 'User2', 'User1', 'User2', 'User1', 'User2', 'User2'], 'Posted':['17.02.2020 12:32', '19.02.2020 10:11', '21.02.2020 07:08', '22.02.2020 14:00', '23.02.2020 11:02', '25.02.2020 18:19', '27.02.2020 00:03', '29.02.2020 15:56']}
df_posts = pd.DataFrame(posts)

    Login   Posted
0   User1   17.02.2020 12:32
1   User2   19.02.2020 10:11
2   User2   21.02.2020 07:08
3   User1   22.02.2020 14:00
4   User2   23.02.2020 11:02
5   User1   25.02.2020 18:19
6   User2   27.02.2020 00:03
7   User2   29.02.2020 15:56
</code>```

I need to calculate an average number of posts made for each user. For example, for this dataset User1 made 2 posts during a week from Feb 17 to Feb 23 and 1 post during the next week (Feb 24 - Mar 1). So, on average, User1 does 1.5 posts per week.

I need to get the following result:

```<code>    Login   Average number of posts per week
0   User1   1.5
1   User2   2.5
</code>```

I tried to write the following code:

```<code># Assigning a week column to each post
posts['Week'] = posts['Posted'].dt.strftime('%U')

# Calculating total number of posts per week for each user
total_posts = posts.groupby(['Login', 'Week']).size().reset_index(name ='Total_posts')

# Estimating average frequency of making posts for each user
freq_posts_per_week = total_posts.groupby('Login')['Total_posts'].mean().reset_index(name ='Avg_posts_per_week')
</code>```

But I got the following error:

/Users/username/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:2:
  SettingWithCopyWarning:
      A value is trying to be set on a copy of a slice from a DataFrame.
      Try using .loc[row_indexer,col_indexer] = value instead

```<code>See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
</code>```

Also, my results look wrong for me.

Could anyone help me to fix the problem?

答:
Try:</p>

```<code>df_posts.Posted = pd.to_datetime(df_posts.Posted)
(df_posts.groupby(['Login', pd.Grouper(key='Posted',freq='W')]).size()
         .groupby('Login').mean()
         .reset_index(name ='Avg_posts_per_week'))

   Login  Avg_posts_per_week
0  User1                 1.5
1  User2                 2.5
</code>```

Body:
I have a dataset with logins and date and time of users' posts.

posts = {'Login':['User1', 'User2', 'User2', 'User1', 'User2', 'User1', 'User2', 'User2'], 'Posted':['17.02.2020 12:32', '19.02.2020 10:11', '21.02.2020 07:08', '22.02.2020 14:00', '23.02.2020 11:02', '25.02.2020 18:19', '27.02.2020 00:03', '29.02.2020 15:56']}
df_posts = pd.DataFrame(posts)

    Login   Posted
0   User1   17.02.2020 12:32
1   User2   19.02.2020 10:11
2   User2   21.02.2020 07:08
3   User1   22.02.2020 14:00
4   User2   23.02.2020 11:02
5   User1   25.02.2020 18:19
6   User2   27.02.2020 00:03
7   User2   29.02.2020 15:56

I need to calculate an average number of posts made for each user. For example, for this dataset User1 made 2 posts during a week from Feb 17 to Feb 23 and 1 post during the next week (Feb 24 - Mar 1). So, on average, User1 does 1.5 posts per week.

I need to get the following result:

    Login   Average number of posts per week
0   User1   1.5
1   User2   2.5

I tried to write the following code:

# Assigning a week column to each post
posts['Week'] = posts['Posted'].dt.strftime('%U')

# Calculating total number of posts per week for each user
total_posts = posts.groupby(['Login', 'Week']).size().reset_index(name ='Total_posts')

# Estimating average frequency of making posts for each user
freq_posts_per_week = total_posts.groupby('Login')['Total_posts'].mean().reset_index(name ='Avg_posts_per_week')

But I got the following error:

/Users/username/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:2:
  SettingWithCopyWarning:
      A value is trying to be set on a copy of a slice from a DataFrame.
      Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Also, my results look wrong for me.

Could anyone help me to fix the problem?

Body:
Try:

df_posts.Posted = pd.to_datetime(df_posts.Posted)
(df_posts.groupby(['Login', pd.Grouper(key='Posted',freq='W')]).size()
         .groupby('Login').mean()
         .reset_index(name ='Avg_posts_per_week'))

   Login  Avg_posts_per_week
0  User1                 1.5
1  User2                 2.5


问:
2D ArrayList In Java find object in column
I have 2D ArrayList and I want to find the index of a String located in the 1st Column.

arraylist.get(0).indexOf("My String") returns the index of a string located at first row.
But I want something like this

```<code>arraylist.indexOf("MyString").get(0)
</code>```

答:
I have one question for you. How many times do you intend to perform that search (of that String or another one)?

If it is only once you will have to iterate over the ArrayLists until you find the right one.

BUT if you intend to perform several searches in the same column of the bi-dimensional array, I would advice you to make a transposed-copy of that structure and keep it in a variable in memory. You need to be aware that if the rows of the bi-dimensional array have different sizes, then you cannot make this operation.

By this way you will avoid the need of looping through multiple arrays and save some computing time in next searches. Then the look up would be close to what you want:

```<code>Integer index = arraylist_transposed[0].indexOf("MyString");
List<String> result = arraylist.get(index);
</code>```

You can take a look to this question for doing the transpose of your bidimensional array:
Transpose a 2d Array with varying dimensions in Java

Body:
I have 2D ArrayList and I want to find the index of a String located in the 1st Column.

arraylist.get(0).indexOf("My String") returns the index of a string located at first row.
But I want something like this

arraylist.indexOf("MyString").get(0)

Body:
I have one question for you. How many times do you intend to perform that search (of that String or another one)?

If it is only once you will have to iterate over the ArrayLists until you find the right one.

BUT if you intend to perform several searches in the same column of the bi-dimensional array, I would advice you to make a transposed-copy of that structure and keep it in a variable in memory. You need to be aware that if the rows of the bi-dimensional array have different sizes, then you cannot make this operation.

By this way you will avoid the need of looping through multiple arrays and save some computing time in next searches. Then the look up would be close to what you want:

Integer index = arraylist_transposed[0].indexOf("MyString");
List<String> result = arraylist.get(index);

You can take a look to this question for doing the transpose of your bidimensional array:
Transpose a 2d Array with varying dimensions in Java


问:
Building a plot for each unique value of a column
I have data with multiple variables and I want to make a plot for each of the unique values in one column. I looked at multiple answers on here for similar problems but I couldnt solve mine.

An example of the dataset looks as follows:

```<code>structure(list(ID = c(1, 1, 1, 2, 2), Date = c("01/02/20", "01/03/20",
"01/05/20", "01/02/20", "01/05/20"), New = c(10, 5, 5, 10, 5),
    Old = c(20, 20, 20, 20, 20), Percentage = c(0.5, 0.25, 0.25,
    0.5, 0.25)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

```<code>ID      Date          New    Old   Percentage
1       01/02/20      10     20    0.5
1       01/03/20      5      20    0.25
1       01/05/20      5      20    0.25
2       01/02/20      10     20    0.5
2       01/05/20      5      20    0.25
</code>```

I wanted to do a for loop that goes over the unique values of ID and plot the new and old vs date. Also maybe another facet that should the percent change but mainly the first comparison plot. I tried first to make it as date vs new as follow:

```<code>for (ii in unique(data$ID)) {
  plt <- ggplot(data %>% filter(ID == ii),
                aes(x = "Month",
                    y = "New")) +
    geom_point(color = "dodgerblue3") +
    theme_minimal()
  print(plt)

}

</code>```

The result basically gave me a on point plot which I didnt understand. How can I add the Old comparison and also another plot for the percentage.

答:
Is this somewhat what you are looking for?

```<code>library(tidyverse)
library(lubridate)

df %>%
    mutate(Date = mdy(Date)) %>%
    pivot_longer(cols = c("New", "Old"), names_to = "newOrOld") %>%
    ggplot(aes(Date, value, colour = newOrOld)) +
    geom_point() +
    facet_grid(. ~ ID)
</code>```

Body:
I have data with multiple variables and I want to make a plot for each of the unique values in one column. I looked at multiple answers on here for similar problems but I couldnt solve mine.

An example of the dataset looks as follows:

structure(list(ID = c(1, 1, 1, 2, 2), Date = c("01/02/20", "01/03/20",
"01/05/20", "01/02/20", "01/05/20"), New = c(10, 5, 5, 10, 5),
    Old = c(20, 20, 20, 20, 20), Percentage = c(0.5, 0.25, 0.25,
    0.5, 0.25)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

ID      Date          New    Old   Percentage
1       01/02/20      10     20    0.5
1       01/03/20      5      20    0.25
1       01/05/20      5      20    0.25
2       01/02/20      10     20    0.5
2       01/05/20      5      20    0.25

I wanted to do a for loop that goes over the unique values of ID and plot the new and old vs date. Also maybe another facet that should the percent change but mainly the first comparison plot. I tried first to make it as date vs new as follow:

for (ii in unique(data$ID)) {
  plt <- ggplot(data %>% filter(ID == ii),
                aes(x = "Month",
                    y = "New")) +
    geom_point(color = "dodgerblue3") +
    theme_minimal()
  print(plt)

}

The result basically gave me a on point plot which I didnt understand. How can I add the Old comparison and also another plot for the percentage.

Body:
Is this somewhat what you are looking for?

library(tidyverse)
library(lubridate)

df %>%
    mutate(Date = mdy(Date)) %>%
    pivot_longer(cols = c("New", "Old"), names_to = "newOrOld") %>%
    ggplot(aes(Date, value, colour = newOrOld)) +
    geom_point() +
    facet_grid(. ~ ID)


问:
Hibernate save to db 31.12.2009 23:00:00.000000 instead of 1.1.2010
I have application with spring + jpa + hibernate. There are two joda date time fields. They are generate to database as TimeStamp(6).

The first one is set to DateTime()
The second one is set to 01/01/2010

If I check the saved values:
first one is set to LocalTime - 2 which it is probably UTC

second one is set to 31.12.2009 23:00:00.000000

WHY?????????

Edit according to comment by original author:

```<code>private void updateTimeStamps()
{
  if (validFrom == null) {
    validFrom = new DateTime();
  }
  // if (validTill == null) {
    validTill = new DateTime().withDate(2010, 01, 01);
  // }
}
</code>```

But the difference of second one is UTC shift.

答:
Try this:</p>

```<code>new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have application with spring + jpa + hibernate. There are two joda date time fields. They are generate to database as TimeStamp(6).

The first one is set to DateTime()
The second one is set to 01/01/2010

If I check the saved values:
first one is set to LocalTime - 2 which it is probably UTC

second one is set to 31.12.2009 23:00:00.000000

WHY?????????

Edit according to comment by original author:

private void updateTimeStamps()
{
  if (validFrom == null) {
    validFrom = new DateTime();
  }
  // if (validTill == null) {
    validTill = new DateTime().withDate(2010, 01, 01);
  // }
}

But the difference of second one is UTC shift.

Body:
Try this:

new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);


问:
Setting build number format conditionally
I'm using the YML file and i'm trying to set the build number format using the following snippet, but I'm not quite sure how to get the `Build.SourceBranch' into the formatting.

I've tried to use $(Build.SourceBranch) ... (Build.SourceBranch) and Build.SourceBranch

I'm attempting to set the output to look like

20190220-create-yaml.2 etc for when it's a feature feature branch.

and just 20190220.3 when it's a master branch.

```<code>variables:
    ${{ if ne(variables['Build.SourceBranch'], 'master') }}:
      branchSuffix: ${{ format('-{0}', $(Build.SourceBranch)) }}
    ${{ if eq(variables['Build.SourceBranch'], 'master') }}:
      branchSuffix: ''

name: $(Date:yyyyMMdd)$(branchSuffix)$(Rev:.r)
</code>```

答:
As Lance Li mentioned, use Build.SourceBranchName instead of Build.SourceBranch. Additionally, in format function use Build.SourceBranchName variable through variables function:

```<code>variables:
    ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
      branchSuffix: ${{ format('-{0}', variables['Build.SourceBranchName']) }}
    ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
      branchSuffix: ''

name: $(Date:yyyyMMdd)$(branchSuffix)$(Rev:.r)
</code>```

If you want to use $(Build.SourceBranch), add to comparing value refs/heads:

ne(variables['Build.SourceBranch'], 'refs/heads/master')

Body:
I'm using the YML file and i'm trying to set the build number format using the following snippet, but I'm not quite sure how to get the `Build.SourceBranch' into the formatting.

I've tried to use $(Build.SourceBranch) ... (Build.SourceBranch) and Build.SourceBranch

I'm attempting to set the output to look like

20190220-create-yaml.2 etc for when it's a feature feature branch.

and just 20190220.3 when it's a master branch.

variables:
    ${{ if ne(variables['Build.SourceBranch'], 'master') }}:
      branchSuffix: ${{ format('-{0}', $(Build.SourceBranch)) }}
    ${{ if eq(variables['Build.SourceBranch'], 'master') }}:
      branchSuffix: ''

name: $(Date:yyyyMMdd)$(branchSuffix)$(Rev:.r)

Body:
As Lance Li mentioned, use Build.SourceBranchName instead of Build.SourceBranch. Additionally, in format function use Build.SourceBranchName variable through variables function:

variables:
    ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
      branchSuffix: ${{ format('-{0}', variables['Build.SourceBranchName']) }}
    ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
      branchSuffix: ''

name: $(Date:yyyyMMdd)$(branchSuffix)$(Rev:.r)

If you want to use $(Build.SourceBranch), add to comparing value refs/heads:

ne(variables['Build.SourceBranch'], 'refs/heads/master')


问:
how to color text input in Angular material
this is my user Form:

I have a problem, the color of  input field is white, and the background is same white.
I could not find anywhere How to change the color of input field.

What the attribute css for color texte  ?

this is my template :

    <mat-form-field>
      <input matInput placeholder="Input">
    </mat-form-field>

    <mat-form-field>
      <textarea matInput placeholder="Textarea"></textarea>
    </mat-form-field>

    <mat-form-field>
      <mat-select placeholder="Select">
        <mat-option value="option">Option</mat-option>
      </mat-select>
    </mat-form-field>

  new contact
```

答:
If you are using angular ..

add this in 'style.css'

```<code> .mat-form-field-empty.mat-form-field-label {
    color: green;}
</code>```

Body:
If you are using angular ..

add this in 'style.css'

 .mat-form-field-empty.mat-form-field-label {
    color: green;}


问:
Presto-Sql : Converting time in string format to date format
In presto, I have a date formatted as varchar that looks like below :

```<code> 10:46:00
</code>```

I need to cast this in timestamp. I have tried few but presto throwing errors as

Value cannot be cast to date:10:46:00 and Value cannot be cast to
  timestamp:10:46:00

```<code>select cast('10:46:00' as DATE) from abc;

select cast('10:46:00' as TIMESTAMP) from abc;
</code>```

答:
Try with the below query it will solve your problem.

Input Query in Presto:

select (hour(date_parse(CheckStartTime,'%T')) + 1) as hr from TableName;

CheckStartTime:

Column name(varchar) of the table in the format of '12:32:20'.

Output:

13 (it will add one hour to the input time)

Body:
In presto, I have a date formatted as varchar that looks like below :

 10:46:00

I need to cast this in timestamp. I have tried few but presto throwing errors as

Value cannot be cast to date:10:46:00 and Value cannot be cast to
  timestamp:10:46:00

select cast('10:46:00' as DATE) from abc;

select cast('10:46:00' as TIMESTAMP) from abc;


问:
Recursive DotDict
I have a utility class that makes Python dictionaries behave somewhat like JavaScript objects as far as getting and setting attributes.

```<code>class DotDict(dict):
    """
    a dictionary that supports dot notation
    as well as dictionary access notation
    usage: d = DotDict() or d = DotDict({'val1':'first'})
    set attributes: d.val2 = 'second' or d['val2'] = 'second'
    get attributes: d.val2 or d['val2']
    """
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__
</code>```

I would like to make it so it also converts nested dictionaries into DotDict() instances. I was hoping to be able to do something like this with __init__ or __new__, but I haven't come up with anything that works:

```<code>def __init__(self, dct):
    for key in dct.keys():
        if hasattr(dct[key], 'keys'):
            dct[key] = DotDict(dct[key])
</code>```

How can I recursively convert the nested dictionaries into DotDict() instances?

```<code>>>> dct = {'scalar_value':1, 'nested_dict':{'value':2}}
>>> dct = DotDict(dct)

>>> print dct
{'scalar_value': 1, 'nested_dict': {'value': 2}}

>>> print type(dct)
<class '__main__.DotDict'>

>>> print type(dct['nested_dict'])
<type 'dict'>
</code>```

答:
Shamelessly plugging my own package

There is a package doing exactly what you want and also something more and it is called Prodict.

from prodict import Prodict

life_dict = {'bigBang':
                {'stars':
                    {'planets': []}
                }
            }

life = Prodict.from_dict(life_dict)

print(life.bigBang.stars.planets)
# prints []

# you can even add new properties dynamically
life.bigBang.galaxies = []

```

PS 1: I'm the author of the Prodict.

PS 2: This is a direct copy paste of an answer of another question.

Title: Recursive DotDict

Body:
I have a utility class that makes Python dictionaries behave somewhat like JavaScript objects as far as getting and setting attributes.

class DotDict(dict):
    """
    a dictionary that supports dot notation
    as well as dictionary access notation
    usage: d = DotDict() or d = DotDict({'val1':'first'})
    set attributes: d.val2 = 'second' or d['val2'] = 'second'
    get attributes: d.val2 or d['val2']
    """
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

I would like to make it so it also converts nested dictionaries into DotDict() instances. I was hoping to be able to do something like this with __init__ or __new__, but I haven't come up with anything that works:

def __init__(self, dct):
    for key in dct.keys():
        if hasattr(dct[key], 'keys'):
            dct[key] = DotDict(dct[key])

How can I recursively convert the nested dictionaries into DotDict() instances?

>>> dct = {'scalar_value':1, 'nested_dict':{'value':2}}
>>> dct = DotDict(dct)

>>> print dct
{'scalar_value': 1, 'nested_dict': {'value': 2}}

>>> print type(dct)
<class '__main__.DotDict'>

>>> print type(dct['nested_dict'])
<type 'dict'>

Body:
Shamelessly plugging my own package

There is a package doing exactly what you want and also something more and it is called Prodict.

from prodict import Prodict

life_dict = {'bigBang':
                {'stars':
                    {'planets': []}
                }
            }

life = Prodict.from_dict(life_dict)

print(life.bigBang.stars.planets)
# prints []

# you can even add new properties dynamically
life.bigBang.galaxies = []

PS 1: I'm the author of the Prodict.

PS 2: This is a direct copy paste of an answer of another question.


问:
Should @transactional services be singleton or prototype in spring?
Will transaction management be a problem in spring if the service layer class is singleton? Or should it be prototype?</p>

答:
No that should not be a problem. What the @Transactional annotation will do is bind the Transaction lifecyle to the current thread. So each new thread will be run in a separate transaction.

So when your method is invoked, Spring will wrap that method call into a Transaction, so in a single threaded context, a transaction will start and commit  if the invocation is successful, and rollback (depending on your config) if an exception is thrown.

In a multithreaded context, each Thread will run in a separate transaction.


问:
Username as a path
I would like to have a user's name as a part of a URL, e.g. mysite.com/username. This should redirect to the user profile. I use Profile 2 and Pathauto, but I am not sure how to do this. </p>

答: Pathauto pattern of [user:name] under User paths should do the trick.

Title: Username as a path


问:
How to add custom translation to Antdesign + React.js App
I am using Antd + React.js combination. Can anybody help me with how to implement Internationalization like I want to add my own translation too? I understand how the default one is working. I would like to add the translation for my own custom component.</p>

答:
If you have your own custom component you probably won't be able to use internationalization that comes packed with antd components.

Your best bet would probably be a library like react-i18next or react-intl. Both are easy to implement and can provide you a way to put any kind of translated/formatted strings in your application, no matter what UI framework you actually use.


问:
SQL error 'ER_OPERAND_COLUMNS: Operand should contain 1 column(s)' for DELETE function
Trying to delete rows that exist in both temp_abstract table and abstract table.

```<code>DELETE FROM temp_abstracts
WHERE application_id IN
    (SELECT temp_abstracts.application_id, abstracts.application_id
    FROM temp_abstracts INNER JOIN abstracts
    ON temp_abstracts.application_id=abstracts.application_id)
    ;
</code>```

When I just run what's inside the parentheses it returns what I want, but adding a delete from where seems to throw this error. Any help?

答:
You can use EXISTS instead :

```<code>DELETE ta
FROM temp_abstracts ta
WHERE EXISTS (SELECT 1 FROM abstracts a WHERE a.application_id = ta.application_id);
</code>```

Sub-query will return only one expression while using IN OR NOT IN.

Body:
Trying to delete rows that exist in both temp_abstract table and abstract table.

DELETE FROM temp_abstracts
WHERE application_id IN
    (SELECT temp_abstracts.application_id, abstracts.application_id
    FROM temp_abstracts INNER JOIN abstracts
    ON temp_abstracts.application_id=abstracts.application_id)
    ;

When I just run what's inside the parentheses it returns what I want, but adding a delete from where seems to throw this error. Any help?

Body:
You can use EXISTS instead :

DELETE ta
FROM temp_abstracts ta
WHERE EXISTS (SELECT 1 FROM abstracts a WHERE a.application_id = ta.application_id);

Sub-query will return only one expression while using IN OR NOT IN.