问:
Flutter: How scroll programmatically and periodic(from stream)?
I have flutter widget. It is SingleChildScrollView with children + "middle cursor":

I can scroll this list left and right - the cursor always remains in the middle.
Now I need to scroll programmatically the "children" relative to the cursor with a frequency of one second.

I tried adding a timer and a thread and processing this in my widget. Also I added SteamBuilder in my widget, but I get an error in one frame.

My error frame:

My normal frame:

This error occurs after one frame. Any ideas how to fix this - u will be very grateful.

This is my full code:

```<code>    void main() => //runApp(MyApp());
runApp(StartApp());

class StartApp extends StatefulWidget {
  @override
  _StartAppState createState() => _StartAppState();
}

class _StartAppState extends State<StartApp> {
  StreamController<double> _currentPositionController;
  double position = 0;
  Timer _progressTimer;

  void positionUpdate(Timer timer) {
    position += 0.550;
    _currentPositionController.add(position);
  }

  @override
  void initState() {
    super.initState();
    _progressTimer = Timer.periodic(
        Duration(milliseconds: 350), positionUpdate);
    _currentPositionController = StreamController<double>.broadcast();
  }

  @override
  void dispose() {
    _progressTimer?.cancel();
    _currentPositionController?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TmpPage(currentPosition:_currentPositionController.stream ),
      ),
    );
  }
}
</code>```

This is my widget(TmpPage) :

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

class TmpPage extends StatefulWidget {
  final Stream<double> currentPosition;

  const TmpPage({Key key, this.currentPosition}) : super(key: key);
  @override
  _TmpPageState createState() => _TmpPageState();
}

class _TmpPageState extends State<TmpPage> with WidgetsBindingObserver {

  double before = 0;
  double halfWidth;
  double leftPosition;
  ScrollController _controller;

  @override
  void initState() {

    WidgetsBinding.instance.addObserver(this);
    halfWidth =0;
    _controller = ScrollController();
    _controller.addListener(_scrollListener);
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _controller.removeListener(_scrollListener);
    _controller.dispose();
    super.dispose();
  }

  double width = 0.0;
  double height = 0.0;

