问:
Regex to extract expressions from input string
I'm trying to use a regular expression to extract expressions in the format of "operand operator operand" from a input string. The operands may be any single words or quoted phrases and the operator between operands will be the tilde sign followed by a numeral. The expression might occur n number of times within the input string. What's wrong in my regex?

```<code>package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExpressionExtractor {

    private static final String operator = "\\s+\\~{1}\\d+\\s+";
    private static final String quotedWords = "[\"|'|“][A-Za-zÀ-ü0-9\\\\.\\/\\-,\\*\\s]+[\"|'|“]";
    private static final String singleWords = "[A-Za-zÀ-ü0-9\\\\.\\/\\-,\\*]+";
    private static final String operand = quotedWords+"|"+singleWords;
    private static final Pattern expressionPattern = Pattern.compile("("+operand + operator +operand+")");
    private static final Pattern operatorPattern = Pattern.compile(operator);

    public static Matcher evaluateExpression(String input) {
        return expressionPattern.matcher(input);
    }
}
</code>```

A test case with the expected results:

```<code>package test;

import static org.junit.Assert.assertEquals;

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

import org.junit.Test;

public class ExpressionExtractorUnitTest {

    @Test
    public void testExpressionExtractor() {
        assertEquals(Arrays.asList("firstWord ~20 secondWord"), find("any word firstWord ~20 secondWord one more word"));
        assertEquals(Arrays.asList("mother-in-law ~8 long-Word"), find("start of sentence mother-in-law ~8 long-Word one sentence"));
        assertEquals(Arrays.asList("firstWord ~7 secondWord", "word ~8 \"complex expression\""),
                find("more complex expression firstWord ~7 secondWord with another word ~8 \"complex expression\" continued"));
    }

    private List<String> find(String expression) {
        Matcher matcher = ExpressionExtractor.evaluateExpression(expression);
        List<String> tokens = new ArrayList<>();
        while (matcher.find()) {
            tokens.add(matcher.group());
        }
        return tokens;
    }
}
</code>```

答:
Since your code includes a nice unit test, here are suggested fixes/changes:

You don't need to specify character number if it is 1 so "~{1}" can become "~". You don't need to escape the tilde character, so "\s+\~{1}\d+\s+" can become "\s+~\d+\s+". There if you don't like the "picket fence" you can use another character, for example like this

```<code>String operator = "!s+~!d+!s+".replace('!','\\').
</code>```

I find the expression fro quoted words too complicated to follow. You can try a a group starting with quote character, followed by 0 or more non-quote characters and then followed by a quote. Also, you don't need pipe within square brackets

```<code>String quotedWords = "[\"|'|“][^\"|'|“]*[\"|'|“]";
</code>```

In order to match many alternative patterns you have to add extra parenthesis for each group

```<code>expressionPattern = Pattern.compile("(" + operand + ")(" +operator + ")(" +operand + ")");
</code>```

This will make the tests pass. However, you might consider using a grammar parser library like ANTLR. There you could easily go to nested expressions and get the abstract syntax tree (AST)

Body:
I'm trying to use a regular expression to extract expressions in the format of "operand operator operand" from a input string. The operands may be any single words or quoted phrases and the operator between operands will be the tilde sign followed by a numeral. The expression might occur n number of times within the input string. What's wrong in my regex?

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExpressionExtractor {

    private static final String operator = "\\s+\\~{1}\\d+\\s+";
    private static final String quotedWords = "[\"|'|“][A-Za-zÀ-ü0-9\\\\.\\/\\-,\\*\\s]+[\"|'|“]";
    private static final String singleWords = "[A-Za-zÀ-ü0-9\\\\.\\/\\-,\\*]+";
    private static final String operand = quotedWords+"|"+singleWords;
    private static final Pattern expressionPattern = Pattern.compile("("+operand + operator +operand+")");
    private static final Pattern operatorPattern = Pattern.compile(operator);

    public static Matcher evaluateExpression(String input) {
        return expressionPattern.matcher(input);
    }
}

A test case with the expected results:

package test;

import static org.junit.Assert.assertEquals;

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

import org.junit.Test;

public class ExpressionExtractorUnitTest {

    @Test
    public void testExpressionExtractor() {
        assertEquals(Arrays.asList("firstWord ~20 secondWord"), find("any word firstWord ~20 secondWord one more word"));
        assertEquals(Arrays.asList("mother-in-law ~8 long-Word"), find("start of sentence mother-in-law ~8 long-Word one sentence"));
        assertEquals(Arrays.asList("firstWord ~7 secondWord", "word ~8 \"complex expression\""),
                find("more complex expression firstWord ~7 secondWord with another word ~8 \"complex expression\" continued"));
    }

    private List<String> find(String expression) {
        Matcher matcher = ExpressionExtractor.evaluateExpression(expression);
        List<String> tokens = new ArrayList<>();
        while (matcher.find()) {
            tokens.add(matcher.group());
        }
        return tokens;
    }
}

Body:
Since your code includes a nice unit test, here are suggested fixes/changes:

You don't need to specify character number if it is 1 so "~{1}" can become "~". You don't need to escape the tilde character, so "\s+\~{1}\d+\s+" can become "\s+~\d+\s+". There if you don't like the "picket fence" you can use another character, for example like this

String operator = "!s+~!d+!s+".replace('!','\\').

I find the expression fro quoted words too complicated to follow. You can try a a group starting with quote character, followed by 0 or more non-quote characters and then followed by a quote. Also, you don't need pipe within square brackets

String quotedWords = "[\"|'|“][^\"|'|“]*[\"|'|“]";

In order to match many alternative patterns you have to add extra parenthesis for each group

expressionPattern = Pattern.compile("(" + operand + ")(" +operator + ")(" +operand + ")");

This will make the tests pass. However, you might consider using a grammar parser library like ANTLR. There you could easily go to nested expressions and get the abstract syntax tree (AST)


来源: stackexchange

问:
change url zend
class ContactusController extends Zend_Controller_Action it result url/contactus.I like to change url/contact-us . How can i add "-" in url. Please help me to find-out the solution

答:
Instead of

```<code>class ContactusController extends Zend_Controller_Action
</code>```

Use a camelCase name:

```<code>class ContactUsController extends Zend_Controller_Action
</code>```

with a U and not u.

Same thing for yout filename, should be a controller/ContactUsController.php. Then the url is by convention contact-us, contact-us/action, etc.

ContentLicense: CC BY-SA 3.0

Title: change url zend

Body:
Instead of

class ContactusController extends Zend_Controller_Action

Use a camelCase name:

class ContactUsController extends Zend_Controller_Action

with a U and not u.

Same thing for yout filename, should be a controller/ContactUsController.php. Then the url is by convention contact-us, contact-us/action, etc.


问:
Mocking in Laravel with GitHub API Wrapper?
I'm new to Mockery. I'm trying to figure it out with the GitHub API by using a Laravel Package as a wrapper. How can I mock GitHub::repo()->show('symfony', 'demo'); without hiting the actual API? Is there something weird with Facades? I'm getting an error here:

```<code>In EvalLoader.php(34) : eval()'d code line 993:

  Cannot redeclare Mockery_0_GrahamCampbell_GitHub_Facades_GitHub::shouldReceive()

</code>```

Code:

```<code>    use Mockery;
    use Tests\TestCase;
    use GrahamCampbell\GitHub\Facades\GitHub;

    public function testExample()
    {
        $this->mockGitHubWith([
            'id' => 1,
            'name' => 'demo',
            'full_name' => 'symfony/demo',
        ]);

        $repo = GitHub::repo()->show('symfony', 'demo');

        dd($repo);
    }

    protected function mockGitHubWith($expectations)
    {
        $github = Mockery::mock(GitHub::class, $expectations);
        $github->shouldReceive('api')->andReturn($github);
        app()->instance(GitHub::class, $github);
    }
</code>```

also tried:

```<code>use GrahamCampbell\GitHub\Facades\GitHub;

public function testExample()
    {
        Github::shouldReceive('api')->once()->andReturn(['id' => 1]);

        $repo = Github::repo()->show('symfony', 'demo');

        dd($repo);
    }
</code>```

Returns: Mockery\Exception\BadMethodCallException: Method Mockery_0::repo() does not exist on this mock object

Just to confirm, if I remove the GitHub::shouldReceive...  line, it's successful but actually hits the GitHub API.

答:
With the last example you are almost there. Remember you are trying to mock a two step call, first a static method and a call to an instance, therefor the mock should emulate that.

Create the repository that the repo() call will return. Using standard mockery functionality.

```<code>use Github\Api\Repo;

$repoMock = Mockery::mock(Repo::class);
$repoMock->shouldReceive('show')->with('symfony', 'demo')->once()->andReturn(['id' => 1]);
</code>```

Now you can set the return type of the repo call through Laravels approach to mock facades.

```<code>Github::shouldReceive('repo')->once()->andReturn($repoMock);
</code>```

When you call your code repo will return the repo mock, that expects a show call with the parameters symfony and demo.

```<code>$repo = Github::repo()->show('symfony', 'demo');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Mockery. I'm trying to figure it out with the GitHub API by using a Laravel Package as a wrapper. How can I mock GitHub::repo()->show('symfony', 'demo'); without hiting the actual API? Is there something weird with Facades? I'm getting an error here:

In EvalLoader.php(34) : eval()'d code line 993:

  Cannot redeclare Mockery_0_GrahamCampbell_GitHub_Facades_GitHub::shouldReceive()

Code:

    use Mockery;
    use Tests\TestCase;
    use GrahamCampbell\GitHub\Facades\GitHub;

    public function testExample()
    {
        $this->mockGitHubWith([
            'id' => 1,
            'name' => 'demo',
            'full_name' => 'symfony/demo',
        ]);

        $repo = GitHub::repo()->show('symfony', 'demo');

        dd($repo);
    }

    protected function mockGitHubWith($expectations)
    {
        $github = Mockery::mock(GitHub::class, $expectations);
        $github->shouldReceive('api')->andReturn($github);
        app()->instance(GitHub::class, $github);
    }

also tried:

use GrahamCampbell\GitHub\Facades\GitHub;

public function testExample()
    {
        Github::shouldReceive('api')->once()->andReturn(['id' => 1]);

        $repo = Github::repo()->show('symfony', 'demo');

        dd($repo);
    }

Returns: Mockery\Exception\BadMethodCallException: Method Mockery_0::repo() does not exist on this mock object

Just to confirm, if I remove the GitHub::shouldReceive...  line, it's successful but actually hits the GitHub API.

Body:
With the last example you are almost there. Remember you are trying to mock a two step call, first a static method and a call to an instance, therefor the mock should emulate that.

Create the repository that the repo() call will return. Using standard mockery functionality.

use Github\Api\Repo;

$repoMock = Mockery::mock(Repo::class);
$repoMock->shouldReceive('show')->with('symfony', 'demo')->once()->andReturn(['id' => 1]);

Now you can set the return type of the repo call through Laravels approach to mock facades.

Github::shouldReceive('repo')->once()->andReturn($repoMock);

When you call your code repo will return the repo mock, that expects a show call with the parameters symfony and demo.

$repo = Github::repo()->show('symfony', 'demo');


问:
VSCode: How can I disable the windowframe so maximized looks like full screen?
How can I disable the window frame on vscode so that there is no bevel and the window looks as if it is in full screen? It might not be fully clear what I am getting at but I have posted some pictures that will hopefully make more sense.

Maximized with a bevel:

Full screen with no bevel:

I don't these changes are possible via the GUI and envisage that it needs some changes in the settings.json file, possibly via customised .css and .js...

That's my hunch, but not sure if this is true or what to do. I have tried customize-UI and Custom CSS and JS Loader without luck, so was hoping I could get some guidance on here.

答:
I'm not sure if this is exactly what you want, but you could try Zen Mode. This feature gets rid of all UI elements except the editor.

To activate Zen Mode, go to View -> Appearance -> Zen Mode or use the keyboard shortcut Ctrl/cmd+ K Z. To view the top bar, click the alt/option key


问:
Flutter firebase - can't catch exception thrown white trying to update a document with a map with an empty key
While trying to update a document in Firestore with a map with an empty key (a bug in my code), I wasn't able to catch the exception, which resulted in an app crash.

Here's a sample code:

```<code>try {
Map<String, dynamic> crash = {"": 3}; // this is an empty key (bug)
await docRef.collection('collection').document('doc').updateData({"ABC": crash});
} catch (err) {
print(err);
}
</code>```

The exception (quite reasonable):

```<code>*** Assertion failure in auto firebase::firestore::model::FieldPath::FromServerFormat(const absl::string_view)::(anonymous class)::operator()() const(), /project/ios/Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/model/field_path.cc:90
Lost connection to device.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Invalid field path (s3SEDn5nhnWiqeZjpDmY.``). Paths must not be empty, begin with '.', end with '.', or contain '..' (expected !segment.empty())'
</code>```

I don't see the error printed to the console, nor I get to a breakpoint set there.

My questions / issues:

Am I using the try catch block in a wrong way? Why isn't the catch statement working?

After the app crashes, trying to relaunch it fails, with the following error:

```<code>FileSystemException: Getting current working directory failed, path = '' (OS Error: Too many open files in system, errno = 23)
</code>```

Only uninstalling and reinstalling the app works.
Any idea if this is normal? If not, what can I do about it?

Crashes both on iOS and Android,
Firestore plugin version cloud_firestore: ^0.12.7

答:
I had a similar issue trying to catch exeptions on updateData with a map with no internet connection (emulator).

```<code>    await Firestore.instance.collection('collection').document(doc).updateDataa({"ABC": crash}).timeout(Duration(seconds: 10));
</code>```

This was the only way i could handle the timeout and return connection error!

Body:
While trying to update a document in Firestore with a map with an empty key (a bug in my code), I wasn't able to catch the exception, which resulted in an app crash.

Here's a sample code:

try {
Map<String, dynamic> crash = {"": 3}; // this is an empty key (bug)
await docRef.collection('collection').document('doc').updateData({"ABC": crash});
} catch (err) {
print(err);
}

The exception (quite reasonable):

*** Assertion failure in auto firebase::firestore::model::FieldPath::FromServerFormat(const absl::string_view)::(anonymous class)::operator()() const(), /project/ios/Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/model/field_path.cc:90
Lost connection to device.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Invalid field path (s3SEDn5nhnWiqeZjpDmY.``). Paths must not be empty, begin with '.', end with '.', or contain '..' (expected !segment.empty())'

I don't see the error printed to the console, nor I get to a breakpoint set there.

My questions / issues:

Am I using the try catch block in a wrong way? Why isn't the catch statement working?

After the app crashes, trying to relaunch it fails, with the following error:

FileSystemException: Getting current working directory failed, path = '' (OS Error: Too many open files in system, errno = 23)

Only uninstalling and reinstalling the app works.
Any idea if this is normal? If not, what can I do about it?

Crashes both on iOS and Android,
Firestore plugin version cloud_firestore: ^0.12.7

Body:
I had a similar issue trying to catch exeptions on updateData with a map with no internet connection (emulator).

    await Firestore.instance.collection('collection').document(doc).updateDataa({"ABC": crash}).timeout(Duration(seconds: 10));

This was the only way i could handle the timeout and return connection error!


问:
Changing the selected value of a drop down based on the selected value of another drop down in VB.Net
I have a dropdown box which is used to select a user from a database. I am then populating a number of textboxes with the user information from the database. I want to populate a dropdown box, which holds the user's role, dependent on which user is selected from the first drop down box.

Here is my code:

```<code>    Dim currentUser As String = editUserDropDown.SelectedValue
    Dim getUserDetails = "Select aspnet_Users.UserName, aspnet_Roles.RoleName, [User Details].EmployeeName, [User Details].EmployeeAddress, [User Details].PersonalEmailAddress FROM aspnet_Users INNER JOIN [User Details] ON aspnet_Users.UserId = [User Details].UserId CROSS JOIN aspnet_Roles WHERE (aspnet_Users.UserName = '" & currentUser & "')"
    Dim getUserDetailsCmd As New SqlClient.SqlDataAdapter(getUserDetails, DBConn)
    Dim getUserDetailsDS As New DataSet
    getUserDetailsCmd.Fill(getUserDetailsDS)

    Dim username = getUserDetailsDS.Tables(0).Rows(0).Item(0)
    Dim roleName = getUserDetailsDS.Tables(0).Rows(0).Item(1)
    Dim name = getUserDetailsDS.Tables(0).Rows(0).Item(2)
    Dim address = getUserDetailsDS.Tables(0).Rows(0).Item(3)
    Dim email = getUserDetailsDS.Tables(0).Rows(0).Item(4)

    userNameTxt.Text = username

    roleSelect.SelectedValue = roleName

    nameTxt.Text = name
    addressTxt.Text = address.Trim()
    emailTxt.Text = email