  @override void didChangeMetrics() {
    setState(() {
      width = window.physicalSize.width;
      height = window.physicalSize.height;
      halfWidth = window.physicalSize.width / 2;
      //halfWidth = (MediaQuery.of(context).size.width) / 2;
      leftPosition = halfWidth;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _getBody(context);
  }

  Widget _getBody(context) {
    if(halfWidth ==0)
      halfWidth = (MediaQuery.of(context).size.width) / 2;
    if (before == 0)
      leftPosition = halfWidth;
    return StreamBuilder<double>(
      stream: widget.currentPosition,
      builder: (context, snapshot) {
        if(snapshot.data !=null && _controller.hasClients){
            _controller.jumpTo(snapshot.data);
          }
        return NotificationListener<ScrollNotification>(
          onNotification: (scrollNotification) {
            if (scrollNotification is ScrollUpdateNotification) {
              var m = scrollNotification.metrics;
              before = m.extentBefore;
              setState(() {
                leftPosition = before;
              });
              return false;
            }
            return false;
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SingleChildScrollView(
                controller: _controller,
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: halfWidth,
                      ),
                      Stack(
                        children: <Widget>[
                          Row(
                            children: List.generate(
                                30,
                                    (i) => Padding(
                                  padding: const EdgeInsets.all(2.0),
                                  child: new Container(
                                    height: 42.0,
                                    width: 42.0,
                                    color: _getColor(i),
                                  ),
                                )).toList(),
                          ),
                          Positioned(
                            left: leftPosition,
                            top: 0,
                            bottom: 0,
                            child: Container(
                              color: Colors.red,
                              width: 2,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: halfWidth,
                      ),
                    ],
                  )),
            ],
          ),
        );
      }
    );
  }

   Color _getColor(int i) {
    if(i<10)
      return Colors.blueGrey;
    if(i<20)
      return Colors.orange;
    if(i<30)
      return Colors.lightBlueAccent;
    else
      return Colors.green;

  }

  void _scrollListener() {
    if (_controller.offset >= _controller.position.maxScrollExtent &&
        !_controller.position.outOfRange) {
      print('end');
      _controller.jumpTo(_controller.offset - 1);
    }
    if (_controller.offset <= _controller.position.minScrollExtent &&
        !_controller.position.outOfRange) {
      print('start');
      _controller.jumpTo(_controller.offset + 1);
    }
  }
}
</code>```

答:
You cannot trigger a build from within the build method, like with setState. Thus, you can wrap any calls to setState with

```<code>WidgetsBinding.instance.addPostFrameCallback((_) {
  // Your code here
});
</code>```

in order to call the code at the end of the frame, after the build method completes.

Body:
I have flutter widget. It is SingleChildScrollView with children + "middle cursor":

I can scroll this list left and right - the cursor always remains in the middle.
Now I need to scroll programmatically the "children" relative to the cursor with a frequency of one second.

I tried adding a timer and a thread and processing this in my widget. Also I added SteamBuilder in my widget, but I get an error in one frame.

My error frame:

My normal frame:

This error occurs after one frame. Any ideas how to fix this - u will be very grateful.

This is my full code:

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

class StartApp extends StatefulWidget {
  @override
  _StartAppState createState() => _StartAppState();
}

class _StartAppState extends State<StartApp> {
  StreamController<double> _currentPositionController;
  double position = 0;
  Timer _progressTimer;

  void positionUpdate(Timer timer) {
    position += 0.550;
    _currentPositionController.add(position);
  }

  @override
  void initState() {
    super.initState();
    _progressTimer = Timer.periodic(
        Duration(milliseconds: 350), positionUpdate);
    _currentPositionController = StreamController<double>.broadcast();
  }

  @override
  void dispose() {
    _progressTimer?.cancel();
    _currentPositionController?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TmpPage(currentPosition:_currentPositionController.stream ),
      ),
    );
  }
}

This is my widget(TmpPage) :

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

class TmpPage extends StatefulWidget {
  final Stream<double> currentPosition;

  const TmpPage({Key key, this.currentPosition}) : super(key: key);
  @override
  _TmpPageState createState() => _TmpPageState();
}

class _TmpPageState extends State<TmpPage> with WidgetsBindingObserver {

  double before = 0;
  double halfWidth;
  double leftPosition;
  ScrollController _controller;

  @override
  void initState() {

    WidgetsBinding.instance.addObserver(this);
    halfWidth =0;
    _controller = ScrollController();
    _controller.addListener(_scrollListener);
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _controller.removeListener(_scrollListener);
    _controller.dispose();
    super.dispose();
  }

  double width = 0.0;
  double height = 0.0;

  @override void didChangeMetrics() {
    setState(() {
      width = window.physicalSize.width;
      height = window.physicalSize.height;
      halfWidth = window.physicalSize.width / 2;
      //halfWidth = (MediaQuery.of(context).size.width) / 2;
      leftPosition = halfWidth;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _getBody(context);
  }

  Widget _getBody(context) {
    if(halfWidth ==0)
      halfWidth = (MediaQuery.of(context).size.width) / 2;
    if (before == 0)
      leftPosition = halfWidth;
    return StreamBuilder<double>(
      stream: widget.currentPosition,
      builder: (context, snapshot) {
        if(snapshot.data !=null && _controller.hasClients){
            _controller.jumpTo(snapshot.data);
          }
        return NotificationListener<ScrollNotification>(
          onNotification: (scrollNotification) {
            if (scrollNotification is ScrollUpdateNotification) {
              var m = scrollNotification.metrics;
              before = m.extentBefore;
              setState(() {
                leftPosition = before;
              });
              return false;
            }
            return false;
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SingleChildScrollView(
                controller: _controller,
                  scrollDirection: Axis.horizontal,
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: halfWidth,
                      ),
                      Stack(
                        children: <Widget>[
                          Row(
                            children: List.generate(
                                30,
                                    (i) => Padding(
                                  padding: const EdgeInsets.all(2.0),
                                  child: new Container(
                                    height: 42.0,
                                    width: 42.0,
                                    color: _getColor(i),
                                  ),
                                )).toList(),
                          ),
                          Positioned(
                            left: leftPosition,
                            top: 0,
                            bottom: 0,
                            child: Container(
                              color: Colors.red,
                              width: 2,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: halfWidth,
                      ),
                    ],
                  )),
            ],
          ),
        );
      }
    );
  }

   Color _getColor(int i) {
    if(i<10)
      return Colors.blueGrey;
    if(i<20)
      return Colors.orange;
    if(i<30)
      return Colors.lightBlueAccent;
    else
      return Colors.green;

  }

  void _scrollListener() {
    if (_controller.offset >= _controller.position.maxScrollExtent &&
        !_controller.position.outOfRange) {
      print('end');
      _controller.jumpTo(_controller.offset - 1);
    }
    if (_controller.offset <= _controller.position.minScrollExtent &&
        !_controller.position.outOfRange) {
      print('start');
      _controller.jumpTo(_controller.offset + 1);
    }
  }
}

Body:
You cannot trigger a build from within the build method, like with setState. Thus, you can wrap any calls to setState with

WidgetsBinding.instance.addPostFrameCallback((_) {
  // Your code here
});

in order to call the code at the end of the frame, after the build method completes.


来源: stackexchange

问:
Sequence is giving already given numbers
I'm using a sequence datasource_id_seq created by hand to create unique table names by concatenating a string with numbers returned by the sequence via select nextval('datasource_id_seq').

The code to create it is on my very first migration:

```<code>create sequence datasource_id_seq;
</code>```

And there's nothing like that again in the whole code base.

I recently stump into a bug that ended being the sequence was giving numbers already given. It was returning values in the 6xx (six hundreds) while we already have tables with names over 3xxx (three thousands).

Reading the docs (https://www.postgresql.org/docs/12/functions-sequence.html) the only thing I could catch that points to a reset in the sequence is:

If a sequence object has been created with default parameters, successive nextval calls will return successive values beginning with 1

So, the only ways to reset a sequence is to recreate it or to use setval(), none of which are in the code base.

My question is: how can happen a sequence resets? What other means are to reset a sequence

答:
With properly working, bug-free PostgreSQL server it is not possible to allocate the same sequence number two or more times. It's not even "returned" in case of a rollback. The only method to manipulate next value is using the functions you've already mentioned.

Look for the problem during deployment of your app. I'd speculate that the sequence got dropped and recreated.

ContentLicense: CC BY-SA 4.0

Body:
I'm using a sequence datasource_id_seq created by hand to create unique table names by concatenating a string with numbers returned by the sequence via select nextval('datasource_id_seq').

The code to create it is on my very first migration:

create sequence datasource_id_seq;

And there's nothing like that again in the whole code base.

I recently stump into a bug that ended being the sequence was giving numbers already given. It was returning values in the 6xx (six hundreds) while we already have tables with names over 3xxx (three thousands).

Reading the docs (https://www.postgresql.org/docs/12/functions-sequence.html) the only thing I could catch that points to a reset in the sequence is:

If a sequence object has been created with default parameters, successive nextval calls will return successive values beginning with 1

So, the only ways to reset a sequence is to recreate it or to use setval(), none of which are in the code base.

My question is: how can happen a sequence resets? What other means are to reset a sequence


问:
docker volume over fuse : Transport endpoint is not connected
So I have this remote folder /mnt/shared mounted with fuse. It is mostly available, except there shall be some disconnections from time to time.

The actual mounted folder /mnt/shared becomes available again when the re-connection happens.

The issue is that I put this folder into a docker volume to make it available to my app: /shared. When I start the container, the volume is available.

But if a disconnection happens in between, while the /mnt/shared repo on the host machine is available, the /shared folder is not accessible from the container, and I get:

```<code>user@machine:~$ docker exec -it e313ec554814 bash
root@e313ec554814:/app# ls /shared
ls: cannot access '/shared': Transport endpoint is not connected
</code>```

In order to get it to work again, the only solution I found is to docker restart e313ec554814, which brings downtime to my app, hence is not an acceptable solution.

So my questions are:

Is this somehow a docker "bug" not to reconnect to the mounted folder when it is available again?

Can I execute this task manually, without having to restart the whole container?

Thanks

答:
I would try the following solution.

If you mount the volume to your docker like so:

```<code>docker run -v /mnt/shared:/shared my-image
</code>```

I would create an intermediate directory /mnt/base/shared and mount it to docker like so:

```<code>docker run -v /mnt/base/shared:/base/shared my-image
</code>```

and I will also adjust my code to refer to the new path or creating a link from /base/shared to /shared inside the container

Explanation:

The problem is that the mounted directory /mnt/shared is probably deleted on host machine, when there is a disconnection and a new directory is created after connection is back. But, the container started running with directory mapping for the old directory which was deleted. By creating an intermediate directory and mapping to it instead you avoid this mapping issue.

Body:
So I have this remote folder /mnt/shared mounted with fuse. It is mostly available, except there shall be some disconnections from time to time.

The actual mounted folder /mnt/shared becomes available again when the re-connection happens.

The issue is that I put this folder into a docker volume to make it available to my app: /shared. When I start the container, the volume is available.

But if a disconnection happens in between, while the /mnt/shared repo on the host machine is available, the /shared folder is not accessible from the container, and I get:

user@machine:~$ docker exec -it e313ec554814 bash
root@e313ec554814:/app# ls /shared
ls: cannot access '/shared': Transport endpoint is not connected

In order to get it to work again, the only solution I found is to docker restart e313ec554814, which brings downtime to my app, hence is not an acceptable solution.

So my questions are:

Is this somehow a docker "bug" not to reconnect to the mounted folder when it is available again?

Can I execute this task manually, without having to restart the whole container?

Thanks

Body:
I would try the following solution.

If you mount the volume to your docker like so:

docker run -v /mnt/shared:/shared my-image

I would create an intermediate directory /mnt/base/shared and mount it to docker like so:

docker run -v /mnt/base/shared:/base/shared my-image

and I will also adjust my code to refer to the new path or creating a link from /base/shared to /shared inside the container

Explanation:

The problem is that the mounted directory /mnt/shared is probably deleted on host machine, when there is a disconnection and a new directory is created after connection is back. But, the container started running with directory mapping for the old directory which was deleted. By creating an intermediate directory and mapping to it instead you avoid this mapping issue.


问:
Unable to connect to Mysql 5.7 running as docker container from docker host using mysql client
After going through the following links from SOF- I still am facing the issue and there is no reasoning or solution available.

References:

Connecting to mysql docker container

Connect to Docker MySQL container from localhost?

Mysql 5.7 is running as container in my local machine. Once the server is up, connecting to the server using root or the new user created fails over localhost/0.0.0.0/127.0.0.1. Even after disabling the firewald, the connectivity failed with the same error.  I might have done something terribly wrong about this connectivity.  Any advice would be helpful.

version: '3.5'
services:
  service:
    image: mysql:5.7
    #build:
    #  context: ./
    #  dockerfile: Dockerfile
    environment:
      MYSQL_USER: user
      MYSQL_PASSWORD: manage
      MYSQL_ROOT_PASSWORD: manage
      MYSQL_DATABASE: testapp
    ports:
      - published: 3306
        target: 3306
```

<p>Following is the output after <strong>docker-compose up -d</strong></p>

<pre class="lang-sh prettyprint-override"><code>docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
45ba02e6e457        mysql:5.7           "docker-entrypoint.s…"   52 seconds ago      Up 50 seconds       0.0.0.0:3306->3306/tcp, 33060/tcp
</code>```

Below are the attempts to connect to the mysql container.

```<code>mysql -u root -h localhost -pmanage
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

mysql -u root -h 0.0.0.0 -pmanage
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

mysql -u root -h 127.0.0.1 -pmanage
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
</code>```

IP of the running container works fine. But this is not a solution as the IP can change with time.

```<code>mysql -u root -h 172.31.0.2 -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.30 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
</code>```

I am not looking for solutions with another docker command. How to connect to mysql container from docker host using mysql client.

答:
You need to use the --protocol=tcp in your connection url.

```<code>mysql -u root -h localhost --protocol=tcp
</code>```

Your mysql is running inside the docker container. So, you have to connect through TCP and local socket is not available for that. This is basically duplicate of this question.

Body:
After going through the following links from SOF- I still am facing the issue and there is no reasoning or solution available.

References:

Connecting to mysql docker container

Connect to Docker MySQL container from localhost?

Mysql 5.7 is running as container in my local machine. Once the server is up, connecting to the server using root or the new user created fails over localhost/0.0.0.0/127.0.0.1. Even after disabling the firewald, the connectivity failed with the same error.  I might have done something terribly wrong about this connectivity.  Any advice would be helpful.

version: '3.5'
services:
  service:
    image: mysql:5.7
    #build:
    #  context: ./
    #  dockerfile: Dockerfile
    environment:
      MYSQL_USER: user
      MYSQL_PASSWORD: manage
      MYSQL_ROOT_PASSWORD: manage
      MYSQL_DATABASE: testapp
    ports:
      - published: 3306
        target: 3306

Following is the output after docker-compose up -d

docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
45ba02e6e457        mysql:5.7           "docker-entrypoint.s…"   52 seconds ago      Up 50 seconds       0.0.0.0:3306->3306/tcp, 33060/tcp

Below are the attempts to connect to the mysql container.

mysql -u root -h localhost -pmanage
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

mysql -u root -h 0.0.0.0 -pmanage
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

mysql -u root -h 127.0.0.1 -pmanage
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

IP of the running container works fine. But this is not a solution as the IP can change with time.

mysql -u root -h 172.31.0.2 -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.30 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

I am not looking for solutions with another docker command. How to connect to mysql container from docker host using mysql client.

Body:
You need to use the --protocol=tcp in your connection url.

mysql -u root -h localhost --protocol=tcp

Your mysql is running inside the docker container. So, you have to connect through TCP and local socket is not available for that. This is basically duplicate of this question.


问:
Utilities/Platform missing for react-native
I trying to run expo-cli in browser mode.

But there is the error:

Module not found: Can't resolve '../../Utilities/Platform' in
  '.../node_modules/react-native/Libraries/Core/Timers'.

I tried also to look manually for this module but no luck.

What can I do to make expo client works in web browsers?

答: Using a module resolver plugin to resolve dependencies to the React Native Web exports might help you. React-native-viewpager has an issue with resolving relative paths. See this comment and this entire thread: https://github.com/expo/web-examples/issues/73#issuecomment-621078860 and sample repo here: https://github.com/ricardoribas/expo-react-native-web</p>


问:
Cannot clone git from Azure DevOps using PAT
I cannot clone a simple repository from Azure DevOps.
OS: Ubuntu 18.10

I do this:

Got to Azure DevOps

Click on the top right corner on my user name

Go to the security tab

Create a PAT with all the scope (to be sure there is no scope
problem)

Copy the PAT to the clipboard

Paste the PAT somewhere else to confirm the PAT has been copied correctly (I know... not safe but that is out of the scope of this question)

Go to my console

Issue: git clone https://myorganization.visualstudio.com/myproject/_git/myrepo/

I enter the user name and the password (the PAT)

I keep getting this message from Git:
fatal: Authentication failed for 'https://myorganization.visualstudio.com/myproject/_git/myrepo/'

I was reading the solutions of other people but none worked for me.
I also tried this:

Pass the token in the form https://usename:token@myorganization.visualstudio.com/myproject/_git/myrepo/ I am really surprised people say this worked... for my git complains
because believes the : means the port.

Tried to
activate/deactivate credential manager of git  * Tried on Windows and
Ubuntu.

Tried to activate and deactivate the simple credentials.

Tried with the simple credentials, i.e. username + password.

Tried to put my user name in https://username@....

Tried to use SSH

Tried to use the http.extraHeader in the git command with the header being ```Authorization: Basic Base64Encoded(uname:PAT)```

Tried to use the http.extraHeader in the git command with the header being ```Authorization: Bearer PAT```

Tried to use the VSCode client. It generates the PAT by itself but still cannot authenticate and clone.

Tried to use the Rider VSTS client. It generates the PAT by itself but still cannot authenticate and clone.

Tried to use the git credentials manager for Linux. It promps the Code and when we authenticate in the browser, it generates a PAT successfully. Still, after that cannot authenticate.

Any clue why this is not working?

答:
Git http.extraheader & bearer

YAML style Pipelines can use the preset variable System.AccessToken.  After examining the formal 'Checkout ...' step at the beginning of the Pipeline I found this step to work in my script:

```<code>- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'git -c http.extraheader="AUTHORIZATION: bearer $(System.AccessToken)" clone --depth 1 https://my-org@dev.azure.com/my-org/my-proj/_git/my-repo'
</code>```

Note that Azure DevOps job authorization scope may affect this

Body:
I cannot clone a simple repository from Azure DevOps.
OS: Ubuntu 18.10

I do this:

Got to Azure DevOps

Click on the top right corner on my user name

Go to the security tab

Create a PAT with all the scope (to be sure there is no scope
problem)

Copy the PAT to the clipboard

Paste the PAT somewhere else to confirm the PAT has been copied correctly (I know... not safe but that is out of the scope of this question)

Go to my console

Issue: git clone https://myorganization.visualstudio.com/myproject/_git/myrepo/

I enter the user name and the password (the PAT)

I keep getting this message from Git:
fatal: Authentication failed for 'https://myorganization.visualstudio.com/myproject/_git/myrepo/'

I was reading the solutions of other people but none worked for me.
I also tried this:

Pass the token in the form https://usename:token@myorganization.visualstudio.com/myproject/_git/myrepo/ I am really surprised people say this worked... for my git complains
because believes the : means the port.

Tried to
activate/deactivate credential manager of git  * Tried on Windows and
Ubuntu.

Tried to activate and deactivate the simple credentials.

Tried with the simple credentials, i.e. username + password.

Tried to put my user name in https://username@....

Tried to use SSH

Tried to use the http.extraHeader in the git command with the header being
Authorization: Basic Base64Encoded(uname:PAT)

Tried to use the http.extraHeader in the git command with the header being
Authorization: Bearer PAT

Tried to use the VSCode client. It generates the PAT by itself but still cannot authenticate and clone.

Tried to use the Rider VSTS client. It generates the PAT by itself but still cannot authenticate and clone.

Tried to use the git credentials manager for Linux. It promps the Code and when we authenticate in the browser, it generates a PAT successfully. Still, after that cannot authenticate.

Any clue why this is not working?

Body:
Git http.extraheader & bearer

YAML style Pipelines can use the preset variable System.AccessToken.  After examining the formal 'Checkout ...' step at the beginning of the Pipeline I found this step to work in my script:

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'git -c http.extraheader="AUTHORIZATION: bearer $(System.AccessToken)" clone --depth 1 https://my-org@dev.azure.com/my-org/my-proj/_git/my-repo'

Note that Azure DevOps job authorization scope may affect this


答:
Pandas is good for uniform columnar data. If your input isn't uniform, you can preprocess it and then load the dataframe. This one is easy, all you need to do is scan for grid headers and remove them. Since the data itself is numeric, separated by whitespace, a simple split will parse it. This example creates a list but if the dataset is large, it may be reasonable to write to an intermediate file instead.</p>

```<code>import csv
import re
import pandas as  pd

grid_re = re.compile(r"Grid-ref=\s*(\d+),(\d+)")

with open('test.csv') as fobj:
    table = []
    try:
        while True:
            # find next block
            for line in fobj:
                match = grid_re.search(line)
                if match:
                    grid_xy = list(match.groups())
                    break
            else:
                raise StopIteration()
            for _ in range(10):
                line = next(fobj)
                # add row plus grid columns
                table.append(line.strip().split() + grid_xy)
    except StopIteration:
        pass

df = pd.DataFrame(table)
print(df)
</code>```

Title: read csv and Iterate through 10 row blocks

Body:
I am trying to read a CSV file and Iterate through 10-row blocks.
The data is quite unusual, with two columns and 10-row blocks.

57485 rows x 2 columns in the format below:

Grid-ref=   1,148
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630
 3020 2820 3040 2880 1740 1360  980  990 1410 1770 2580 2630

Grid-ref=   1,311
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450
  490  290  280  230  200  250  440  530  460  420  530  450

Grid-ref=   1,312
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410
  460  280  260  220  190  240  430  520  450  400  520  410

Every 10 rows consist of a grid reference and two records X/Y ref.
The grid reference and X value is in column 1, the Y value is in column 2, and then 9 rows with 12 columns, in column one.

The blocks (x) 0 - 9, represent months (Jan - December
The blocks (y) 0 - 9, represent years (1991-2000)

So for 0, is 1991
3020 is January 1991, 2820 is February 1991

Grid-ref = 1 (X),148 (Y)

The code below reads 10 rows, but keeps repeating the first row in all following 10-row blocks??

I don't understand why it keeps repeating the first row??
Any suggestions to resolve this would be appreciated..

## Python 3.6

## Read in the datasets (they are in CSV format)
data = pd.read_csv('cru-ts-2-10-1991-2000-cutdown.csv', skiprows=5, na_values =  [-999] )

## View data    >> 57485 rows x 2 columns
#print(data)
#print(len(data))   ## len = 57485

## header = pd.MultiIndex.from_product([['Grid-ref', 'Xref', 'Yref'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] ])

# df = pd.DataFrame(np.random.randn(10, 11),
# index=['1991','1992','1993','1994','1995', '1996', '1997', '1998', '1999', '2000', '2001'],
#  columns=header)

# print(data.head(10)) ## prints chunks of 10 rows

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

for group in chunker(data, 10):
    print(group)

The first two block:

                                      Grid-ref=   1   148
0   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
1   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
2   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
3   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
4   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
5   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
6   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
7   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
8   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
9   3020 2820 3040 2880 1740 1360  980  990 1410 ...   NaN
                                        Grid-ref=   1    148
10                                      Grid-ref=   1  311.0
11    490  290  280  230  200  250  440  530  460 ...    NaN
12    490  290  280  230  200  250  440  530  460 ...    NaN
13    490  290  280  230  200  250  440  530  460 ...    NaN
14    490  290  280  230  200  250  440  530  460 ...    NaN
15    490  290  280  230  200  250  440  530  460 ...    NaN
16    490  290  280  230  200  250  440  530  460 ...    NaN
17    490  290  280  230  200  250  440  530  460 ...    NaN
18    490  290  280  230  200  250  440  530  460 ...    NaN
19    490  290  280  230  200  250  440  530  460 ...    NaN

Body:
Pandas is good for uniform columnar data. If your input isn't uniform, you can preprocess it and then load the dataframe. This one is easy, all you need to do is scan for grid headers and remove them. Since the data itself is numeric, separated by whitespace, a simple split will parse it. This example creates a list but if the dataset is large, it may be reasonable to write to an intermediate file instead.

import csv
import re
import pandas as  pd

grid_re = re.compile(r"Grid-ref=\s*(\d+),(\d+)")

with open('test.csv') as fobj:
    table = []
    try:
        while True:
            # find next block
            for line in fobj:
                match = grid_re.search(line)
                if match:
                    grid_xy = list(match.groups())
                    break
            else:
                raise StopIteration()
            for _ in range(10):
                line = next(fobj)
                # add row plus grid columns
                table.append(line.strip().split() + grid_xy)
    except StopIteration:
        pass

df = pd.DataFrame(table)
print(df)


问:
Spring Boot Security - Use token from Cookies if Authorization header missing
I currently authenticate my requests against the JWK of my authorization server.
I'm using the spring-boot-starter-oauth2-resource-server package on spring-boot 2.3.
The JWT is taken out from the Authorization: Bearer <token> header and validated against the JWK endpoint.
My security config looks like this:

SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  protected Environment env;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt();
  }
}
```

<p>application.properties</p>

```spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://auth.work.com/v1/jwk
```

<p>External users don't have the <code>Authorization: ...</code> header in their requests, but instead have the following 2 cookies that make up the JWT:</p>

```auth.token_type = Bearer
auth.access_token = <token>
```

Is there a way to extract the JWT from the cookies and validate against the auth server if the the Authorization: ... header is missing?
Could I extract the cookies and add a header to the request before it tries to authorize?
Or it could even be a second method in the authentication chain.

答:
I think you may use Custom Filter, intercept request and fetch cookies from HttpServletRequest.

```<code>@Override
public void doFilter(
  ServletRequest request,
  ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
    Cookie[] cookies = request.getCookies();
    // Your validation logic
}
</code>```

Just add it to Spring Security filters chain.

More details how to do it here: https://www.baeldung.com/spring-security-custom-filter

Body:
I currently authenticate my requests against the JWK of my authorization server.
I'm using the spring-boot-starter-oauth2-resource-server package on spring-boot 2.3.
The JWT is taken out from the Authorization: Bearer <token> header and validated against the JWK endpoint.
My security config looks like this:

SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  protected Environment env;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests().antMatchers("/logs").permitAll();
    http.authorizeRequests().antMatchers("/", "/api/**").authenticated();
    http.oauth2ResourceServer().jwt();
  }
}

application.properties

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://auth.work.com/v1/jwk

External users don't have the Authorization: ... header in their requests, but instead have the following 2 cookies that make up the JWT:

auth.token_type = Bearer
auth.access_token = <token>

Is there a way to extract the JWT from the cookies and validate against the auth server if the the Authorization: ... header is missing?
Could I extract the cookies and add a header to the request before it tries to authorize?
Or it could even be a second method in the authentication chain.

Body:
I think you may use Custom Filter, intercept request and fetch cookies from HttpServletRequest.

@Override
public void doFilter(
  ServletRequest request,
  ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
    Cookie[] cookies = request.getCookies();
    // Your validation logic
}

Just add it to Spring Security filters chain.

More details how to do it here: https://www.baeldung.com/spring-security-custom-filter


问:
In ASP.NET Core 2.2, How to create a custom Registration Form
Seems like in ASP.NET Core 2.2, authentication is very different. For example, I want to customize both my Registration and Login forms and I can't find them in my project I scaffolded. The work, and clearly I can see them being called with this anchor tag helper:

```<code><li class="nav-item">
    <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
</li>
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
</code>```

in loginpartial.cshtml1

What confuses me is  where is the view page /Account/Register and how do I modify it? Where are the model classes I might want to update? All those things use to be in the AccountController but that's now gone.