</code>```

any help is greatly appreciated

答:
You have to do this by doing a Post-back on the fist select drop down and then getting the content for the second one depending of the selection made on the first...

Hoped that helped!

Body:
I have a dropdown box which is used to select a user from a database. I am then populating a number of textboxes with the user information from the database. I want to populate a dropdown box, which holds the user's role, dependent on which user is selected from the first drop down box.

Here is my code:

    Dim currentUser As String = editUserDropDown.SelectedValue
    Dim getUserDetails = "Select aspnet_Users.UserName, aspnet_Roles.RoleName, [User Details].EmployeeName, [User Details].EmployeeAddress, [User Details].PersonalEmailAddress FROM aspnet_Users INNER JOIN [User Details] ON aspnet_Users.UserId = [User Details].UserId CROSS JOIN aspnet_Roles WHERE (aspnet_Users.UserName = '" & currentUser & "')"
    Dim getUserDetailsCmd As New SqlClient.SqlDataAdapter(getUserDetails, DBConn)
    Dim getUserDetailsDS As New DataSet
    getUserDetailsCmd.Fill(getUserDetailsDS)

    Dim username = getUserDetailsDS.Tables(0).Rows(0).Item(0)
    Dim roleName = getUserDetailsDS.Tables(0).Rows(0).Item(1)
    Dim name = getUserDetailsDS.Tables(0).Rows(0).Item(2)
    Dim address = getUserDetailsDS.Tables(0).Rows(0).Item(3)
    Dim email = getUserDetailsDS.Tables(0).Rows(0).Item(4)

    userNameTxt.Text = username

    roleSelect.SelectedValue = roleName

    nameTxt.Text = name
    addressTxt.Text = address.Trim()
    emailTxt.Text = email

any help is greatly appreciated


问:
docker failed to register layer windows 10 version 1709 (build 16299.1087)
I'm on Windows 10 version 1709 (build 16299.1087). Ultimately, I want to work with Windows containers. When I do docker pull mcr.microsoft.com/windows/nanoserver:1709 I get

```<code>1709: Pulling from windows/nanoserver
407ada6e90de: Extracting  81.04MB/81.04MB
9ef95ce817ec: Download complete
failed to register layer: re-exec error: exit status 3221225794: output:
</code>```

Not sure how to grok the exit status or the empty error message. Any thoughts?

EDIT:

Running docker info gives me:

```<code> Kernel Version: 10.0 16299 (16299.637.amd64fre.rs3_release_svc.180808-1748)
 Operating System: Windows 10 Pro Version 1709 (OS Build 16299.1087)
 OSType: windows
 Architecture: x86_64
 CPUs: 8
 Total Memory: 7.958GiB
</code>```

答:
Check your Docker for Windows service and ensure that it's set to run Windows containers.  In your setup, you have to switch the service back and forth:

You can see some explanation here: https://github.com/docker/for-win/issues/933

Body:
I'm on Windows 10 version 1709 (build 16299.1087). Ultimately, I want to work with Windows containers. When I do docker pull mcr.microsoft.com/windows/nanoserver:1709 I get

1709: Pulling from windows/nanoserver
407ada6e90de: Extracting  81.04MB/81.04MB
9ef95ce817ec: Download complete
failed to register layer: re-exec error: exit status 3221225794: output:

Not sure how to grok the exit status or the empty error message. Any thoughts?

EDIT:

Running docker info gives me:

 Kernel Version: 10.0 16299 (16299.637.amd64fre.rs3_release_svc.180808-1748)
 Operating System: Windows 10 Pro Version 1709 (OS Build 16299.1087)
 OSType: windows
 Architecture: x86_64
 CPUs: 8
 Total Memory: 7.958GiB


问:
Increase TEXT SIZE in SQL Server Agent
SQL Server Agent has a 512 characters limit on texts fields like nvarchar(max). I found this out after seeing my stored procedure is working correctly when I run it in SSMS but not working when is being run by a SQL Server job.

To fix this I know I can use SET TEXTSIZE { number } in my stored procedure to increase this number. However I don't want to add this line in each and every stored procedure that are being run by SQL Server jobs. Is there a way that I can set this value for SQL Server agent itself?

答:
Hear my plea MS.  Be kind to our eyes and allow us to increase the SQL Agent font size.

I use a sysinternals tool called ZoomIt.  Pressing [Control] + [1] takes a snapshot of the screen and zooms in to various magnifications.  It's a far cry from increasing the Agent job & steps, but works in a pinch.

Another work around is to return the job or it's steps in a query window.

```<code>select subsystem, step_id, step_name, command from sysjobsteps where job_id in
(select job_id from sysjobs where name like '%Some Job with tiny screen letters%')
</code>```

Title: Increase TEXT SIZE in SQL Server Agent

Body:
Hear my plea MS.  Be kind to our eyes and allow us to increase the SQL Agent font size.

I use a sysinternals tool called ZoomIt.  Pressing [Control] + [1] takes a snapshot of the screen and zooms in to various magnifications.  It's a far cry from increasing the Agent job & steps, but works in a pinch.

Another work around is to return the job or it's steps in a query window.

select subsystem, step_id, step_name, command from sysjobsteps where job_id in
(select job_id from sysjobs where name like '%Some Job with tiny screen letters%')


问:
Jenkins - disable stop / cancel for single stage
In a groovy multi-branch pipeline on Jenkins I have a single step which I don't want any user to be able to abort via the UI. However any other step should be able to be aborted. See example pipeline definition:

```<code>#!/usr/bin/env groovy

node {
    stage("I can be aborted") {
      // run some scripts etc here
    }

    stage("I cannot be aborted") {
      // some code that will complete even if stop / abort is pressed
    }

    stage("I will run if the build was not stopped before and can be stopped") {
      // rest of the pipeline
    }

}
</code>```

TLDR;
block the ability to stop a jenkins build on a per stage basis

Is this possible?

答:
When a user aborts a build, the code being execution usually throws an AbortException although it can also throw an InterruptedException (I've seen that where a stage is aborted while executing a shell script).

Since your pipeline is in groovy, you can use try/catch blocks to get the behavior you want:

```<code>#!/usr/bin/env groovy

import groovy.transform.Field // see https://stackoverflow.com/a/50573082/6692227

@Field boolean stopBuild = false

node {
    stage("I can be aborted") {
      // run some scripts etc here
    }

    stage("I cannot be aborted") {
      try {
        // some code that will complete even if stop / abort is pressed
      } catch (AbortException ex) {
        currentBuild.result = "UNSTABLE" // or whatever
        echo "User tried to abort but that's not allowed"
        stopBuild = true
      }
    }

    stage("I will run if the build was not stopped before and can be stopped") {
      if (stopBuild) return

      // rest of the pipeline
    }

}
</code>```

Body:
In a groovy multi-branch pipeline on Jenkins I have a single step which I don't want any user to be able to abort via the UI. However any other step should be able to be aborted. See example pipeline definition:

#!/usr/bin/env groovy

node {
    stage("I can be aborted") {
      // run some scripts etc here
    }

    stage("I cannot be aborted") {
      // some code that will complete even if stop / abort is pressed
    }

    stage("I will run if the build was not stopped before and can be stopped") {
      // rest of the pipeline
    }

}

TLDR;
block the ability to stop a jenkins build on a per stage basis

Is this possible?

Body:
When a user aborts a build, the code being execution usually throws an AbortException although it can also throw an InterruptedException (I've seen that where a stage is aborted while executing a shell script).

Since your pipeline is in groovy, you can use try/catch blocks to get the behavior you want:

#!/usr/bin/env groovy

import groovy.transform.Field // see https://stackoverflow.com/a/50573082/6692227

@Field boolean stopBuild = false

node {
    stage("I can be aborted") {
      // run some scripts etc here
    }

    stage("I cannot be aborted") {
      try {
        // some code that will complete even if stop / abort is pressed
      } catch (AbortException ex) {
        currentBuild.result = "UNSTABLE" // or whatever
        echo "User tried to abort but that's not allowed"
        stopBuild = true
      }
    }

    stage("I will run if the build was not stopped before and can be stopped") {
      if (stopBuild) return

      // rest of the pipeline
    }

}


问:
matlab, format table nicely, without cell arrays
Asking because I suspect there's an easy way I'm unaware of and couldn't google to satisfaction:
I want to format a cell array nicely and a table would be very convenient. How can I format the strings contained in a cell array to be formatted nicely without any ' and {''} pre/suffixes?

```<code>t={'a','b','c'}
cell2table(t,'VariableNames',{'1','2','3'})

ans =

  1×3 table

      1        2        3
    _____    _____    _____

    {'a'}    {'b'}    {'c'}
</code>```

答:
Thanks to Andrew and others, here's a slightly insane 'oneliner' / anonymous function.

It works by converting all table contents to categorical, then reassembling the table from that categorical array.

disp_table = @(tbl) disp(array2table(categorical(cellfun(@(x) num2str(x),table2cell(tbl),'uni',0)),'VariableNames',tbl.Properties.VariableNames));

%test the display function, create table...
tbl = cell2table({'a','b','c',NaN,-1,{'asdf asdf'}},'VariableNames',{'1','2','3','4','5','6'});
disp_table(tbl)

    1    2    3     4     5         6
    _    _    _    ___    __    _________

    a    b    c    NaN    -1    asdf asdf

```