答:
In dot net core 3.1, you have to override registration and login page as they are embedded by default. here is a step by step:

Right-click on project

Add -> New Scaffolded item..

From a left panel, choose: Identity

Select Identity

Add

A popup window will appear. You can choose a page you wish to override

Then you will get the custom pages you selected inside
AccountController

Body:
Seems like in ASP.NET Core 2.2, authentication is very different. For example, I want to customize both my Registration and Login forms and I can't find them in my project I scaffolded. The work, and clearly I can see them being called with this anchor tag helper:

    Register

    Login

in loginpartial.cshtml1

What confuses me is  where is the view page /Account/Register and how do I modify it? Where are the model classes I might want to update? All those things use to be in the AccountController but that's now gone.


问:
How can I combine these HTML files in order to run them at the same time on a single webpage?
My knowledge of HTML/Javascript is extremely limited. I was working with this code I found online, and wanted to combine the two programs so that I had the brickbreaker game on top, and the live data updating beneath it. The two activities don't need to be linked, but want them to appear on the same webpage, both within view without having to scroll. I appreciate any help!

```<code><!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {

var dataPoints1 = [];
var dataPoints2 = [];
var dataPoints3 = [];

var chart = new CanvasJS.Chart("chartContainer", {
    zoomEnabled: true,
    title: {
        text: "Protein Activity"
    },
    axisX: {
        title: "chart updates every 1 secs"
    },
    axisY:{
        prefix: "",
        includeZero: false
    },
    toolTip: {
        shared: true
    },
    legend: {
        cursor:"pointer",
        verticalAlign: "top",
        fontSize: 22,
        fontColor: "dimGrey",
        itemclick : toggleDataSeries
    },
    data: [{
        type: "line",
        xValueType: "dateTime",
        yValueFormatString: "####.00",
        xValueFormatString: "hh:mm:ss",
        showInLegend: true,
        name: "Blue Protein",
        dataPoints: dataPoints1
        },
        {
            type: "line",
            xValueType: "dateTime",
            yValueFormatString: "####.00",
            xValueFormatString: "hh:mm:ss",
            showInLegend: true,
            name: "Red Protein" ,
            dataPoints: dataPoints2
    },
    {
        type: "line",
        xValueType: "dateTime",
        yValueFormatString: "####.00",
        xValueFormatString: "hh:mm:ss",
        showInLegend: true,
        name: "Green Protein" ,
        dataPoints: dataPoints3
}]
});

function toggleDataSeries(e) {
    if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
        e.dataSeries.visible = false;
    }
    else {
        e.dataSeries.visible = true;
    }
    chart.render();
}
//initial interval was 3000 (every 3 seconds)
var updateInterval = 1000; // 1 second interval 1000
// initial value originally 600 and 605
var yValue1 = 0;
var yValue2 = 0
var yValue3 = 0;

var time = new Date;
// starting at 9.30 am

time.setMinutes(00);
time.setSeconds(00);

function updateChart(count) {

    count = count || 1;
    var deltaY1, deltaY2, deltaY3;
    for (var i = 0; i < count; i++) {
        time.setTime(time.getTime() + updateInterval);
        // dropping the parenthetical manipulators
        // the change is between 0 and 1 ... place holder until we connect with the game
        deltaY1 =  Math.random() ;
        deltaY2 =  Math.random();
        deltaY3 =  Math.random();

    // adding random value and rounding it to two digits.
    yValue1 = Math.round((yValue1 + deltaY1)*100)/100;
    yValue2 = Math.round((yValue2 + deltaY2)*100)/100;
    yValue3 = Math.round((yValue3 + deltaY3)*100)/100;
    // pushing the new values
    dataPoints1.push({
        x: time.getTime(),
        y: yValue1
    });
    dataPoints2.push({
        x: time.getTime(),
        y: yValue2
    });
    dataPoints3.push({
        x: time.getTime(),
        y: yValue3
    });
    }

    // updating legend text with  updated with y Value
    chart.options.data[0].legendText = " Blue Protein:  " + yValue1;
    chart.options.data[1].legendText = " Red Protein:  " + yValue2;
    chart.options.data[2].legendText = " Green Protein:  " + yValue3;
    chart.render();

}
// generates first set of dataPoints
updateChart(0);
setInterval(function(){updateChart()}, updateInterval);

}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
</code>```

and

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>
    <style>
        * { padding: 0; margin: 0; }
        canvas { background: #eee; display: block; margin: 0 auto; }
    </style>
</head>
<body>

<canvas id="myCanvas" width="480" height="320"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
var brickRowCount = 5;
var brickColumnCount = 3;
var brickWidth = 75;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var score = 0;
var lives = 3;

var bricks = [];
for(var c=0; c<brickColumnCount; c++) {
  bricks[c] = [];
  for(var r=0; r<brickRowCount; r++) {
    bricks[c][r] = { x: 0, y: 0, status: 1 };
  }
}

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
document.addEventListener("mousemove", mouseMoveHandler, false);

function keyDownHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = true;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.key == "Right" || e.key == "ArrowRight") {
        rightPressed = false;
    }
    else if(e.key == "Left" || e.key == "ArrowLeft") {
        leftPressed = false;
    }
}

function mouseMoveHandler(e) {
  var relativeX = e.clientX - canvas.offsetLeft;
  if(relativeX > 0 && relativeX < canvas.width) {
    paddleX = relativeX - paddleWidth/2;
  }
}
function collisionDetection() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      var b = bricks[c][r];
      if(b.status == 1) {
        if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
          dy = -dy;
          b.status = 0;
          score++;
          if(score == brickRowCount*brickColumnCount) {
            alert("YOU WIN, CONGRATS!");
            document.location.reload();
          }
        }
      }
    }
  }
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(x, y, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}
function drawPaddle() {
  ctx.beginPath();
  ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}
function drawBricks() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      if(bricks[c][r].status == 1) {
        var brickX = (r*(brickWidth+brickPadding))+brickOffsetLeft;
        var brickY = (c*(brickHeight+brickPadding))+brickOffsetTop;
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
      }
    }
  }
}
function drawScore() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Score: "+score, 8, 20);
}
function drawLives() {
  ctx.font = "16px Arial";
  ctx.fillStyle = "#0095DD";
  ctx.fillText("Lives: "+lives, canvas.width-65, 20);
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBricks();
  drawBall();
  drawPaddle();
  drawScore();
  drawLives();
  collisionDetection();

  if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
    dx = -dx;
  }
  if(y + dy < ballRadius) {
    dy = -dy;
  }
  else if(y + dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
      dy = -dy;
    }
    else {
      lives--;
      if(!lives) {
        alert("GAME OVER");
        document.location.reload();
      }
      else {
        x = canvas.width/2;
        y = canvas.height-30;
        dx = 3;
        dy = -3;
        paddleX = (canvas.width-paddleWidth)/2;
      }
    }
  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
  requestAnimationFrame(draw);
}

draw();
</script>

</body>
</html>
</code>```

答:
JavaScript uses canvas or div elements for showing codes. You must put in body element:

```<code><canvas id="myCanvas" width="480" height="320"></canvas>
</code>```

and

```<code><div id="chartContainer" style="height: 300px; width: 100%;"></div>
</code>```

And if you don't have same function and variable names, you can add all the codes between

Body:
My knowledge of HTML/Javascript is extremely limited. I was working with this code I found online, and wanted to combine the two programs so that I had the brickbreaker game on top, and the live data updating beneath it. The two activities don't need to be linked, but want them to appear on the same webpage, both within view without having to scroll. I appreciate any help!

<!DOCTYPE HTML>

and

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Gamedev Canvas Workshop</title>

<canvas id="myCanvas" width="480" height="320"></canvas>

Body:
JavaScript uses canvas or div elements for showing codes. You must put in body element:

<canvas id="myCanvas" width="480" height="320"></canvas>

and

<div id="chartContainer" style="height: 300px; width: 100%;"></div>

And if you don't have same function and variable names, you can add all the codes between <script> and <script>.

Your screen resolution is another problem. You can see "width" and "height" variables in <canvas> and <div> elements. If your screen resolution is enough for sum of heights (I think, it must be) you will see in one page two of them.


问:
Validation with html form only gives if statement
No matter how many characters I enter, it only gives the if statement and not the else.
is there a typo I entered somewhere I am not seeing, or does the function not work if there are two inputs?

function valid_Function(){
    var x, text;

    x = document.getElementById("name").value;

    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }
    document.getElementById("valid").innerHTML = text;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>form input {
    display: block;
    margin-top: 10px;
}
form [type="submit"] {
    padding: 5px;
    border-radius: 5px;
    border: none;
    background: skyblue;
    transition: .5s ease;
}
form [type="submit"]:hover {
    box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}</code>```

<form action="#">
        <input for="fname" id="name" placeholder="First Name" type="text">
        <input for="lname" id="name" placeholder="Last Name" type="text">
        <input onclick="valid_Function()" type="submit" value="Submit">
    </form>

```

答:
Why not a simple truthy check?

```<code>if (!x) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }
</code>```

And, if you just want to make sure the length remains less than 10, then

```<code> if (!x || x.length> 10) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }
</code>```

Body:
No matter how many characters I enter, it only gives the if statement and not the else.
is there a typo I entered somewhere I am not seeing, or does the function not work if there are two inputs?

function valid_Function(){
    var x, text;

    x = document.getElementById("name").value;

    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }
    document.getElementById("valid").innerHTML = text;
}

form input {
    display: block;
    margin-top: 10px;
}
form [type="submit"] {
    padding: 5px;
    border-radius: 5px;
    border: none;
    background: skyblue;
    transition: .5s ease;
}
form [type="submit"]:hover {
    box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}

<form action="#">
        <input for="fname" id="name" placeholder="First Name" type="text">
        <input for="lname" id="name" placeholder="Last Name" type="text">
        <input onclick="valid_Function()" type="submit" value="Submit">
    </form>

Body:
Why not a simple truthy check?

if (!x) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }

And, if you just want to make sure the length remains less than 10, then

 if (!x || x.length> 10) {
        text = "Input not valid";
    }
    else {
        text = "Input OK";
    }


问:
how to specify data file in adobe live cycle designer?
I am following the documentation tutorials point at which I am stuck this tutorial has given how to attach the pdf with the data file in preview mode. I have successfully done it but , I don't know how to do it for the time when we are going to open pdf. I mean whenever I open the generated pdf in adobe acrobat independently the data doesn't appear in the fields. Please guide how to do it.</p>

答:
The tutorial points towards using AEM Designer for previewing your PDF design with a sample data file. You can only do this in the Preview tab of AEM Designer. Once you finalize the PDF and open it up with Adobe Acrobat, it will show you the finalized PDF and will NOT have the sample data that you used for testing purposes.

If you are looking to import data into the finalized PDF, use Acrobat Pro:

Open the PDF form into which you want to import data. Choose Tools > Prepare Form.

Choose More > Import Data. In the Select File
Containing Form Data dialog box, select a format in File Of Type corresponding to the data file you want to import.

Reference link for the operation Above: https://helpx.adobe.com/ca/acrobat/using/collecting-pdf-form-data.html


问:
Filter Database values to set string format
I am trying to filter my database values that matches my condition.

Here is code:

```<code>con = new SqlConnect();
con.SqlQuery("Select * from DeductionInfo where [IS Percentage] = @yes");
con.cmd.Parameters.AddWithValue("@yes", "' Yes '");

sdr = con.cmd.ExecuteReader();

if (sdr.Read().ToString() == "Yes")
{
    ii.SubItems[2].Text = string.Format("{0:C}", Convert.ToDouble(ii.SubItems[2].Text.ToString()));
}
else
{
    ii.SubItems[2].Text = string.Format("{0:P0}", Convert.ToDouble(ii.SubItems[2].Text.ToString()));
}

con.cmd.Connection.Close();
</code>```

But the output is not what I want:

I want the values to be formatted to Dollar sign if the condition is "No" and Percent if the conditions is "Yes". Can I have a help on this? Thanks

答:
Here is the answer to my own question. I took it out inside the foreach loop and made a for loop.

```<code>      con = new SqlConnect();
        con.SqlQuery("Select * from DeductionInfo order by [Deduction Title] ASC");
        sda = new SqlDataAdapter(con.cmd);
        ds = new DataSet();
        sda.Fill(ds);
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            if (ds.Tables[0].Rows[i].ItemArray[3].ToString() == "Yes")
            {
                lvUserManagement.Items[i].SubItems[2].Text = string.Format("{0:P0}", Convert.ToDouble(lvUserManagement.Items[i].SubItems[2].Text.ToString()));
            }
            else if (ds.Tables[0].Rows[i].ItemArray[3].ToString() == "No")
            {

                lvUserManagement.Items[i].SubItems[2].Text = string.Format("{0:C}", Convert.ToDouble(lvUserManagement.Items[i].SubItems[2].Text.ToString()));
            }
        }
        con.cmd.Connection.Close();