Body:
Asking because I suspect there's an easy way I'm unaware of and couldn't google to satisfaction:
I want to format a cell array nicely and a table would be very convenient. How can I format the strings contained in a cell array to be formatted nicely without any ' and {''} pre/suffixes?

t={'a','b','c'}
cell2table(t,'VariableNames',{'1','2','3'})

ans =

  1×3 table

      1        2        3
    _____    _____    _____

    {'a'}    {'b'}    {'c'}


问:
Wireless signal strength from scapy using python3
Trying to retrieve wireless signal strength using a python tool and scapy. the output for all networks come out as -100. Here is a section of the code.

```<code>try:
            extra = frame.notdecoded
            rssi = (256 - ord(extra[-3:-2]))
        except:
            rssi = -100
</code>```

Any help?

答:
Just use Scapy 2.4.1+ and use

```<code>rssi = frame[RadioTap]. dBm_AntSignal
</code>```

See the doc: https://scapy.readthedocs.io/en/latest/api/scapy.layers.dot11.html#scapy.layers.dot11.RadioTap

(Similar issue: https://stackoverflow.com/a/51918918/5459467)

Body:
Trying to retrieve wireless signal strength using a python tool and scapy. the output for all networks come out as -100. Here is a section of the code.

try:
            extra = frame.notdecoded
            rssi = (256 - ord(extra[-3:-2]))
        except:
            rssi = -100

Any help?

Body:
Just use Scapy 2.4.1+ and use

rssi = frame[RadioTap]. dBm_AntSignal

See the doc: https://scapy.readthedocs.io/en/latest/api/scapy.layers.dot11.html#scapy.layers.dot11.RadioTap

(Similar issue: https://stackoverflow.com/a/51918918/5459467)


问:
What's the preferred way to create a jQuery object with attributes?
When creating jQuery objects I've used the following syntax lately, as described here:

```<code>var $el = $('<div/>', {
   class: 'class-1 class-2'
});
</code>```

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

答:
You can't use class; it's a reserved word.

Use className instead:

```<code>var $el = $('<div/>', {
   className: 'class-1 class-2'
});
</code>```

Body:
When creating jQuery objects I've used the following syntax lately, as described here:

var $el = $('
', {
   class: 'class-1 class-2'
});

Safari 5.0.5 gives a syntax error at the point where I use the above construction.

Removing the second argument and adding classes with addClass removes the error, but seems rather unelegant.

How do you create your objects? I tried with attr({class: 'class-1'}), as well, but received the same syntax error.

Body:
You can't use class; it's a reserved word.

Use className instead:

var $el = $('<div/>', {
   className: 'class-1 class-2'
});


问:
Tensorflow API, Tensorflow hub and Keras input shape
I am working with tf=2.0.0, and tensorflow hub. Currently I am using the Tensorflow data API to load my data which is stored in a tfrecords file.

I am successfully loading the dataset and compiling the model but when I try to fit the data into the model I get the error:

Error when checking input: expected inputs_input to have 1 dimensions,
  but got array with shape (64, 1)

This is how I am loading my data:

```<code>def _dataset_parser(value):
    """Parse a record from value."""
    featdef={
        'id':  tf.io.FixedLenFeature([1], tf.int64),
        'question': tf.io.FixedLenFeature([1], tf.string),
        'label': tf.io.FixedLenFeature([1], tf.int64)
    }

    example = tf.io.parse_single_example(value, featdef)

    label = tf.cast(example['label'], tf.int32)
    question = tf.cast(example['question'], tf.string)
    return example['question'], example['label']
def _input(epochs, batch_size, filenames):
    dataset = tf.data.TFRecordDataset(filenames)

    dataset = dataset.repeat(epochs)
    dataset = dataset.prefetch(1)

    # Parse records.
    dataset = dataset.map(_dataset_parser)
    dataset = dataset.shuffle(100)

    # Batch it up.
    dataset = dataset.batch(batch_size)
    iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)

    question_batch, label_batch = iterator.get_next()
    label_batch = tf.one_hot(label_batch, NUM_CLASSES)

    return question_batch, label_batch

train_ds = _input(20, 64, ['train_xs.tfrecords'])
</code>```

This is my model:

```<code>model = tf.keras.Sequential([
        hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
        tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
        tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
    ])

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])
</code>```

I already tried setting the input shape of the entry layer as (None, 1) but it keeps failing, not sure if the problem is due to TensorFlow hub however I tried running this example from the hands-on-ml book:

```<code>model = tf.keras.Sequential([
    hub.KerasLayer("https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1",
                   dtype=tf.string, input_shape=[], output_shape=[50]),
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dense(1, activation="sigmoid")
])
model.compile(loss="binary_crossentropy", optimizer="adam",
              metrics=["accuracy"])
datasets, info = tfds.load("imdb_reviews", as_supervised=True, with_info=True)
train_size = info.splits["train"].num_examples
batch_size = 32
train_set = datasets["train"].repeat().batch(batch_size).prefetch(1)
history = model.fit(train_set, steps_per_epoch=5, epochs=5)#steps_per_epoch=train_size // batch_size, epochs=5)
</code>```

and it works fine, however one difference I found is that if I print the train_set on the example from the book I get:

```<code><PrefetchDataset shapes: ((None,), (None,)), types: (tf.string, tf.int64)>
</code>```

Whereas with my code I get this when I print the dataset that I am feeding to the model:

```<code>(<tf.Tensor: id=11409, shape=(64, 1), dtype=string, numpy=  array([[b'Restroom score out of 9'],
        [b'Name'],
        [b'Lastname'],
        [b'Type of house'],
        [b'Inspection date'],
        [b'Pet'],
        [b'Phone'], dtype=object)>,  <tf.Tensor: id=11414, shape=(64, 1, 80), dtype=float32, numpy=  array([[[0., 0., 0., ...,
0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        ...,

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]]], dtype=float32)>)
</code>```

Does someone know why the difference in the shape of the data?

答:
If anyone is interested, this is the final code that worked for me:</p>

```<code>    model = tf.keras.Sequential([
        hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
name=INPUT_TENSOR_NAME),
        tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
        tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
    ])

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

    def _dataset_parser(value):
        """Parse a record from value."""
        featdef={
            'id':  tf.io.FixedLenFeature([], tf.int64),
            'question': tf.io.FixedLenFeature([], tf.string),
            'label': tf.io.FixedLenFeature([], tf.int64)
        }

        example = tf.io.parse_single_example(value, featdef)

        label = tf.cast(example['label'], tf.int64)
        question = tf.cast(example['question'], tf.string)
        return question, tf.one_hot(label, NUM_CLASSES)

    def _input(epochs, batch_size, filenames):
        dataset = tf.data.TFRecordDataset(filenames)

        dataset = dataset.repeat(epochs)
        dataset = dataset.prefetch(1)

        # Parse records.
        dataset = dataset.map(_dataset_parser)
        dataset = dataset.shuffle(100)

        # Batch it up.
        dataset = dataset.batch(batch_size)

        return dataset

    train_ds = _input(1, 10, ['train_xs.tfrecords'])

    model.fit(train_ds,epochs=1)
</code>```

Body:
I am working with tf=2.0.0, and tensorflow hub. Currently I am using the Tensorflow data API to load my data which is stored in a tfrecords file.

I am successfully loading the dataset and compiling the model but when I try to fit the data into the model I get the error:

Error when checking input: expected inputs_input to have 1 dimensions,
  but got array with shape (64, 1)

This is how I am loading my data:

def _dataset_parser(value):
    """Parse a record from value."""
    featdef={
        'id':  tf.io.FixedLenFeature([1], tf.int64),
        'question': tf.io.FixedLenFeature([1], tf.string),
        'label': tf.io.FixedLenFeature([1], tf.int64)
    }

    example = tf.io.parse_single_example(value, featdef)

    label = tf.cast(example['label'], tf.int32)
    question = tf.cast(example['question'], tf.string)
    return example['question'], example['label']
def _input(epochs, batch_size, filenames):
    dataset = tf.data.TFRecordDataset(filenames)

    dataset = dataset.repeat(epochs)
    dataset = dataset.prefetch(1)

    # Parse records.
    dataset = dataset.map(_dataset_parser)
    dataset = dataset.shuffle(100)

    # Batch it up.
    dataset = dataset.batch(batch_size)
    iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)

    question_batch, label_batch = iterator.get_next()
    label_batch = tf.one_hot(label_batch, NUM_CLASSES)

    return question_batch, label_batch

train_ds = _input(20, 64, ['train_xs.tfrecords'])

This is my model:

model = tf.keras.Sequential([
        hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
        tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
        tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
    ])

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