</code>```

enter image description here

Body:
I am trying to filter my database values that matches my condition.

Here is code:

con = new SqlConnect();
con.SqlQuery("Select * from DeductionInfo where [IS Percentage] = @yes");
con.cmd.Parameters.AddWithValue("@yes", "' Yes '");

sdr = con.cmd.ExecuteReader();

if (sdr.Read().ToString() == "Yes")
{
    ii.SubItems[2].Text = string.Format("{0:C}", Convert.ToDouble(ii.SubItems[2].Text.ToString()));
}
else
{
    ii.SubItems[2].Text = string.Format("{0:P0}", Convert.ToDouble(ii.SubItems[2].Text.ToString()));
}

con.cmd.Connection.Close();

But the output is not what I want:

I want the values to be formatted to Dollar sign if the condition is "No" and Percent if the conditions is "Yes". Can I have a help on this? Thanks

Body:
Here is the answer to my own question. I took it out inside the foreach loop and made a for loop.

      con = new SqlConnect();
        con.SqlQuery("Select * from DeductionInfo order by [Deduction Title] ASC");
        sda = new SqlDataAdapter(con.cmd);
        ds = new DataSet();
        sda.Fill(ds);
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            if (ds.Tables[0].Rows[i].ItemArray[3].ToString() == "Yes")
            {
                lvUserManagement.Items[i].SubItems[2].Text = string.Format("{0:P0}", Convert.ToDouble(lvUserManagement.Items[i].SubItems[2].Text.ToString()));
            }
            else if (ds.Tables[0].Rows[i].ItemArray[3].ToString() == "No")
            {

                lvUserManagement.Items[i].SubItems[2].Text = string.Format("{0:C}", Convert.ToDouble(lvUserManagement.Items[i].SubItems[2].Text.ToString()));
            }
        }
        con.cmd.Connection.Close();

enter image description here


问:
Python QT findChildren does not find any children from UI file
I have a UI file like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>RoverPlanner</class>
 <widget class="QWidget" name="RoverPlanner">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>752</width>
    <height>555</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>RoverPlanner</string>
  </property>
  <widget class="QWidget" name="horizontalLayoutWidget_6">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>10</y>
     <width>641</width>
     <height>501</height>
    </rect>
   </property>
   <layout class="QHBoxLayout" name="hl_rover_planner">
    <item>
     <layout class="QVBoxLayout" name="vl_path_config">
      <item>
       <layout class="QHBoxLayout" name="hl_rover_select">
        <item>
         <widget class="QLabel" name="lbl_rover">
          <property name="text">
           <string>Rover : </string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QComboBox" name="cb_rover">
          <item>
           <property name="text">
            <string>Husky</string>
           </property>
          </item>
          <item>
           <property name="text">
            <string>ArgoJ5</string>
           </property>
          </item>
          <item>
           <property name="text">
            <string>Husky (Simulated)</string>
           </property>
          </item>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_path_creator">
        <item>
         <widget class="QLabel" name="lbl_path_creator">
          <property name="text">
           <string>Path Creator</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QPushButton" name="btn_add_to_path">
          <property name="text">
           <string>Add to path</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_segment_options">
        <item>
         <layout class="QVBoxLayout" name="vl_segment_type">
          <item>
           <widget class="QRadioButton" name="radio_circle">
            <property name="text">
             <string>Circle</string>
            </property>
            <property name="checked">
             <bool>true</bool>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QRadioButton" name="radio_line">
            <property name="text">
             <string>Line</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QVBoxLayout" name="vl_segment_extra_options">
          <item>
           <widget class="QCheckBox" name="chk_backwards">
            <property name="text">
             <string>Backwards</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QCheckBox" name="chk_clockwise">
            <property name="text">
             <string>Clockwise</string>
            </property>
            <property name="checked">
             <bool>true</bool>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_radius">
        <item>
         <widget class="QLabel" name="lbl_radius">
          <property name="text">
           <string>Circle Radius (m)</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QDoubleSpinBox" name="spin_radius">
          <property name="singleStep">
           <double>0.010000000000000</double>
          </property>
          <property name="value">
           <double>1.000000000000000</double>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_arc_angle">
        <item>
         <widget class="QLabel" name="lbl_arc_angle">
          <property name="text">
           <string>Arc Angle (rad)</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QDoubleSpinBox" name="spin_arc_angle">
          <property name="decimals">
           <number>5</number>
          </property>
          <property name="singleStep">
           <double>0.010000000000000</double>
          </property>
          <property name="value">
           <double>0.785400000000000</double>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QVBoxLayout" name="vl_segments">
      <item>
       <widget class="QLabel" name="lbl_path">
        <property name="text">
         <string>Paths</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QTreeView" name="tree_paths"/>
      </item>
      <item>
       <layout class="QHBoxLayout" name="horizontalLayout">
        <item>
         <widget class="QPushButton" name="btn_save_paths">
          <property name="text">
           <string>Save Paths</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QPushButton" name="btn_load_paths">
          <property name="text">
           <string>Load Paths</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

</code>```

And some Python code below, which is for an RQT ROS plugin.

```<code>
import os
import rospy
import rospkg
from PySide2.QtWidgets import QTreeView, QPushButton, QFileDialog
from python_qt_binding import loadUi

from qt_gui.plugin import Plugin
from python_qt_binding.QtWidgets import QWidget
from argparse import ArgumentParser

def get_file():
    print("Hello World!")
    dlg = QFileDialog()
    dlg.setFileMode(QFileDialog.AnyFile)
    dlg.setFilter("XML files (*.xml)")

    if dlg.exec_():
        filenames = dlg.selectedFiles()
        f = open(filenames[0], 'r')

        with f:
            data = f.read()
            # self.contents.setText(data)

class RoverPlanner(Plugin):
    def __init__(self, context):
        super(RoverPlanner, self).__init__(context)
        self.setObjectName('RoverPlanner')
        parser = ArgumentParser()
        parser.add_argument("-q", "--quiet", action="store_true",
                            dest="quiet",
                            help="Put plugin in silent mode")
        args, unknowns = parser.parse_known_args(context.argv())
        if not args.quiet:
            print('arguments: ', args)
            print('unknowns: ', unknowns)

        self.widget = QWidget()
        ui_file = os.path.join(rospkg.RosPack().get_path('cuarl-rover-planner'), 'resource', 'rover_planner_widget.ui')
        loadUi(ui_file, self.widget)
        self.widget.setObjectName('RoverPlannerUI')
        # Show widget.windowTitle on left-top of each plugin (when
        # it's set in widget). This is useful when you open multiple
        # plugins at once. Also if you open multiple instances of your
        # plugin at once, these lines add number to make it easy to
        # tell from pane to pane.
        if context.serial_number() > 1:
            self.widget.setWindowTitle(self.widget.windowTitle() + (' (%d)' % context.serial_number()))
        # Add widget to the user interface
        context.add_widget(self.widget)
        self.tree_paths = self.widget.findChild(QTreeView)
        self.btn_load_paths = self.widget.findChildren(QPushButton)
        print(self.tree_paths)
        print(self.btn_load_paths)

    def shutdown_plugin(self):
        # TODO unregister all publishers here
        pass

    def save_settings(self, plugin_settings, instance_settings):
        # TODO save intrinsic configuration, usually using:
        # instance_settings.set_value(k, v)
        pass

    def restore_settings(self, plugin_settings, instance_settings):
        # TODO restore intrinsic configuration, usually using:
        # v = instance_settings.value(k)
        pass
</code>```

According to the documentation, it seems that my code should find these children. But the output of this code is

```<code>('arguments: ', Namespace(quiet=False))
('unknowns: ', [])
None
[]
</code>```

I don't know if I'm not using the findChildren/findChild functions correctly or there's something that I am missing

答:
I ever encountered a similar problem and the cause was that the library used some wrapper like python_qt_binding but another part of the code used PyQt5 or PySide2. Why does that happen? because wrappers create new classes that use the same code base but in the end they are different classes.

My recommendation is that if you are going to use python_qt_binding then no longer use pyqt5 or pyside2 directly but rather the wrapper, in your case you should use the following:

```<code>import os

from argparse import ArgumentParser

import rospy
import rospkg

from qt_gui.plugin import Plugin

from python_qt_binding.QtWidgets import QWidget, <b>QTreeView, QPushButton, QFileDialog</b>
from python_qt_binding import loadUi

# ....</code>```

Body:
I have a UI file like this

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>RoverPlanner</class>
 <widget class="QWidget" name="RoverPlanner">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>752</width>
    <height>555</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>RoverPlanner</string>
  </property>
  <widget class="QWidget" name="horizontalLayoutWidget_6">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>10</y>
     <width>641</width>
     <height>501</height>
    </rect>
   </property>
   <layout class="QHBoxLayout" name="hl_rover_planner">
    <item>
     <layout class="QVBoxLayout" name="vl_path_config">
      <item>
       <layout class="QHBoxLayout" name="hl_rover_select">
        <item>
         <widget class="QLabel" name="lbl_rover">
          <property name="text">
           <string>Rover : </string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QComboBox" name="cb_rover">
          <item>
           <property name="text">
            <string>Husky</string>
           </property>
          </item>
          <item>
           <property name="text">
            <string>ArgoJ5</string>
           </property>
          </item>
          <item>
           <property name="text">
            <string>Husky (Simulated)</string>
           </property>
          </item>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_path_creator">
        <item>
         <widget class="QLabel" name="lbl_path_creator">
          <property name="text">
           <string>Path Creator</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QPushButton" name="btn_add_to_path">
          <property name="text">
           <string>Add to path</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_segment_options">
        <item>
         <layout class="QVBoxLayout" name="vl_segment_type">
          <item>
           <widget class="QRadioButton" name="radio_circle">
            <property name="text">
             <string>Circle</string>
            </property>
            <property name="checked">
             <bool>true</bool>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QRadioButton" name="radio_line">
            <property name="text">
             <string>Line</string>
            </property>
           </widget>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QVBoxLayout" name="vl_segment_extra_options">
          <item>
           <widget class="QCheckBox" name="chk_backwards">
            <property name="text">
             <string>Backwards</string>
            </property>
           </widget>
          </item>
          <item>
           <widget class="QCheckBox" name="chk_clockwise">
            <property name="text">
             <string>Clockwise</string>
            </property>
            <property name="checked">
             <bool>true</bool>
            </property>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_radius">
        <item>
         <widget class="QLabel" name="lbl_radius">
          <property name="text">
           <string>Circle Radius (m)</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QDoubleSpinBox" name="spin_radius">
          <property name="singleStep">
           <double>0.010000000000000</double>
          </property>
          <property name="value">
           <double>1.000000000000000</double>
          </property>
         </widget>
        </item>
       </layout>
      </item>
      <item>
       <layout class="QHBoxLayout" name="hl_arc_angle">
        <item>
         <widget class="QLabel" name="lbl_arc_angle">
          <property name="text">
           <string>Arc Angle (rad)</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QDoubleSpinBox" name="spin_arc_angle">
          <property name="decimals">
           <number>5</number>
          </property>
          <property name="singleStep">
           <double>0.010000000000000</double>
          </property>
          <property name="value">
           <double>0.785400000000000</double>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
    <item>
     <layout class="QVBoxLayout" name="vl_segments">
      <item>
       <widget class="QLabel" name="lbl_path">
        <property name="text">
         <string>Paths</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QTreeView" name="tree_paths"/>
      </item>
      <item>
       <layout class="QHBoxLayout" name="horizontalLayout">
        <item>
         <widget class="QPushButton" name="btn_save_paths">
          <property name="text">
           <string>Save Paths</string>
          </property>
         </widget>
        </item>
        <item>
         <widget class="QPushButton" name="btn_load_paths">
          <property name="text">
           <string>Load Paths</string>
          </property>
         </widget>
        </item>
       </layout>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

And some Python code below, which is for an RQT ROS plugin.

import os
import rospy
import rospkg
from PySide2.QtWidgets import QTreeView, QPushButton, QFileDialog
from python_qt_binding import loadUi

from qt_gui.plugin import Plugin
from python_qt_binding.QtWidgets import QWidget
from argparse import ArgumentParser

def get_file():
    print("Hello World!")
    dlg = QFileDialog()
    dlg.setFileMode(QFileDialog.AnyFile)
    dlg.setFilter("XML files (*.xml)")

    if dlg.exec_():
        filenames = dlg.selectedFiles()
        f = open(filenames[0], 'r')

        with f:
            data = f.read()
            # self.contents.setText(data)

class RoverPlanner(Plugin):
    def __init__(self, context):
        super(RoverPlanner, self).__init__(context)
        self.setObjectName('RoverPlanner')
        parser = ArgumentParser()
        parser.add_argument("-q", "--quiet", action="store_true",
                            dest="quiet",
                            help="Put plugin in silent mode")
        args, unknowns = parser.parse_known_args(context.argv())
        if not args.quiet:
            print('arguments: ', args)
            print('unknowns: ', unknowns)

        self.widget = QWidget()
        ui_file = os.path.join(rospkg.RosPack().get_path('cuarl-rover-planner'), 'resource', 'rover_planner_widget.ui')
        loadUi(ui_file, self.widget)
        self.widget.setObjectName('RoverPlannerUI')
        # Show widget.windowTitle on left-top of each plugin (when
        # it's set in widget). This is useful when you open multiple
        # plugins at once. Also if you open multiple instances of your
        # plugin at once, these lines add number to make it easy to
        # tell from pane to pane.
        if context.serial_number() > 1:
            self.widget.setWindowTitle(self.widget.windowTitle() + (' (%d)' % context.serial_number()))
        # Add widget to the user interface
        context.add_widget(self.widget)
        self.tree_paths = self.widget.findChild(QTreeView)
        self.btn_load_paths = self.widget.findChildren(QPushButton)
        print(self.tree_paths)
        print(self.btn_load_paths)

    def shutdown_plugin(self):
        # TODO unregister all publishers here
        pass

    def save_settings(self, plugin_settings, instance_settings):
        # TODO save intrinsic configuration, usually using:
        # instance_settings.set_value(k, v)
        pass

    def restore_settings(self, plugin_settings, instance_settings):
        # TODO restore intrinsic configuration, usually using:
        # v = instance_settings.value(k)
        pass

According to the documentation, it seems that my code should find these children. But the output of this code is

('arguments: ', Namespace(quiet=False))
('unknowns: ', [])
None
[]

I don't know if I'm not using the findChildren/findChild functions correctly or there's something that I am missing

Body:
I ever encountered a similar problem and the cause was that the library used some wrapper like python_qt_binding but another part of the code used PyQt5 or PySide2. Why does that happen? because wrappers create new classes that use the same code base but in the end they are different classes.

My recommendation is that if you are going to use python_qt_binding then no longer use pyqt5 or pyside2 directly but rather the wrapper, in your case you should use the following:

import os

from argparse import ArgumentParser

import rospy
import rospkg

from qt_gui.plugin import Plugin

from python_qt_binding.QtWidgets import QWidget, QTreeView, QPushButton, QFileDialog
from python_qt_binding import loadUi

# ....


问:
When is combining HostBinding with Input *sometimes* necessary when updating a property
I am trying to understand when I need to use @HostBinding and when it must be combined with @Input within a directive. Consider I have a directive that replaces a missing image with a default one:

Here is a working version:

image-fallback.directive.ts

```<code>@Directive({
  selector: "[appImageFallbackHostBindingAndInput]",
})
export class ImageFallbackDirectiveWithHostBindingAndInput {
  verifiedSrc: string;
  defaultImage = DEFAULT_IMAGE;
  @HostBinding("src") @Input('src') src: string;
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  constructor() {}
  handleErrorFallback() {
    // set directly like it is a class property without eg, renderer2
    this.src = this.defaultImage;
  }
}
</code>```

app.component.html

```<code><img [src]="src" appImageFallbackHostBindingAndInput alt="HostBinding and Input" />
</code>```

Even though this src property is not an @Input on AppComponent, apparently it is still needed here. Why? I thought HostBinding would allow me to bind to a property of its host.

But, even more than that, if you'll look at this StackBlitz you'll note that omitting the second @Input decorator does in fact work the first time. Just once, but it does allow me to set this.src = this.defaultImage like the "completely working" example. So my first thought of like, well I guess you need the Input if you are going to two-way bind or something, doesn't really hold water because apparently it does to some extent work. In fact, I didn't even notice the bug I had using only HostBinding until sometime had passed and I noticed updated images weren't always rendering when they errored.

When is it necessary to combine these decorators, and why does it work with only HostBinding once?

Note: a few answers here say that it is necessary, but they don't explain why or in which specific cases it is necessary, or explain why it sometimes works without both.

答:
Without @Input() decorator, you are only updating the src property of the HTMLImageElement, not the directive. The first version is working because you update the property of the directive, then change it to fall back url, then bind it to HTMLImageElement src property. The proper solution should be:

@Directive({
  selector: "[appImageFallbackWithOnlyHostBinding]",
})
export class ImageFallbackDirectiveWithOnlyHostBinding {
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  constructor(private el: ElementRef<HTMLImageElement>) {}
  handleErrorFallback() {
    // Prevent infinite loop
    if (this.el.nativeElement.src !== DEFAULT_IMAGE) {
      this.el.nativeElement.src = DEFAULT_IMAGE;
    }
  }
}
```

<p>Edit: it takes some time to explain your problem. We'll rename <code>src</code> to <code>directiveSrc</code> in the directive, and <code>src</code> to <code>appSrc</code> in the <code>app.component.ts</code>, so the first one with <code>@Input()</code> becomes:</p>

<pre class="lang-html prettyprint-override"><code><img [directiveSrc]="appSrc" appImageFallbackHostBindingAndInput alt="HostBinding and Input" />
</code>```

@Directive({
  selector: "[appImageFallbackHostBindingAndInput]",
})
export class ImageFallbackDirectiveWithHostBindingAndInput {
  defaultImage = DEFAULT_IMAGE;
  @HostBinding("src") @Input() directiveSrc: string;
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  handleErrorFallback() {
    this.src = this.defaultImage;
  }
}
```

<p>With <code>@Input()</code>, <code>directiveSrc</code> is bound to <code>appSrc</code>, which will update <code>src</code> of HTMLImageElement thanks to <code>@HostBinding('src')</code>. If there is an error, we update <code>directiveSrc</code> to fallback url, which will update <code>src</code> of HTMLImageElement thanks to <code>@HostBinding('src')</code>. So it works:</p>

<ul>
<li>appSrc = good ==> directiveSrc = good ==> src = good</li>
<li>appSrc = bad ==> directiveSrc = bad ==> src = bad ==> event error ==> directiveSrc = <code>bad --> fallback</code> ==> src = fallback</li>
</ul>

<p>Now, without <code>@Input()</code>, it will become:</p>

<pre class="lang-html prettyprint-override"><code><img [src]="appSrc" appImageFallbackWithOnlyHostBinding alt="HostBinding only" />
</code>```