I already tried setting the input shape of the entry layer as (None, 1) but it keeps failing, not sure if the problem is due to TensorFlow hub however I tried running this example from the hands-on-ml book:

model = tf.keras.Sequential([
    hub.KerasLayer("https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1",
                   dtype=tf.string, input_shape=[], output_shape=[50]),
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dense(1, activation="sigmoid")
])
model.compile(loss="binary_crossentropy", optimizer="adam",
              metrics=["accuracy"])
datasets, info = tfds.load("imdb_reviews", as_supervised=True, with_info=True)
train_size = info.splits["train"].num_examples
batch_size = 32
train_set = datasets["train"].repeat().batch(batch_size).prefetch(1)
history = model.fit(train_set, steps_per_epoch=5, epochs=5)#steps_per_epoch=train_size // batch_size, epochs=5)

and it works fine, however one difference I found is that if I print the train_set on the example from the book I get:

<PrefetchDataset shapes: ((None,), (None,)), types: (tf.string, tf.int64)>

Whereas with my code I get this when I print the dataset that I am feeding to the model:

(<tf.Tensor: id=11409, shape=(64, 1), dtype=string, numpy=  array([[b'Restroom score out of 9'],
        [b'Name'],
        [b'Lastname'],
        [b'Type of house'],
        [b'Inspection date'],
        [b'Pet'],
        [b'Phone'], dtype=object)>,  <tf.Tensor: id=11414, shape=(64, 1, 80), dtype=float32, numpy=  array([[[0., 0., 0., ...,
0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        ...,

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]]], dtype=float32)>)

Does someone know why the difference in the shape of the data?

Body:
If anyone is interested, this is the final code that worked for me:

    model = tf.keras.Sequential([
        hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
name=INPUT_TENSOR_NAME),
        tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
        tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
    ])

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

    def _dataset_parser(value):
        """Parse a record from value."""
        featdef={
            'id':  tf.io.FixedLenFeature([], tf.int64),
            'question': tf.io.FixedLenFeature([], tf.string),
            'label': tf.io.FixedLenFeature([], tf.int64)
        }

        example = tf.io.parse_single_example(value, featdef)

        label = tf.cast(example['label'], tf.int64)
        question = tf.cast(example['question'], tf.string)
        return question, tf.one_hot(label, NUM_CLASSES)

    def _input(epochs, batch_size, filenames):
        dataset = tf.data.TFRecordDataset(filenames)

        dataset = dataset.repeat(epochs)
        dataset = dataset.prefetch(1)

        # Parse records.
        dataset = dataset.map(_dataset_parser)
        dataset = dataset.shuffle(100)

        # Batch it up.
        dataset = dataset.batch(batch_size)

        return dataset

    train_ds = _input(1, 10, ['train_xs.tfrecords'])

    model.fit(train_ds,epochs=1)


问:
Datetime format in xml from Oracle
I have a simple requirement to display a time field as a Datetime in xml when converted from excel.
Being new to Oracle field, I'm stuck with a few questions

When I run the below query in Oracle my value is displayed as 31-DEC-99 07.45.30.000000000

select to_timestamp('1899-12-31 07:45:30', 'yyyy-mm-dd hh:mi:ss') as res from dual;

Now,I understand that my NLS_DATE_FORMAT = 'DD-MON-RR' and hence the date is shown as 31-DEC-99 but why is the time shown as hh.mm.ss.ffff rather than hh:mm:ss:ffff

Is this the reason that when I download this simple file from oracle to excel and convert to xml, the datatype is show as string rather than datetime . I tried a similar exercise directly on excel and we can see the value as datetime on xml  but this doesnt work with excel downloaded from oracle. Where am I going wrong?

Just to confirm, my requirement here is to get a timestamp displayed in excel properly when downloaded from oracle table and display the same as a datetime field when I open in xml

答:
Is this concerning a BI/XML Publisher report?  If so, you need to do something like this to your dates in your data definition:</p>

```<code>TO_CHAR(ORDERED_DATE,'MM-DD-YYYY  HH24:MI:SS') ORDERED_DATE
</code>```

Title: Datetime format in xml from Oracle

Body:
Is this concerning a BI/XML Publisher report?  If so, you need to do something like this to your dates in your data definition:

TO_CHAR(ORDERED_DATE,'MM-DD-YYYY  HH24:MI:SS') ORDERED_DATE


问:
find contours of thresholded image
I want to detect the contours of image. and check if these contours are in the other image or no</p>

答:
You can do a perspective warp to align one image to the other. Convert both to HSV and get the saturation channels. Then threshold them and get the absolute difference between them. Then get the contours and finally the bounding boxes of the contours, which are drawn on the first image. Here is how to do that with Python/OpenCV. Note, I do not have SIFT installed, so I will use ORB in its place.

Input 1 (reference image):

Input 2 (image to be warped/aligned):

```<code>import cv2
import numpy as np

MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15

def alignImages(im1, im2):

  # im2 is reference and im1 in to be warped to match im2
  # note: numbering is swapped in function

  # Convert images to grayscale
  im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
  im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)

  # Detect ORB features and compute descriptors.
  orb = cv2.ORB_create(MAX_FEATURES)
  keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
  keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)

  # Match features.
  matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
  matches = matcher.match(descriptors1, descriptors2, None)

  # Sort matches by score
  matches.sort(key=lambda x: x.distance, reverse=False)

  # Remove not so good matches
  numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
  matches = matches[:numGoodMatches]

  # Draw top matches
  imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
  cv2.imwrite("pipes_matches.png", imMatches)

  # Extract location of good matches
  points1 = np.zeros((len(matches), 2), dtype=np.float32)
  points2 = np.zeros((len(matches), 2), dtype=np.float32)

  for i, match in enumerate(matches):
    points1[i, :] = keypoints1[match.queryIdx].pt
    points2[i, :] = keypoints2[match.trainIdx].pt

  # Find homography
  h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)

  # Use homography
  height, width, channels = im2.shape
  im1Reg = cv2.warpPerspective(im1, h, (width, height))

  return im1Reg, h

if __name__ == '__main__':

  # Read reference image
  refFilename = "pipes1.jpg"
  print("Reading reference image : ", refFilename)
  imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)

  # Read image to be aligned
  imFilename = "pipes2.jpg"
  print("Reading image to align : ", imFilename);
  im = cv2.imread(imFilename, cv2.IMREAD_COLOR)

  # Aligned image will be stored in imReg.
  # The estimated homography will be stored in h.
  imReg, h = alignImages(im, imReference)

  # Print estimated homography
  print("Estimated homography : \n",  h)

  # Convert images to HSV and get saturation channel
  refSat = cv2.cvtColor(imReference, cv2.COLOR_BGR2HSV)[:,:,1]
  imSat = cv2.cvtColor(imReg, cv2.COLOR_BGR2HSV)[:,:,1]

  # Otsu threshold
  refThresh = cv2.threshold(refSat, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
  imThresh = cv2.threshold(imSat, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

  # apply morphology open and close
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
  refThresh = cv2.morphologyEx(refThresh, cv2.MORPH_OPEN, kernel, iterations=1)
  refThresh = cv2.morphologyEx(refThresh, cv2.MORPH_CLOSE, kernel, iterations=1).astype(np.float64)
  imThresh = cv2.morphologyEx(imThresh, cv2.MORPH_OPEN, kernel, iterations=1).astype(np.float64)
  imThresh = cv2.morphologyEx(imThresh, cv2.MORPH_CLOSE, kernel, iterations=1)

  # get absolute difference between the two thresholded images
  diff = np.abs(cv2.add(imThresh,-refThresh))

  # apply morphology open to remove thin lines caused by slight misalignment of the two images
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13,13))
  diff_cleaned = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel, iterations=1).astype(np.uint8)

  # Filter using contour area and draw bounding boxes that do not touch the sides of the image
  cnts = cv2.findContours(diff_cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  cnts = cnts[0] if len(cnts) == 2 else cnts[1]
  result = imReference.copy()
  for c in cnts:
      x,y,w,h = cv2.boundingRect(c)
      cv2.rectangle(result, (x, y), (x+w, y+h), (0, 0, 255), 2)

  # show images
  cv2.imshow('reference', imReference)
  cv2.imshow('image', im)
  cv2.imshow('image_aligned', imReg)
  cv2.imshow('refThresh', refThresh)
  cv2.imshow('imThresh', imThresh)
  cv2.imshow('diff', diff)
  cv2.imshow('diff_cleaned', diff_cleaned)
  cv2.imshow('result', result)
  cv2.waitKey()

  # save images
  cv2.imwrite('pipes2_aligned.jpg', imReg)
  cv2.imwrite('pipes_diff.png', diff_cleaned)
  cv2.imwrite('pipes_result.png', result)
</code>```

Matches Image:

Image 2 (perspectively) aligned to Image 1:

Absolute difference image (cleaned):

Result:

Title: find contours of thresholded image

Body:
You can do a perspective warp to align one image to the other. Convert both to HSV and get the saturation channels. Then threshold them and get the absolute difference between them. Then get the contours and finally the bounding boxes of the contours, which are drawn on the first image. Here is how to do that with Python/OpenCV. Note, I do not have SIFT installed, so I will use ORB in its place.

Input 1 (reference image):

Input 2 (image to be warped/aligned):

import cv2
import numpy as np

MAX_FEATURES = 500
GOOD_MATCH_PERCENT = 0.15

def alignImages(im1, im2):

  # im2 is reference and im1 in to be warped to match im2
  # note: numbering is swapped in function

  # Convert images to grayscale
  im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
  im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)

  # Detect ORB features and compute descriptors.
  orb = cv2.ORB_create(MAX_FEATURES)
  keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
  keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)

  # Match features.
  matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
  matches = matcher.match(descriptors1, descriptors2, None)

  # Sort matches by score
  matches.sort(key=lambda x: x.distance, reverse=False)

  # Remove not so good matches
  numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
  matches = matches[:numGoodMatches]

  # Draw top matches
  imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
  cv2.imwrite("pipes_matches.png", imMatches)

  # Extract location of good matches
  points1 = np.zeros((len(matches), 2), dtype=np.float32)
  points2 = np.zeros((len(matches), 2), dtype=np.float32)

  for i, match in enumerate(matches):
    points1[i, :] = keypoints1[match.queryIdx].pt
    points2[i, :] = keypoints2[match.trainIdx].pt

  # Find homography
  h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)

  # Use homography
  height, width, channels = im2.shape
  im1Reg = cv2.warpPerspective(im1, h, (width, height))

  return im1Reg, h

if __name__ == '__main__':

  # Read reference image
  refFilename = "pipes1.jpg"
  print("Reading reference image : ", refFilename)
  imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)

  # Read image to be aligned
  imFilename = "pipes2.jpg"
  print("Reading image to align : ", imFilename);
  im = cv2.imread(imFilename, cv2.IMREAD_COLOR)

  # Aligned image will be stored in imReg.
  # The estimated homography will be stored in h.
  imReg, h = alignImages(im, imReference)

  # Print estimated homography
  print("Estimated homography : \n",  h)

  # Convert images to HSV and get saturation channel
  refSat = cv2.cvtColor(imReference, cv2.COLOR_BGR2HSV)[:,:,1]
  imSat = cv2.cvtColor(imReg, cv2.COLOR_BGR2HSV)[:,:,1]

  # Otsu threshold
  refThresh = cv2.threshold(refSat, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
  imThresh = cv2.threshold(imSat, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

  # apply morphology open and close
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
  refThresh = cv2.morphologyEx(refThresh, cv2.MORPH_OPEN, kernel, iterations=1)
  refThresh = cv2.morphologyEx(refThresh, cv2.MORPH_CLOSE, kernel, iterations=1).astype(np.float64)
  imThresh = cv2.morphologyEx(imThresh, cv2.MORPH_OPEN, kernel, iterations=1).astype(np.float64)
  imThresh = cv2.morphologyEx(imThresh, cv2.MORPH_CLOSE, kernel, iterations=1)

  # get absolute difference between the two thresholded images
  diff = np.abs(cv2.add(imThresh,-refThresh))

  # apply morphology open to remove thin lines caused by slight misalignment of the two images
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13,13))
  diff_cleaned = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel, iterations=1).astype(np.uint8)

  # Filter using contour area and draw bounding boxes that do not touch the sides of the image
  cnts = cv2.findContours(diff_cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  cnts = cnts[0] if len(cnts) == 2 else cnts[1]
  result = imReference.copy()
  for c in cnts:
      x,y,w,h = cv2.boundingRect(c)
      cv2.rectangle(result, (x, y), (x+w, y+h), (0, 0, 255), 2)

  # show images
  cv2.imshow('reference', imReference)
  cv2.imshow('image', im)
  cv2.imshow('image_aligned', imReg)
  cv2.imshow('refThresh', refThresh)
  cv2.imshow('imThresh', imThresh)
  cv2.imshow('diff', diff)
  cv2.imshow('diff_cleaned', diff_cleaned)
  cv2.imshow('result', result)
  cv2.waitKey()

  # save images
  cv2.imwrite('pipes2_aligned.jpg', imReg)
  cv2.imwrite('pipes_diff.png', diff_cleaned)
  cv2.imwrite('pipes_result.png', result)

Matches Image:

Image 2 (perspectively) aligned to Image 1:

Absolute difference image (cleaned):

Result:


问:
How to prevent tracking sensitive data in URLs?
Some URLs in my single-page-app (SPA) contain sensitive information like an access token, user information, etc.

Examples:

```<code>/callback#access_token=HBVYTU2Rugv3gUbvgIUY
/?email=username@example.com
</code>```

I see that hotjar allows suppressing DOM elements and images from tracked data. Is it possible to hide params in URL or at least disable tracking for some pages?

答:
If you control the page and order of scripts, you could read the data from the url then delete it before anything else can get to it.

proofOfConcept.html

    Link to private

```

Of course the Link to private should not exist as is.  Also, this does break refresh and  most navigation in general, though there are ways to catch and save that.

Body:
Some URLs in my single-page-app (SPA) contain sensitive information like an access token, user information, etc.

Examples:

/callback#access_token=HBVYTU2Rugv3gUbvgIUY
/?email=username@example.com

I see that hotjar allows suppressing DOM elements and images from tracked data. Is it possible to hide params in URL or at least disable tracking for some pages?

Body:
If you control the page and order of scripts, you could read the data from the url then delete it before anything else can get to it.

proofOfConcept.html

<script id="firstThingToLoad.js">
    console.log(window.location.href);
    const keyRegex = /key=[^&]*/;
    const key = window.location.href.match(keyRegex);
    console.log("I have key", key);

    const href = window.location.href.replace(keyRegex, "");
    history.replaceState({}, "", href);
</script>

<script id="someSnoopyCode.js">
    console.log("I'm snooping: ", window.location.href);
</script>

<body>
    <a href="/?key=secret">Link to private</a>
</body>

Of course the Link to private should not exist as is.  Also, this does break refresh and  most navigation in general, though there are ways to catch and save that.


问:
How to fix the issue:Your PHP installation appears to be missing the MySQL extension
Environment:os and apache and php and mariadb version.

```<code>uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies
</code>```

Login mariadb with password and input status:

```<code>Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9
</code>```

Check php-mysql:

```<code>sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]
</code>```

Get the mysql.so library:

```<code>sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so
</code>```

Chekc all modules which contain mysql:

```<code>php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini
</code>```

Rewrite

```<code>; ... or under UNIX:
;
;extension=mysql.so
</code>```

as

```<code>extension=mysqli.so
</code>```

or

```<code>extension=mysqlnd.so
</code>```

or

```<code>extension=pdo_mysql.so
</code>```

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?

答:
As others have stated, though without a source, the mysql extension (ext/mysql) was deprecated in 5.5 (per RFC: ext/mysql deprecation) and removed in 7.0 (per RFC: Remove deprecated functionality in PHP 7).

(This is the git commit that actually removed ext/mysql from PHP, as linked to from the removal RFC - this link was added by the RFC author [nikic])

This is also mentioned all throughout the ext/mysql manual on php.net, though it doesn't link to any other notes concerning the deprecation and subsequent removal.

If you view the backwards-incompatible changes page for 7.0 then it further mentions that all mysql extension functions were removed, and provides a link to help in choosing a new MySQL API. This provides the support and path necessary for moving on from ext/mysql.

Body:
Environment:os and apache and php and mariadb version.

uname -a
Linux MiWiFi-R3-srv 4.9.0-11-amd64 #1 SMP Debian 4.9.189-3+deb9u2 (2019-11-11) x86_64 GNU/Linux

sudo apachectl -v
Server version: Apache/2.4.25 (Debian)
Server built:   2019-10-13T15:43:54

php -v
PHP 7.0.33-0+deb9u6 (cli) (built: Oct 24 2019 18:50:20) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0+deb9u6, Copyright (c) 1999-2017, by Zend Technologies

Login mariadb with password and input status:

Server:         MariaDB
Server version:     10.1.41-MariaDB-0+deb9u1 Debian 9.9

Check php-mysql:

sudo dpkg -l php-mysql
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  php-mysql      1:7.0+49     all          MySQL module for PHP [default]

Get the mysql.so library:

sudo find  /  -name  "*mysql.so"
/usr/lib/php/20151012/pdo_mysql.so

Chekc all modules which contain mysql:

php -m |grep  mysql
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php/20151012/php_pdo_mysql.so' - /usr/lib/php/20151012/php_pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0
mysqli
mysqlnd
pdo_mysql

sudo vim  /etc/php/7.0/fpm/php.ini

Rewrite

; ... or under UNIX:
;
;extension=mysql.so

as

extension=mysqli.so

or

extension=mysqlnd.so

or

extension=pdo_mysql.so

Restart apache2 and mariadb database,the issue remains ,none of the three format can work,how to fix then?


问:
Data binding could not find identifier "view"
```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<data>
    <variable
        name = "registrationViewModel"
        type="com.android.freecommunity.ui.auth.AuthViewModel"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    tools:context=".ui.auth.Register">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="352dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/intro_background" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="32dp"
        android:layout_marginEnd="32dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/round_layout_container"
        android:clipChildren="false"
        android:clipToPadding="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0">

        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="45dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/user"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Fullname"
            android:text="@={registrationViewModel.fullName}"
            android:inputType="phone"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView2" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/email"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Email Address"
            android:text="@={registrationViewModel.email}"
            android:inputType="textEmailAddress"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText" />

        <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edge_button"
            android:text="REGISTER"
            android:onClick="@={(view)-> registrationViewModel.onRegisterButtonClicked(view)}"
            android:textColor="@android:color/white"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/spinner2" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:text="Already a member"
            android:textColor="@color/not_a_member"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button" />

        <TextView
            android:id="@+id/textView12"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:text="Login"
            android:onClick="@{registrationViewModel::onLogin}"
            android:textColor="@color/not_a_member"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button" />

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:text="Forget Password ?"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView12" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="horizontal"
            app:layout_constraintGuide_begin="81dp" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:translationY="-10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:srcCompat="@drawable/logo_holder"
            tools:layout_editor_absoluteY="-22dp" />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/phone"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Phone"
            android:text="@={registrationViewModel.phoneNumber}"
            android:inputType="phone"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText2" />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/calendar"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="DOB"
            android:text="@={registrationViewModel.date_of_birth}"
            android:inputType="date"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText3" />

        <EditText
            android:id="@+id/editText5"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/address"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Home Address"
            android:text="@={registrationViewModel.address}"
            android:inputType="textPersonName"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText4" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="345dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/round_edit_text"
            android:drawSelectorOnTop="true"
            android:entries="@array/work_category_array"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText5" />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:drawSelectorOnTop="true"
            android:entries="@array/daily_payment_plan"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/spinner" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView6" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Thats my xml