@Directive({
  selector: "[appImageFallbackWithOnlyHostBinding]",
})
export class ImageFallbackDirectiveWithOnlyHostBinding {
  defaultImage = DEFAULT_IMAGE;
  @HostBinding("src") directiveSrc: string;
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  handleErrorFallback() {
    // First time: directiveSrc is undefined
    // From second time: directiveSrc is equal this.defaultImage
    this.directiveSrc = this.defaultImage;
  }
}
```

<p>So, without <code>@Input()</code> the HTMLImageElement's <code>src</code> is bound to <code>appSrc</code>, it displays the image. When <code>appSrc</code> becomes bad:</p>

<ul>
<li>First time: appSrc = bad => src = bad => error event => directiveSrc = <code>undefined --> fallback</code> => src = fallback</li>
<li>From second time: appSrc = bad ==> src = bad ==> error event ==> directiveSrc = <code>fallback --> fallback</code>: since there is no change in <code>directiveSrc</code>, <code>src</code> is not updated.</li>
</ul>

<p>To overcome it: you need to make <code>directiveSrc</code> change in 2 different cycles, such as:</p>

<pre class="lang-js prettyprint-override"><code>  handleErrorFallback() {
    this.src = undefined;
    setTimeout(() => this.src = this.defaultImage);
  }
</code>```

Of course, I would not recommend either of your solutions, as it is hard to understand. That's why the proper solution is using ElementRef, which is really easy to understand, without using @Hostbinding() and @Input()

Body:
I am trying to understand when I need to use @HostBinding and when it must be combined with @Input within a directive. Consider I have a directive that replaces a missing image with a default one:

Here is a working version:

image-fallback.directive.ts

@Directive({
  selector: "[appImageFallbackHostBindingAndInput]",
})
export class ImageFallbackDirectiveWithHostBindingAndInput {
  verifiedSrc: string;
  defaultImage = DEFAULT_IMAGE;
  @HostBinding("src") @Input('src') src: string;
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  constructor() {}
  handleErrorFallback() {
    // set directly like it is a class property without eg, renderer2
    this.src = this.defaultImage;
  }
}

app.component.html

Even though this src property is not an @Input on AppComponent, apparently it is still needed here. Why? I thought HostBinding would allow me to bind to a property of its host.

But, even more than that, if you'll look at this StackBlitz you'll note that omitting the second @Input decorator does in fact work the first time. Just once, but it does allow me to set this.src = this.defaultImage like the "completely working" example. So my first thought of like, well I guess you need the Input if you are going to two-way bind or something, doesn't really hold water because apparently it does to some extent work. In fact, I didn't even notice the bug I had using only HostBinding until sometime had passed and I noticed updated images weren't always rendering when they errored.

When is it necessary to combine these decorators, and why does it work with only HostBinding once?

Note: a few answers here say that it is necessary, but they don't explain why or in which specific cases it is necessary, or explain why it sometimes works without both.

Body:
Without @Input() decorator, you are only updating the src property of the HTMLImageElement, not the directive. The first version is working because you update the property of the directive, then change it to fall back url, then bind it to HTMLImageElement src property. The proper solution should be:

@Directive({
  selector: "[appImageFallbackWithOnlyHostBinding]",
})
export class ImageFallbackDirectiveWithOnlyHostBinding {
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  constructor(private el: ElementRef<HTMLImageElement>) {}
  handleErrorFallback() {
    // Prevent infinite loop
    if (this.el.nativeElement.src !== DEFAULT_IMAGE) {
      this.el.nativeElement.src = DEFAULT_IMAGE;
    }
  }
}

Edit: it takes some time to explain your problem. We'll rename src to directiveSrc in the directive, and src to appSrc in the app.component.ts, so the first one with @Input() becomes:

<img [directiveSrc]="appSrc" appImageFallbackHostBindingAndInput alt="HostBinding and Input" />

@Directive({
  selector: "[appImageFallbackHostBindingAndInput]",
})
export class ImageFallbackDirectiveWithHostBindingAndInput {
  defaultImage = DEFAULT_IMAGE;
  @HostBinding("src") @Input() directiveSrc: string;
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  handleErrorFallback() {
    this.src = this.defaultImage;
  }
}

With @Input(), directiveSrc is bound to appSrc, which will update src of HTMLImageElement thanks to @HostBinding('src'). If there is an error, we update directiveSrc to fallback url, which will update src of HTMLImageElement thanks to @HostBinding('src'). So it works:

appSrc = good ==> directiveSrc = good ==> src = good

appSrc = bad ==> directiveSrc = bad ==> src = bad ==> event error ==> directiveSrc = bad --> fallback ==> src = fallback

Now, without @Input(), it will become:

<img [src]="appSrc" appImageFallbackWithOnlyHostBinding alt="HostBinding only" />

@Directive({
  selector: "[appImageFallbackWithOnlyHostBinding]",
})
export class ImageFallbackDirectiveWithOnlyHostBinding {
  defaultImage = DEFAULT_IMAGE;
  @HostBinding("src") directiveSrc: string;
  @HostListener("error") onError() {
    this.handleErrorFallback();
  }
  handleErrorFallback() {
    // First time: directiveSrc is undefined
    // From second time: directiveSrc is equal this.defaultImage
    this.directiveSrc = this.defaultImage;
  }
}

So, without @Input() the HTMLImageElement's src is bound to appSrc, it displays the image. When appSrc becomes bad:

First time: appSrc = bad => src = bad => error event => directiveSrc = undefined --> fallback => src = fallback

From second time: appSrc = bad ==> src = bad ==> error event ==> directiveSrc = fallback --> fallback: since there is no change in directiveSrc, src is not updated.

To overcome it: you need to make directiveSrc change in 2 different cycles, such as:

  handleErrorFallback() {
    this.src = undefined;
    setTimeout(() => this.src = this.defaultImage);
  }

Of course, I would not recommend either of your solutions, as it is hard to understand. That's why the proper solution is using ElementRef, which is really easy to understand, without using @Hostbinding() and @Input()


问:
set-acl to AD OU
I know that this subject was already discussed here but solutions here and on other sites seem not to work for me.

I want to add to CNO: "CLUSTER" permission on OU to Create Computer Object.

More or less all solution are based on following idea:

$ou = 'OU=sql,OU=prod,DC=ssd,DC=xxx,DC=net'
$cno = 'CLUSTER1'
$sid = [System.Security.Principal.SecurityIdentifier](Get-ADComputer -Filter "name -eq `"$cno`"").SID
$acl = get-acl $ou
$objectGUID = New-Object guid bf967a86-0de6-11d0-a285-00aa003049e2
$guidNull = New-Object guid 00000000-0000-0000-0000-000000000000
$ace1 = new-object System.DirectoryServices.ActiveDirectoryAccessRule $sid,"ReadProperty,GenericExecute","Allow",$guidNull,"None",$guidNull
$acl.AddAccessRule($ace1)
$ace2 = new-object System.DirectoryServices.ActiveDirectoryAccessRule $sid,"CreateChild","Allow",$ObjectGUID,"None",$guidNull
$acl.AddAccessRule($ace2)
set-acl -aclobject $acl $ou
```

<p>I am getting following error:</p>

<pre class="lang-none prettyprint-override"><code>Set-Acl : This security ID may not be assigned as the owner of this object
At line:1 char:8
+ set-acl <<<<  -aclobject $acl $ou
    + CategoryInfo          : NotSpecified: (OU=sql,OU=ssd...=xxx,DC=net:String) [Set-Acl], ADException
    + FullyQualifiedErrorId : ADProvider:SetSecurityDescriptor:ADError,Microsoft.PowerShell.Commands.SetAclCommand
</code>```

Any idea what can be wrong?

答:
seems to be working on any AD object, including DNS records via DN:</p>

```<code>dsacls $DistinguishedName /G "NT AUTHORITY\Authenticated Users:GW"
</code>```

ContentLicense: CC BY-SA 3.0

Title: set-acl to AD OU

Body:
I know that this subject was already discussed here but solutions here and on other sites seem not to work for me.

I want to add to CNO: "CLUSTER" permission on OU to Create Computer Object.

More or less all solution are based on following idea:

$ou = 'OU=sql,OU=prod,DC=ssd,DC=xxx,DC=net'
$cno = 'CLUSTER1'
$sid = [System.Security.Principal.SecurityIdentifier](Get-ADComputer -Filter "name -eq `"$cno`"").SID
$acl = get-acl $ou
$objectGUID = New-Object guid bf967a86-0de6-11d0-a285-00aa003049e2
$guidNull = New-Object guid 00000000-0000-0000-0000-000000000000
$ace1 = new-object System.DirectoryServices.ActiveDirectoryAccessRule $sid,"ReadProperty,GenericExecute","Allow",$guidNull,"None",$guidNull
$acl.AddAccessRule($ace1)
$ace2 = new-object System.DirectoryServices.ActiveDirectoryAccessRule $sid,"CreateChild","Allow",$ObjectGUID,"None",$guidNull
$acl.AddAccessRule($ace2)
set-acl -aclobject $acl $ou

I am getting following error:

Set-Acl : This security ID may not be assigned as the owner of this object
At line:1 char:8
+ set-acl <<<<  -aclobject $acl $ou
    + CategoryInfo          : NotSpecified: (OU=sql,OU=ssd...=xxx,DC=net:String) [Set-Acl], ADException
    + FullyQualifiedErrorId : ADProvider:SetSecurityDescriptor:ADError,Microsoft.PowerShell.Commands.SetAclCommand

Any idea what can be wrong?

Body:
seems to be working on any AD object, including DNS records via DN:

dsacls $DistinguishedName /G "NT AUTHORITY\Authenticated Users:GW"