```<code> fun onRegisterButtonClicked(view: View){

    authListener?.onStarted()

    if (fullName.isNullOrEmpty()){
        authListener?.onFailure("FullName is required")
        return
    }
    if (email.isNullOrEmpty()){
        authListener?.onFailure("Email is required")
        return
    }

    if (password.isNullOrEmpty()){
        authListener?.onFailure("Password is required")
        return
    }
</code>```

This is where im trying to use the function inside my view model, i've tried all other way to do the onclick in my xml, but i keep getting errors.
[please ignore]

This is where im trying to use the function inside my view model, i've tried all other way to do the onclick in my xml, but i keep getting errors.
This is where im trying to use the function inside my view model, i've tried all other way to do the onclick in my xml, but i keep getting errors.

答:
So since you didn't provide the error log you get, I will try to add potential cause as mentioned in the question title

Data binding could not find identifier “view”

In your layout you need to remove view from the button click callback and the equal sign is useless, so replace below

```<code><Button
    android:id="@+id/button"
    android:onClick="@={(view)-> registrationViewModel.onRegisterButtonClicked(view)}" />
</code>```

with

```<code><Button
    android:id="@+id/button"
    android:onClick="@{()-> registrationViewModel.onRegisterButtonClicked()}" />
</code>```

or you also use

```<code><Button
    android:id="@+id/button"
    android:onClick="@{registrationViewModel::onRegisterButtonClicked}" />
</code>```

I omitted other attributes, so keep them unchanged.

Body:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<data>
    <variable
        name = "registrationViewModel"
        type="com.android.freecommunity.ui.auth.AuthViewModel"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    tools:context=".ui.auth.Register">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="352dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/intro_background" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayout"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginStart="32dp"
        android:layout_marginEnd="32dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/round_layout_container"
        android:clipChildren="false"
        android:clipToPadding="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0">

        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="45dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/user"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Fullname"
            android:text="@={registrationViewModel.fullName}"
            android:inputType="phone"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView2" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/email"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Email Address"
            android:text="@={registrationViewModel.email}"
            android:inputType="textEmailAddress"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText" />

        <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edge_button"
            android:text="REGISTER"
            android:onClick="@={(view)-> registrationViewModel.onRegisterButtonClicked(view)}"
            android:textColor="@android:color/white"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/spinner2" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:text="Already a member"
            android:textColor="@color/not_a_member"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button" />

        <TextView
            android:id="@+id/textView12"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:text="Login"
            android:onClick="@{registrationViewModel::onLogin}"
            android:textColor="@color/not_a_member"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/button" />

        <TextView
            android:id="@+id/textView13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:text="Forget Password ?"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView12" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="horizontal"
            app:layout_constraintGuide_begin="81dp" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:translationY="-10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:srcCompat="@drawable/logo_holder"
            tools:layout_editor_absoluteY="-22dp" />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/phone"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Phone"
            android:text="@={registrationViewModel.phoneNumber}"
            android:inputType="phone"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText2" />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/calendar"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="DOB"
            android:text="@={registrationViewModel.date_of_birth}"
            android:inputType="date"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText3" />

        <EditText
            android:id="@+id/editText5"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/round_edit_text"
            android:drawableLeft="@drawable/address"
            android:drawablePadding="16dp"
            android:ems="10"
            android:hint="Home Address"
            android:text="@={registrationViewModel.address}"
            android:inputType="textPersonName"
            android:paddingStart="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText4" />

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="345dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/round_edit_text"
            android:drawSelectorOnTop="true"
            android:entries="@array/work_category_array"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/editText5" />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:drawSelectorOnTop="true"
            android:entries="@array/daily_payment_plan"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/spinner" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView6" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Thats my xml

 fun onRegisterButtonClicked(view: View){

    authListener?.onStarted()

    if (fullName.isNullOrEmpty()){
        authListener?.onFailure("FullName is required")
        return
    }
    if (email.isNullOrEmpty()){
        authListener?.onFailure("Email is required")
        return
    }

    if (password.isNullOrEmpty()){
        authListener?.onFailure("Password is required")
        return
    }

This is where im trying to use the function inside my view model, i've tried all other way to do the onclick in my xml, but i keep getting errors.
[please ignore]

This is where im trying to use the function inside my view model, i've tried all other way to do the onclick in my xml, but i keep getting errors.
This is where im trying to use the function inside my view model, i've tried all other way to do the onclick in my xml, but i keep getting errors.

Body:
So since you didn't provide the error log you get, I will try to add potential cause as mentioned in the question title

Data binding could not find identifier “view”

In your layout you need to remove view from the button click callback and the equal sign is useless, so replace below

<Button
    android:id="@+id/button"
    android:onClick="@={(view)-> registrationViewModel.onRegisterButtonClicked(view)}" />

with

<Button
    android:id="@+id/button"
    android:onClick="@{()-> registrationViewModel.onRegisterButtonClicked()}" />

or you also use

<Button
    android:id="@+id/button"
    android:onClick="@{registrationViewModel::onRegisterButtonClicked}" />

I omitted other attributes, so keep them unchanged.


问:
Not able to build grails 2.3.7 project since the maven central repository has moved to https
I am not able to build my 2.3.7 grails projects since the maven central repository has moved to https.
I tried the recommandations on this post :  Requests to http://repo1.maven.org/maven2/ return a 501 HTTPS Required status and a body

However I'am still having an issue because the maven repo is coded in the framework jars ( grails-aether-2.3.7-sources.jar )
The class is org.codehaus.groovy.grails.resolve.maven.aether.config.RepositoriesConfinguration.groovy.

```<code>RemoteRepository mavenCentral(Closure configurer = null) {
    final existing = repositories.find { ArtifactRepository ar -> ar.id == "mavenCentral" }
    if (!existing) {
        final repositoryBuilder = new RemoteRepository.Builder("mavenCentral", "default", "http://repo1.maven.org/maven2/")

        configureRepository(repositoryBuilder, configurer)
        final repository = repositoryBuilder.build()
        repositories << repository
        return repository
    }
    else {
        return existing
    }
}
</code>```

This file is readonly.

How can I fix this issue? I cannot migrate the project to a new Grails version for several reasons.
This is the error I got.

16:14:10 + /opt/grails-2.3.7/bin/grails --stacktrace clean 16:14:13 |
  Loading Grails 2.3.7 16:14:17 | Configuring classpath 16:14:20 | Error
  Resolve error obtaining dependencies: Failed to read artifact
  descriptor for xalan:serializer:jar:2.7.1 (NOTE: Stack trace has been
  filtered. Use --verbose to see entire trace.) 16:14:20
  org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to
  read artifact descriptor for xalan:serializer:jar:2.7.1 16:14:20  at
  org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:335)
  16:14:20  at
  org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:217)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:466)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:261)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies(DefaultRepositorySystem.java:317)
  16:14:20  at
  grails.util.BuildSettings.doResolve(BuildSettings.groovy:513) 16:14:20
    at grails.util.BuildSettings.doResolve(BuildSettings.groovy) 16:14:20
    at
  grails.util.BuildSettings$_getDefaultBuildDependencies_closure17.doCall(BuildSettings.groovy:774)
  16:14:20  at
  grails.util.BuildSettings$_getDefaultBuildDependencies_closure17.doCall(BuildSettings.groovy)
  16:14:20  at
  grails.util.BuildSettings.getDefaultBuildDependencies(BuildSettings.groovy:768)
  16:14:20  at
  grails.util.BuildSettings.getBuildDependencies(BuildSettings.groovy:673)
  16:14:20 Caused by:
  org.eclipse.aether.resolution.ArtifactResolutionException: Could not
  transfer artifact xalan:serializer:pom:2.7.1 from/to mavenCentral
  (http://repo1.maven.org/maven2/ ): HTTPS Required (501) 16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:460)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:262)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:239)
  16:14:20  at
  org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:320)
  16:14:20  ... 10 more 16:14:20 Caused by:
  org.eclipse.aether.transfer.ArtifactTransferException: Could not
  transfer artifact xalan:serializer:pom:2.7.1 from/to mavenCentral
  (http://repo1.maven.org/maven2/ ): HTTPS Required (501) 16:14:20  at
  org.eclipse.aether.connector.basic.ArtifactTransportListener.transferFailed(ArtifactTransportListener.java:43)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:342)
  16:14:20  at
  org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:67)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute(BasicRepositoryConnector.java:649)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector.get(BasicRepositoryConnector.java:247)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:536)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:437)
  16:14:20  ... 13 more 16:14:20 Caused by:
  org.apache.http.client.HttpResponseException: HTTPS Required (501)
  16:14:20  at
  org.eclipse.aether.transport.http.HttpTransporter.handleStatus(HttpTransporter.java:404)
  16:14:20  at
  org.eclipse.aether.transport.http.HttpTransporter.execute(HttpTransporter.java:298)
  16:14:20  at
  org.eclipse.aether.transport.http.HttpTransporter.implGet(HttpTransporter.java:250)
  16:14:20  at
  org.eclipse.aether.spi.connector.transport.AbstractTransporter.get(AbstractTransporter.java:59)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask(BasicRepositoryConnector.java:418)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:337)
  16:14:20  ... 18 more

答:
I was dealing with Grails 2.3.11 and I just added the following repository and changed any other external repository URLs to https:

```<code>repositories {
        mavenRepo "https://repo.grails.org/grails/core"
</code>```

Also I had to use Java 8 due to the TLS default being 1.2 in Java 8.  The bummer is Grails 2.3.7 does not support Java 8.

Body:
I am not able to build my 2.3.7 grails projects since the maven central repository has moved to https.
I tried the recommandations on this post :  Requests to http://repo1.maven.org/maven2/ return a 501 HTTPS Required status and a body

However I'am still having an issue because the maven repo is coded in the framework jars ( grails-aether-2.3.7-sources.jar )
The class is org.codehaus.groovy.grails.resolve.maven.aether.config.RepositoriesConfinguration.groovy.

RemoteRepository mavenCentral(Closure configurer = null) {
    final existing = repositories.find { ArtifactRepository ar -> ar.id == "mavenCentral" }
    if (!existing) {
        final repositoryBuilder = new RemoteRepository.Builder("mavenCentral", "default", "http://repo1.maven.org/maven2/")

        configureRepository(repositoryBuilder, configurer)
        final repository = repositoryBuilder.build()
        repositories << repository
        return repository
    }
    else {
        return existing
    }
}

This file is readonly.

How can I fix this issue? I cannot migrate the project to a new Grails version for several reasons.
This is the error I got.

16:14:10 + /opt/grails-2.3.7/bin/grails --stacktrace clean 16:14:13 |
  Loading Grails 2.3.7 16:14:17 | Configuring classpath 16:14:20 | Error
  Resolve error obtaining dependencies: Failed to read artifact
  descriptor for xalan:serializer:jar:2.7.1 (NOTE: Stack trace has been
  filtered. Use --verbose to see entire trace.) 16:14:20
  org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to
  read artifact descriptor for xalan:serializer:jar:2.7.1 16:14:20  at
  org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:335)
  16:14:20  at
  org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:217)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:466)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:261)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies(DefaultRepositorySystem.java:317)
  16:14:20  at
  grails.util.BuildSettings.doResolve(BuildSettings.groovy:513) 16:14:20
    at grails.util.BuildSettings.doResolve(BuildSettings.groovy) 16:14:20
    at
  grails.util.BuildSettings$_getDefaultBuildDependencies_closure17.doCall(BuildSettings.groovy:774)
  16:14:20  at
  grails.util.BuildSettings$_getDefaultBuildDependencies_closure17.doCall(BuildSettings.groovy)
  16:14:20  at
  grails.util.BuildSettings.getDefaultBuildDependencies(BuildSettings.groovy:768)
  16:14:20  at
  grails.util.BuildSettings.getBuildDependencies(BuildSettings.groovy:673)
  16:14:20 Caused by:
  org.eclipse.aether.resolution.ArtifactResolutionException: Could not
  transfer artifact xalan:serializer:pom:2.7.1 from/to mavenCentral
  (http://repo1.maven.org/maven2/ ): HTTPS Required (501) 16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:460)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:262)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:239)
  16:14:20  at
  org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:320)
  16:14:20  ... 10 more 16:14:20 Caused by:
  org.eclipse.aether.transfer.ArtifactTransferException: Could not
  transfer artifact xalan:serializer:pom:2.7.1 from/to mavenCentral
  (http://repo1.maven.org/maven2/ ): HTTPS Required (501) 16:14:20  at
  org.eclipse.aether.connector.basic.ArtifactTransportListener.transferFailed(ArtifactTransportListener.java:43)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:342)
  16:14:20  at
  org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:67)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute(BasicRepositoryConnector.java:649)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector.get(BasicRepositoryConnector.java:247)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:536)
  16:14:20  at
  org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:437)
  16:14:20  ... 13 more 16:14:20 Caused by:
  org.apache.http.client.HttpResponseException: HTTPS Required (501)
  16:14:20  at
  org.eclipse.aether.transport.http.HttpTransporter.handleStatus(HttpTransporter.java:404)
  16:14:20  at
  org.eclipse.aether.transport.http.HttpTransporter.execute(HttpTransporter.java:298)
  16:14:20  at
  org.eclipse.aether.transport.http.HttpTransporter.implGet(HttpTransporter.java:250)
  16:14:20  at
  org.eclipse.aether.spi.connector.transport.AbstractTransporter.get(AbstractTransporter.java:59)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask(BasicRepositoryConnector.java:418)
  16:14:20  at
  org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:337)
  16:14:20  ... 18 more

Body:
I was dealing with Grails 2.3.11 and I just added the following repository and changed any other external repository URLs to https:

repositories {
        mavenRepo "https://repo.grails.org/grails/core"

Also I had to use Java 8 due to the TLS default being 1.2 in Java 8.  The bummer is Grails 2.3.7 does not support Java 8.


问:
how to write wifi config to nfc tag using android studio and java?
how to write wifi hotspot configuration to nfc tag using app written in java? ive read Near Field Communication with Android Cookbook and its chapter about configuring a wifi network. but this example is not working anymore and its kinda hard for me to determine the reason why.
app structure:
activity_main.xml with ssid and password input fields,a spinner with security type and a button to start writing
MainActivity.java with code that writes this info to nfc tag

is there a simple way to solve this?

ive found this file:
https://github.com/bparmentier/WiFiKeyShare/blob/master/app/src/main/java/be/brunoparmentier/wifikeyshare/utils/NfcUtils.java

but have no idea how to properly change this code to met my needs

答:
Working Example of how it is done in the Android OS (what my swipe and presses run)

http://androidxref.com/9.0.0_r3/xref/packages/apps/Settings/src/com/android/settings/wifi/WriteWifiConfigToNfcDialog.java