问:
How to synchronize custom ID column with table's primary key column
Primarily, sorry for being too descriptive.
I am storing patient's info in sql db by creating a custom ID field "PatientID" and I have a primary key field "ID". PatientID has a pattern "PID-1" or "PID-2" so on and so forth. I want to synchronize both IDs. Like if table's ID for "John" is 4 then its patientID should also be "PID-4". For this, I have done some coding like if no record exist then start saving patientID from "PID-1" and then for all next record first find the max id of patient from ID field and increment it by 1 and concatenate it with "PID" + (tableID+1).

```<code> ID    PatientID
 1      PID-1
 2      PID-2
 3      PID-3
 4      PID-4
</code>```

Now, for an instance, while adding more record an exception is thrown although record is not saved but ID gets incremented. And here comes the problem. Suppose, some bug comes and record for ID 5 could not be saved in the db, after fixing that bug when program runs correctly it put the ID 6 rather than 5. And for the patientID it puts "PID-5" due to MAX query. From here both IDs start being distinct. Same problem for deleting, if I am deleting last record from above table i.e, 4 and PID-4, the next record's ID would be 5 while PatientID would be "PID-4". This was the whole problematic picture of handling both IDs from my side. Any alternate solution or any modification in my idea or any better idea then mine would be highly appreciated.

答:
In SQL Server you could create a computed column for this purpose:

```<code>ALTER TABLE Patient DROP COLUMN PatientID;
GO
ALTER TABLE Patient ADD COLUMN PatientID AS ('PID-'+CAST(ID AS VARCHAR(15));
</code>```

For more info regarding computed columns, please have a look here.

Note: I assumed that your table's name is Patient. You have to change this correspondingly if this is not the name of your table.

Body:
Primarily, sorry for being too descriptive.
I am storing patient's info in sql db by creating a custom ID field "PatientID" and I have a primary key field "ID". PatientID has a pattern "PID-1" or "PID-2" so on and so forth. I want to synchronize both IDs. Like if table's ID for "John" is 4 then its patientID should also be "PID-4". For this, I have done some coding like if no record exist then start saving patientID from "PID-1" and then for all next record first find the max id of patient from ID field and increment it by 1 and concatenate it with "PID" + (tableID+1).

 ID    PatientID
 1      PID-1
 2      PID-2
 3      PID-3
 4      PID-4

Now, for an instance, while adding more record an exception is thrown although record is not saved but ID gets incremented. And here comes the problem. Suppose, some bug comes and record for ID 5 could not be saved in the db, after fixing that bug when program runs correctly it put the ID 6 rather than 5. And for the patientID it puts "PID-5" due to MAX query. From here both IDs start being distinct. Same problem for deleting, if I am deleting last record from above table i.e, 4 and PID-4, the next record's ID would be 5 while PatientID would be "PID-4". This was the whole problematic picture of handling both IDs from my side. Any alternate solution or any modification in my idea or any better idea then mine would be highly appreciated.

Body:
In SQL Server you could create a computed column for this purpose:

ALTER TABLE Patient DROP COLUMN PatientID;
GO
ALTER TABLE Patient ADD COLUMN PatientID AS ('PID-'+CAST(ID AS VARCHAR(15));

For more info regarding computed columns, please have a look here.

Note: I assumed that your table's name is Patient. You have to change this correspondingly if this is not the name of your table.


来源: stackexchange

问:
pass two variable in getElementById function
I have a code, If any one click on anchor tag then a pop-up opens. It is correctly working.

But I want some variables, in pop-up after click on anchor tag.

My PHP code are:

```<code><?php
 include("connection.php");
  $query=mysql_query("select * from tenant where email1='$username'") or die(mysql_error());
 while($result=mysql_fetch_array($query))
 {
 extract($result);
 ?>
 <a onClick="document.getElementById('id01').style.display='block'" style="width:auto;"><?php echo $first_name.' '.$last_name; ?></a>?>
 <?php } ?>
</code>```

In PHP code- some variables should be pass through onClick. By which, in the pop-up I can fetch data from table related selected variables.

My Pop-up window are:

```<code>   <div id="id01" class="modal">

     <form class="modal-content animate" action="xyz.php">
     <div class="imgcontainer">
  <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>

    </div>

     <div class="container">

       <div>Content</div>

     </div>
    </form>
   </div>
</code>```

Javascript code:

```<code> <script>
 // Get the modal
 var modal = document.getElementById('id01');

 // When the user clicks anywhere outside of the modal, close it
 window.onclick = function(event) {
if (event.target == modal) {
    modal.style.display = "none";
 }
 }
  </script>
</code>```

Please help.
Thank you.

答:
If I did correctly understand you, one of the solutions consists to create a JavaScript function and call it from your PHP page by passing argument like this:

PHP CODE:

```<code><?php
include("connection.php");
$query=mysql_query("select * from tenant where email1='$username'") or die(mysql_error());

while($result=mysql_fetch_array($query))
{
  extract($result);
?>
<a href="#" onClick="doSomething('<?php echo $zip_code; ?>')" style="width:auto;"><?php echo $first_name.' '.$last_name; ?></a>?>
<?php
}
?>
</code>```

JavaScript Code:

You are now able to use the arg argument for fetching data as you want.

```<code><script>
    function doSomething(arg) {

        var modal = document.getElementById('id01');

        modal.style.display = 'block';
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {

        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</code>```

More information about functions can be found Here

Note: Please PDO and Prepared Statements instead of using mysql_* functions

ContentLicense: CC BY-SA 3.0

Body:
I have a code, If any one click on anchor tag then a pop-up opens. It is correctly working.

But I want some variables, in pop-up after click on anchor tag.

My PHP code are:

<?php
 include("connection.php");
  $query=mysql_query("select * from tenant where email1='$username'") or die(mysql_error());
 while($result=mysql_fetch_array($query))
 {
 extract($result);
 ?>
 <?php echo $first_name.' '.$last_name; ?>?>
 <?php } ?>

In PHP code- some variables should be pass through onClick. By which, in the pop-up I can fetch data from table related selected variables.

My Pop-up window are:

     <form class="modal-content animate" action="xyz.php">

  ×

Content

    </form>

Javascript code:

Please help.
Thank you.

Body:
If I did correctly understand you, one of the solutions consists to create a JavaScript function and call it from your PHP page by passing argument like this:

PHP CODE:

<?php
include("connection.php");
$query=mysql_query("select * from tenant where email1='$username'") or die(mysql_error());

while($result=mysql_fetch_array($query))
{
  extract($result);
?>
<a href="#" onClick="doSomething('<?php echo $zip_code; ?>')" style="width:auto;"><?php echo $first_name.' '.$last_name; ?></a>?>
<?php
}
?>

JavaScript Code:

You are now able to use the arg argument for fetching data as you want.

<script>
    function doSomething(arg) {

        var modal = document.getElementById('id01');

        modal.style.display = 'block';
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {

        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

More information about functions can be found Here

Note: Please PDO and Prepared Statements instead of using mysql_* functions


问:
How to handle database migrations in Spring Boot with Hibernate?
My database background comes from the Django framework (python). In Django, getting started with database migrations was easy: Django migrations. The Django framework provided tool for creating the migrations based on your models, and also a tool to apply the migrations on your database. I think this way of doing worked in both development and in production. You did not have to write migrations by yourself, the framework created them for you.

Now I have started a project with Spring Boot and Hibernate. I configure my application to use hibernate with JPA. With these settings, I now would need to know how does my framework handle database migrations? I mean if I change a column, either it's type, or even might remove it, then how do I migrate the database to the change? I know that spring boot will automatically detect column changes on startup, and create columns that do not exist based on the models (Entity's). I guess it has something to do with variable

spring.jpa.hibernate.ddl-auto

But how does it handle the existing database objects? Does it add the column to them too, and with what value? The default value I set? What if I change the column type? Can it then handle the change? These settings and spring-boot automated database management probably are not enough in the long run?

What I want to know is, that what are the best practices on how to handle database migrations with Spring Boot and hibernate combination? I believe there is a standard how most of the people with this combination handle the migrations? I hope it is as easy as with Django... I know about flyway, but don't know if I really need it, or if it is used much with this combination of mine (including spring boot and hibernate).

答:
Liquibase or Flyway are the two main options for versioning/handling database migrations. ddl-auto is quick and dirty, but it does not, nor can it, take into account everything that needs to be handled. THere's also the chance of race-conditions (two instances trying to update the DDL at the same time).

This answer goes into more detail about ddl-auto in a production environment, and why you shouldn't.

Hibernate: hbm2ddl.auto=update in production?

https://www.credera.com/blog/technology-insights/java/liquibase-fed-inconsistent-schemas/ has bit more info on the why/concepts.


问:
How do I appropriately interact with PayPal IPN for the purpose of serial generation?
Having a bit of trouble with the PayPal IPN.  I've seen variations on these questions listed about a million times, but not the answers I'm looking for.  As usual this may be a case of asking a question regarding the wrong thing, but I'm hoping there are some super geniuses out there that can assist.

Anyway, I basically need to set up the purchase of some readily available software, and, once the transaction is complete send them a serial.  One would think this is simple, but given the criteria it has proven anything but.  Basically the steps are as follows:

1) Custom form on website to enter personal (but not too =P) info

2) Forward them to PayPal site to make purchase

3) Upon successful transaction AUTOMATICALLY send them to a serial page and/or send an email with the registration.

I've looked at various IPN classes (using PHP btw) and nothing seems very straightforward, and it doesn't seem that PayPal likes any kind of custom variables being passed, nor does it seem to automatically send someone elsewhere after the purchase.  Also, which ID should I be looking at if/when the process finally does come back around?

Perhaps I need the "Pro" account?  In any event, please make no assumptions regarding my knowledge of PayPal IPN.  I'd simply like a class (hopefully one I haven't tried already) or at least some more straightforward (and concise) documentation on how to accomplish this.

Best.

EDIT #1:

Does anyone have any information on enabling the QUANTITY field during a purchase?  For some reason it's stuck at 1 and will not allow a change.  I'm not passing anything for quantity atm.

答:
I suggest that you use ezimerchant -> www.ezimerchant.com

It's free to sign up. They have an excellent API that allows you to do all that, they hook straight in with paypal so you dont have to bother learning their complex api.

To get you started, you'd use the OrderCreate API, once you signed up you can access the documentation here:

https://api.ezimerchant.com/[merchantid]/orders/edit

Don't forget to add your merchant id.

then it's as simple as supplying a "RETURNURL" and a NOTIFYURL. The Notify url is a php script that accepts a ping back with the order details, you just check if payment was successful and email out the serial code.

I have some code in php for this stuff so let me know if you go down this path.

ContentLicense: CC BY-SA 2.5


问:
pg_restore: [archiver] input file does not appear to be a valid archive error in PostgreSQL using Pgadmin 4
I am trying to open a SQL Script of PostgreSQL (.sql file) that contains the Create Database and INSERT statements but when I try to restore the database using PgAdmin 4 it gives me error stating "pg_restore: [archiver] input file does not appear to be a valid archive" . I selected the following fields in the Restore Database dialog box:

Format - as Custom or tar

Filename - C:\Users\parwa\Desktop\DWBI\Assignment - 2(Chinook SQL - 2)\Question Content\Chinook_PostgreSql.sql

Number of Jobs - (left this field blank)

Role name - Postgres

I am not sure why it's giving me this error. Any help regarding this will be greatly appreciated. Thanks!

答:
In pgAdmin 4 the Restore Dialog is a UI interface to the pg_restore command line utility (https://www.postgresql.org/docs/9.2/static/app-pgrestore.html), I don't think it deals with sql files directly.

The documentation says

You can use the Query Tool to play back the script created during a plain-text backup made with the Backup dialog. For more information about backing up or restoring, please refer to the documentation for pg_dump or pg_restore.

Which indicates that to restore the sql file you have you need to use the Query Tool instead.

Tools -> Query Tool and you can open or paste the file in there and run it.


问:
Web Form Not Inheriting Master Page on Microsoft Visual Studio
Alright. I am making a school project using Visual Web Developer, and I need to use a Master Page. When I make a new web form based on my master page, it inherits the colors of the master page, but there is a table which is not inherited. Here is my master page code:

```<code><%@ Master Language="VB" CodeFile="Master1.master.vb" Inherits="Master1" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server" background-color: #00FF00;>
        <title></title>
        <asp:ContentPlaceHolder id="head" runat="server">
        </asp:ContentPlaceHolder>
        <style type="text/css">
            .auto-style2 {
                height: 57px;
                width: 2363px;
            }
            .auto-style3 {
                height: 57px;
                width: 48px;
            }
            .auto-style4 {
                height: 48px;
            }
            .newStyle1 {
                background-color: #FF00FF;
            }
            .auto-style5 {
                width: 369px;
                height: 214px;
            }
        </style>
    </head>
    <body style="background-color: blue;">
        <form id="form1" runat="server">
        <div class="newStyle1">
            <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

                <table class="newStyle1">
                    <tr>
                        <td class="auto-style4" colspan="2">
                            <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
                                <Items>
                                    <asp:MenuItem NavigateUrl="Default.aspx" Text="Home" Value="Home"></asp:MenuItem>
                                    <asp:MenuItem NavigateUrl="About.aspx" Text="About" Value="About"></asp:MenuItem>
                                </Items>
                            </asp:Menu>
                        </td>
                    </tr>
                    <tr>
                        <td class="auto-style3">
                            <img alt="CS Logo" class="auto-style5" src="cSk.png" /></td>
                        <td class="auto-style2">
                            <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                            </asp:ContentPlaceHolder>
                        </td>
                    </tr>
                    <tr>
                        <td class="auto-style4" colspan="2"></td>
                    </tr>
                </table>

            </asp:ContentPlaceHolder>
        </div>
        </form>
    </body>
    </html>
</code>```

Master Page VB Code:

```<code>Partial Class Master1
    Inherits System.Web.UI.MasterPage
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    End Sub
End Class

 Web Form Attempted to Inherit Master Page:

%@ Page Title="" Language="VB" MasterPageFile="~/Master1.master" %>

<script runat="server">

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>
</code>```

答:
You should only place HTML elements inside placeholders in a master page if you wish to overwrite this content in subsequent child pages.

The problem with your child page is that it overwrites the placeholder containing the table with empty HTML.

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>

If you wish to inherit content, do not place shared content in placeholders.

If you must adopt this practice of placing shared content in placeholders, do not overwrite this content in the child page. So in your example:

<s><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content></s>

Would display the table in the master page.

Hope that helps.

Body:
Alright. I am making a school project using Visual Web Developer, and I need to use a Master Page. When I make a new web form based on my master page, it inherits the colors of the master page, but there is a table which is not inherited. Here is my master page code:

<%@ Master Language="VB" CodeFile="Master1.master.vb" Inherits="Master1" %>

    <!DOCTYPE html>

        <title></title>
        <asp:ContentPlaceHolder id="head" runat="server">
        </asp:ContentPlaceHolder>

        <form id="form1" runat="server">

            <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

                            <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
                                <Items>
                                    <asp:MenuItem NavigateUrl="Default.aspx" Text="Home" Value="Home"></asp:MenuItem>
                                    <asp:MenuItem NavigateUrl="About.aspx" Text="About" Value="About"></asp:MenuItem>
                                </Items>
                            </asp:Menu>

                            <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
                            </asp:ContentPlaceHolder>

            </asp:ContentPlaceHolder>

        </form>

Master Page VB Code:

Partial Class Master1
    Inherits System.Web.UI.MasterPage
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    End Sub
End Class

 Web Form Attempted to Inherit Master Page:

%@ Page Title="" Language="VB" MasterPageFile="~/Master1.master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>


问:
Connection string in EF
I’m a student. And this is my first production level project. I’m developing a WPF application using Entity Framework, which will be running only on a tab. I have problem in choosing a database. Since this application is going to run only on one device and cloud database cannot be used, what would be the best option?

If I use mssql the connection string in my development environment and production environment differs. Am I wrong? If I’m right what would be the solution for having a connection string that works identically in both environments.

Thanks in advance.

答:
Usually you always end up with a different connection string for development (ex: without password) and for production (ex: long password).

C# handles this with App.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="yourname" connectionString="..." providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
</configuration>
</code>```

And then you'll add a transformation file that changes certain values of your App.config depending on the environment where you'll deploy it.

Typically there is an App.Release.config file that updates the connectionString when built in Release mode (versus Debug mode)

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
    <add name="yourname"
      connectionString="productionConnectionStringHere"
      xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>
</code>```

As to which database you're going to use: It doesn't really matter. Have a look at Sqlite. Or Mongo if you don't have tabular data.

Title: Connection string in EF

Body:
Usually you always end up with a different connection string for development (ex: without password) and for production (ex: long password).

C# handles this with App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="yourname" connectionString="..." providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
</configuration>

And then you'll add a transformation file that changes certain values of your App.config depending on the environment where you'll deploy it.

Typically there is an App.Release.config file that updates the connectionString when built in Release mode (versus Debug mode)

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
    <add name="yourname"
      connectionString="productionConnectionStringHere"
      xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>

As to which database you're going to use: It doesn't really matter. Have a look at Sqlite. Or Mongo if you don't have tabular data.


问:
How to read another application database in android
I need to read sqlite database of another application from my application. I know that by default this is not possible within android applications, but as the device is rooted I suppose that I should be able to give my application root access and grab the other application's database and read it.

I don't want the device user to be notified and give me SUPER_ACCESS permission, so this should be an anonymous process. The other App has already implemented ContentProvider and has set exported = true

This is what I have tried so far but it still throws an exception that it could not open the database file.

```<code>try {

    File dbFile = new File("/data/data/com.sam.sample/databases/sample.db");

    if(dbFile.exists()) {

        String [] cmd = {"su", "-c", "chmod", "777", file.getPath()};

        Process process = new ProcessBuilder(cmd).start();
        process.waitFor();

        SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);

        Cursor cursor = db.rawQuery("SELECT * FROM sample", null);

        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                    Log.v("FROM DATABASE", name);
                    cursor.moveToNext();
                }
            }
        }

        cursor.close();
        db.close();

    }
}
catch(IOException e) {
   ...
}
</code>```

Is there anything that I am doing wrong here or that I should do differently?

答:
To read data from other application database, it is necessary that the other application had implemented a ContentProvider and had defined that ContentProvider as exported = true

For more info about content providers, check out this.

Then, to access ContentProvider data you should implement a ContentResolver instead of try to access other database directly.

For more info about content receivers, check out this.

Body:
I need to read sqlite database of another application from my application. I know that by default this is not possible within android applications, but as the device is rooted I suppose that I should be able to give my application root access and grab the other application's database and read it.

I don't want the device user to be notified and give me SUPER_ACCESS permission, so this should be an anonymous process. The other App has already implemented ContentProvider and has set exported = true

This is what I have tried so far but it still throws an exception that it could not open the database file.

try {

    File dbFile = new File("/data/data/com.sam.sample/databases/sample.db");

    if(dbFile.exists()) {

        String [] cmd = {"su", "-c", "chmod", "777", file.getPath()};

        Process process = new ProcessBuilder(cmd).start();
        process.waitFor();

        SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);

        Cursor cursor = db.rawQuery("SELECT * FROM sample", null);

        if (cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                    Log.v("FROM DATABASE", name);
                    cursor.moveToNext();
                }
            }
        }

        cursor.close();
        db.close();

    }
}
catch(IOException e) {
   ...
}

Is there anything that I am doing wrong here or that I should do differently?


问:
What is the equivalent of javascript setTimeout in Java?
I need to implement a function to run after 60 seconds of clicking a button. Please help, I used the Timer class, but I think that that is not the best way.</p>

答:
```<code>public ScheduledExecutorService = ses;
ses.scheduleAtFixedRate(new Runnable() {
    run() {
            //running after specified time
    }
}, 60, TimeUnit.SECONDS);
</code>```

It runs after 60 seconds from scheduleAtFixedRate. Check the ScheduledExecutorService documentation.

Body:
public ScheduledExecutorService = ses;
ses.scheduleAtFixedRate(new Runnable() {
    run() {
            //running after specified time
    }
}, 60, TimeUnit.SECONDS);

It runs after 60 seconds from scheduleAtFixedRate. Check the ScheduledExecutorService documentation.

ContentLicense: CC BY-SA 4.0


问:
How to hide all the names when input is empty?
In the following code, when input is empty, all the names are shown. I want no name when the input field is empty.

<input ng-model="search.$">

    {{ x }}

```

Thanks

答:
Try This Code it will help you</p>

```<code><script https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="namesCtrl">
  <input ng-model="search"></input> <br>
  <ul>
    <li ng-repeat="x in names | filter : search">
      {{ x }}
    </li>
  </ul>
</div>

<script>
  angular.module('myApp', []).controller('namesCtrl', function($scope) {

    if ($scope.$$childHead.search == "") {
      $scope.names = [];
    } else {
      $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
      ];
    }
  });
</script>

<!-- end snippet -->
</code>```

Body:
In the following code, when input is empty, all the names are shown. I want no name when the input field is empty.

<input ng-model="search.$">

    {{ x }}

Thanks

Body:
Try This Code it will help you

<script https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="namesCtrl">
  <input ng-model="search"></input> <br>
  <ul>
    <li ng-repeat="x in names | filter : search">
      {{ x }}
    </li>
  </ul>
</div>

<script>
  angular.module('myApp', []).controller('namesCtrl', function($scope) {

    if ($scope.$$childHead.search == "") {
      $scope.names = [];
    } else {
      $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
      ];
    }
  });
</script>

<!-- end snippet -->


问:
jQuery mouse event blocks default propagation
I have an issue with a full-body-overlay effect when clicking on any link.

The wanted effect is:

when any link of the page is "pushed" (mousedown or touchstart), an image overlay appears on the top of the whole body (hiding the complete content of the page)

when the link is (or should be) "released" (mouseup or touchend), the overlay should disappear and the original clicked link target should happen (the "href" attribute must be followed for instance).

The first part is OK: I added an event handler listening the "mousedown touchstart" events on every links. The second part is more complicated as the overlay does not trigger the "release" action of the link (the overlay is over the content with the link). So I attached a "mousedown touchend" event handler on the whole document, which works, but the default behavior of the clicked link (go to its "href" attribute for instance) is never fired :(

Here is my JS:

```<code>$(document).ready(function(){

    // the full-page overlay selector
    var $overlay = $('.body-overlay');

    // a flag to keep a trace of clicked element
    var overlay_triggered = false;

    // the "mousedown" event handler
    function show_overlay(evt)
    {
        var $target = $(evt.target);
        if (overlay_triggered === false) {
            $overlay.show();
            overlay_triggered = $target;
            $(document).on('mouseup touchend', hide_overlay);
        }
        return true;
    }

    // the "mouseup" event handler
    function hide_overlay(evt)
    {
        if (overlay_triggered !== false) {
            $(document).off('mouseup touchend', hide_overlay);
            $overlay.hide();

            // !!! - here I try to trigger a classic click but it never works
            $(overlay_triggered).click();

            overlay_triggered = false;
        }
        return true;
    }

    // attachment of the mousedown handler on all links
    $(document).on('mousedown touchstart', 'a', show_overlay);

});
</code>```

I made a JS Fiddle to show it more clearly.

Does someone know about any mistake here ? Is my logic wrong ?

答: I am not exactly sure why this won't work but I got it working by changing $(overlay_triggered).click(); to window.location = $(overlay_triggered).attr("href");

Body:
I have an issue with a full-body-overlay effect when clicking on any link.

The wanted effect is:

when any link of the page is "pushed" (mousedown or touchstart), an image overlay appears on the top of the whole body (hiding the complete content of the page)

when the link is (or should be) "released" (mouseup or touchend), the overlay should disappear and the original clicked link target should happen (the "href" attribute must be followed for instance).

The first part is OK: I added an event handler listening the "mousedown touchstart" events on every links. The second part is more complicated as the overlay does not trigger the "release" action of the link (the overlay is over the content with the link). So I attached a "mousedown touchend" event handler on the whole document, which works, but the default behavior of the clicked link (go to its "href" attribute for instance) is never fired :(

Here is my JS:

$(document).ready(function(){

    // the full-page overlay selector
    var $overlay = $('.body-overlay');

    // a flag to keep a trace of clicked element
    var overlay_triggered = false;

    // the "mousedown" event handler
    function show_overlay(evt)
    {
        var $target = $(evt.target);
        if (overlay_triggered === false) {
            $overlay.show();
            overlay_triggered = $target;
            $(document).on('mouseup touchend', hide_overlay);
        }
        return true;
    }

    // the "mouseup" event handler
    function hide_overlay(evt)
    {
        if (overlay_triggered !== false) {
            $(document).off('mouseup touchend', hide_overlay);
            $overlay.hide();

            // !!! - here I try to trigger a classic click but it never works
            $(overlay_triggered).click();

            overlay_triggered = false;
        }
        return true;
    }

    // attachment of the mousedown handler on all links
    $(document).on('mousedown touchstart', 'a', show_overlay);

});

I made a JS Fiddle to show it more clearly.

Does someone know about any mistake here ? Is my logic wrong ?


问:
How does a compiler/assembler make sense of processor core registers?
My question is specific to arm cortex M3 micro-controllers. Every peripheral on the micro controller is memory mapped and those memory addresses are used in processing.

For Eg.,: GPIOA->ODR = 0;

This will write a 0 at address 0x4001080C.
This address is defined in the device specific file of the micro controller.

Now, the cortex M3 has processor core registers R0-R12 (general purpose). I want to know, do these registers also have some address like other peripherals?

So, if I have instruction: MOV R0, #10;

will R0 be translated to some address when assembled? Do core registers have special numeric addresses exclusive for core peripherals. Is address of R0 defined in any file (I couldn't find any) like that of GPIOA? Or is it that register R0 and other core registers are referred to as R0 and their respective names only so that the assembler sees "R0" and generates the opcode from it?

I have this confusion because some 8 bit controllers also have addresses for general purpose registers.

Thanks,

Navin

答:
You happened to have picked an instruction that is really easy to see...

```<code>.thumb

mov r0,#10
mov r1,#10
mov r2,#10
mov r3,#10
mov r4,#10
mov r5,#10
mov r6,#10
mov r7,#10
</code>```

assemble then disassemble to see the machine code

```<code>Disassembly of section .text:

00000000 <.text>:
   0:   200a        movs    r0, #10
   2:   210a        movs    r1, #10
   4:   220a        movs    r2, #10
   6:   230a        movs    r3, #10
   8:   240a        movs    r4, #10
   a:   250a        movs    r5, #10
   c:   260a        movs    r6, #10
   e:   270a        movs    r7, #10
</code>```

there will be three or four bits depending on the instruction and instruction set (arm vs thumb (and then thumb2 extensions)) that specify the register.  In this case those bits happen to line up nicely with the hex representation of the machine code instruction so we can see the 0 through 7.  For a cortex-m3 many of the thumb instructions are limited to r0-r7 (implying a 3 bit field within the instruction) with one or two to move between the lower and upper, thumb2 extensions allow for more access to the full r0-r15 (and thus will have a 4 bit field in the instruction).  You should get the armv7m architectural reference manual which is what is associated with the cortex-m3 (after you get the cortex-m3 technical reference manual and see that it uses the armv7m architecture), you can also get the oldest armv5 architectural reference manual as it has the oldest description of the thumb instruction set which is the one instruciton set that is compatible across all arm cores armv6m covers the cortex-m0 which has a lot fewer thumb2 extensions then armv7m which covers the cortex-m3 m4 and m7 have tons more thumb2 extensions.

another example that takes only a second to try

```<code>.thumb

mov r0,r0
mov r1,r1
mov r2,r2
mov r3,r3
mov r4,r4
mov r5,r5
mov r6,r6
mov r7,r7

mov r0,r0
mov r1,r0
mov r2,r0
mov r3,r0
mov r4,r0
mov r5,r0
mov r6,r0
mov r7,r0

Disassembly of section .text:

00000000 <.text>:
   0:   1c00        adds    r0, r0, #0
   2:   1c09        adds    r1, r1, #0
   4:   1c12        adds    r2, r2, #0
   6:   1c1b        adds    r3, r3, #0
   8:   1c24        adds    r4, r4, #0
   a:   1c2d        adds    r5, r5, #0
   c:   1c36        adds    r6, r6, #0
   e:   1c3f        adds    r7, r7, #0
  10:   1c00        adds    r0, r0, #0
  12:   1c01        adds    r1, r0, #0
  14:   1c02        adds    r2, r0, #0
  16:   1c03        adds    r3, r0, #0
  18:   1c04        adds    r4, r0, #0
  1a:   1c05        adds    r5, r0, #0
  1c:   1c06        adds    r6, r0, #0
  1e:   1c07        adds    r7, r0, #0
</code>```

note that the bits didnt line up as nicely as before with hex values, doesnt matter look at the binary to see the three bits changing from instruction to instruction.

in this case the assembler chose to use an add instead of mov

Notes:

Encoding: This instruction is encoded as ADD Rd, Rn, #0.

and

Notes

Operand restriction: If a low register is specified for  and
  H1==0 and H2==0), the result is UNPREDICTABLE .

All this plus a zillion more things you learn when you read the documentation.  http://infocenter.arm.com. on the left arm architecture then reference manuals you may have to sacrifice an email address.  you can google arm architectural reference manual and you may get lucky...

Body:
You happened to have picked an instruction that is really easy to see...

.thumb

mov r0,#10
mov r1,#10
mov r2,#10
mov r3,#10
mov r4,#10
mov r5,#10
mov r6,#10
mov r7,#10

assemble then disassemble to see the machine code

Disassembly of section .text:

00000000 <.text>:
   0:   200a        movs    r0, #10
   2:   210a        movs    r1, #10
   4:   220a        movs    r2, #10
   6:   230a        movs    r3, #10
   8:   240a        movs    r4, #10
   a:   250a        movs    r5, #10
   c:   260a        movs    r6, #10
   e:   270a        movs    r7, #10

there will be three or four bits depending on the instruction and instruction set (arm vs thumb (and then thumb2 extensions)) that specify the register.  In this case those bits happen to line up nicely with the hex representation of the machine code instruction so we can see the 0 through 7.  For a cortex-m3 many of the thumb instructions are limited to r0-r7 (implying a 3 bit field within the instruction) with one or two to move between the lower and upper, thumb2 extensions allow for more access to the full r0-r15 (and thus will have a 4 bit field in the instruction).  You should get the armv7m architectural reference manual which is what is associated with the cortex-m3 (after you get the cortex-m3 technical reference manual and see that it uses the armv7m architecture), you can also get the oldest armv5 architectural reference manual as it has the oldest description of the thumb instruction set which is the one instruciton set that is compatible across all arm cores armv6m covers the cortex-m0 which has a lot fewer thumb2 extensions then armv7m which covers the cortex-m3 m4 and m7 have tons more thumb2 extensions.

another example that takes only a second to try

.thumb

mov r0,r0
mov r1,r1
mov r2,r2
mov r3,r3
mov r4,r4
mov r5,r5
mov r6,r6
mov r7,r7

mov r0,r0
mov r1,r0
mov r2,r0
mov r3,r0
mov r4,r0
mov r5,r0
mov r6,r0
mov r7,r0

Disassembly of section .text:

00000000 <.text>:
   0:   1c00        adds    r0, r0, #0
   2:   1c09        adds    r1, r1, #0
   4:   1c12        adds    r2, r2, #0
   6:   1c1b        adds    r3, r3, #0
   8:   1c24        adds    r4, r4, #0
   a:   1c2d        adds    r5, r5, #0
   c:   1c36        adds    r6, r6, #0
   e:   1c3f        adds    r7, r7, #0
  10:   1c00        adds    r0, r0, #0
  12:   1c01        adds    r1, r0, #0
  14:   1c02        adds    r2, r0, #0
  16:   1c03        adds    r3, r0, #0
  18:   1c04        adds    r4, r0, #0
  1a:   1c05        adds    r5, r0, #0
  1c:   1c06        adds    r6, r0, #0
  1e:   1c07        adds    r7, r0, #0

note that the bits didnt line up as nicely as before with hex values, doesnt matter look at the binary to see the three bits changing from instruction to instruction.

in this case the assembler chose to use an add instead of mov

Notes:

Encoding: This instruction is encoded as ADD Rd, Rn, #0.

and

Notes

Operand restriction: If a low register is specified for  and
  H1==0 and H2==0), the result is UNPREDICTABLE .

All this plus a zillion more things you learn when you read the documentation.  http://infocenter.arm.com. on the left arm architecture then reference manuals you may have to sacrifice an email address.  you can google arm architectural reference manual and you may get lucky...


答:
The Paypal API's are kinda known for not being super user-friendly. That said, I have successfully used the IPN API, however, I'm not sure this is what you want to use in your case. IPN (Instant Payment Notification) is 1.) For sending notifications to your server. 2.) It communicates with your server and therefore does not have any effect on a customer's transaction. 3.) Not instant all the time.

So, if you want to send a customer to a certain page, after purchase, you will not be able to accomplish this with IPN. You could start by looking at the Express Checkout API.

If you just need a simple redirect, Paypal provides a way to do this.

You could setup a PHP file on your server, which integrates with IPN. This file would work like this:

IPN sends a "transaction completed" notification to your PHP file.

Your PHP file reads the notification to ensure that it's a "completed transaction notification", as opposed to another notification (such as "transaction failed", etc).

If everything is ok, your PHP file can generate and email out whatever you need to the customer.

Title: How do I appropriately interact with PayPal IPN for the purpose of serial generation?

Body:
Having a bit of trouble with the PayPal IPN.  I've seen variations on these questions listed about a million times, but not the answers I'm looking for.  As usual this may be a case of asking a question regarding the wrong thing, but I'm hoping there are some super geniuses out there that can assist.

Anyway, I basically need to set up the purchase of some readily available software, and, once the transaction is complete send them a serial.  One would think this is simple, but given the criteria it has proven anything but.  Basically the steps are as follows:

1) Custom form on website to enter personal (but not too =P) info

2) Forward them to PayPal site to make purchase

3) Upon successful transaction AUTOMATICALLY send them to a serial page and/or send an email with the registration.

I've looked at various IPN classes (using PHP btw) and nothing seems very straightforward, and it doesn't seem that PayPal likes any kind of custom variables being passed, nor does it seem to automatically send someone elsewhere after the purchase.  Also, which ID should I be looking at if/when the process finally does come back around?

Perhaps I need the "Pro" account?  In any event, please make no assumptions regarding my knowledge of PayPal IPN.  I'd simply like a class (hopefully one I haven't tried already) or at least some more straightforward (and concise) documentation on how to accomplish this.

Best.

EDIT #1:

Does anyone have any information on enabling the QUANTITY field during a purchase?  For some reason it's stuck at 1 and will not allow a change.  I'm not passing anything for quantity atm.


问:
ionic 2 - Error Could not find an installed version of Gradle either in Android Studio
I create ionic 2 project and add diagnostic cordova plugin like this :

```<code>ionic plugin add cordova.plugins.diagnostic

npm install --save @ionic-native/diagnostic
</code>```

and add android platform like this :

```<code>ionic platform add android@latest
</code>```

but when build with ionic build android console give me this error :

```<code>Error: Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio
</code>```

and I try to download manualy gradle.3.3-all.zip and change this  distributionUrl var in platform/android/cordova/lib/builders/GradleBuilder.js

```<code> var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-3.3-all.zip'
</code>```

to:

```<code>var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'file:///E:/gradles/gradle-3.3-all.zip';
</code>```

but not working and console give me last error.

I dont know how to add gradle for android@latest version

答:
I solve this problem

Download gradle.zip from this site https://gradle.org/install. And follow the instructions indicated in the site.

Then open another terminal cmd and execute the command:

```<code>Cordova build android --prod --release
End
</code>```

Body:
I create ionic 2 project and add diagnostic cordova plugin like this :

ionic plugin add cordova.plugins.diagnostic

npm install --save @ionic-native/diagnostic

and add android platform like this :

ionic platform add android@latest

but when build with ionic build android console give me this error :

Error: Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio

and I try to download manualy gradle.3.3-all.zip and change this  distributionUrl var in platform/android/cordova/lib/builders/GradleBuilder.js

 var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'https\\://services.gradle.org/distributions/gradle-3.3-all.zip'

to:

var distributionUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] || 'file:///E:/gradles/gradle-3.3-all.zip';

but not working and console give me last error.

I dont know how to add gradle for android@latest version

Body:
I solve this problem

Download gradle.zip from this site https://gradle.org/install. And follow the instructions indicated in the site.

Then open another terminal cmd and execute the command:

Cordova build android --prod --release
End


问:
TYPO3 Language Switch with FLUID
I've made a language menu (switch) for TYPO3 7.6 with Fluid only, no TypoScript. Just a Dropdown, see screenshot below. I also used the Ext:vhs, here's my code example:

```<code>{namespace v=FluidTYPO3\Vhs\ViewHelpers}
<ul id="languageMenu" class="dropdown menu" data-dropdown-menu>
    <!-- german L:0 -->
    <f:if condition="{v:page.language()}==0">
        <li class="de">
            <f:link.page pageUid="{page.uid}" additionalParams="{L:0}">
                <f:image src="EXT:myext/Resources/Public/Icons/Flags/de.svg" width="18" height="14" alt="" />
                <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.de" />
            </f:link.page>
            <ul class="menu languageSubMenu">
                <li class="en">
                    <f:link.page pageUid="{page.uid}" additionalParams="{L:1}">
                        <f:image src="EXT:myext/Resources/Public/Icons/Flags/gb.svg" width="18" height="14" alt="" />
                        <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.en" />
                    </f:link.page>
                </li>
            </ul>
        </li>
    </f:if>

    <!-- english L:1 -->
    <f:if condition="{v:page.language()}==1">
        <li class="en">
            <f:link.page pageUid="{page.uid}" additionalParams="{L:1}">
                <f:image src="EXT:hellocode/Resources/Public/Icons/Flags/gb.svg" width="18" height="14"
                         alt="{f:translate(key: 'LLL:EXT:hellocode/Resources/Private/Language/locallang.xlf:language.en')}" />
                <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.en" />
            </f:link.page>
            <ul class="menu languageSubMenu">
                <li class="de">
                    <f:link.page pageUid="{page.uid}" additionalParams="{L:0}">
                        <f:image src="EXT:myext/Resources/Public/Icons/Flags/de.svg" width="18" height="14" alt="" />
                        <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.de" />
                    </f:link.page>
                </li>
            </ul>
        </li>
    </f:if>
</ul>
</code>```

At the moment the language switch is always shown. If there's no page translation, I'll get an 404 Error. Of course, the missing page aren't exist. How can I hide my language switch, if there's no translation?

In past I used USERDEF1 with TypoScript, but I need a solution with Fluid. I also see there's a viewhelper v:condition.page.isLanguage but this isn't working for me or I don't know how?! Is it possible to do this with Fluid or vhs?

I would be grateful for any advice. Otherwise I have to write typoscript again ...

答:
I can only propose to use https://typo3.org/extensions/repository/view/sr_language_menu

You can simply use it like that: https://bitbucket.org/reelworx/rx-typo3-sitesetup/src/e34b675a223f02580838fe7d5d118d7f07fd8a68/Resources/Private/Layouts/Default.html?at=master&fileviewer=file-view-default#Default.html-48

Of course it is fully Fluid based, so you can override all templates to your needs.

Title: TYPO3 Language Switch with FLUID

Body:
I've made a language menu (switch) for TYPO3 7.6 with Fluid only, no TypoScript. Just a Dropdown, see screenshot below. I also used the Ext:vhs, here's my code example:

{namespace v=FluidTYPO3\Vhs\ViewHelpers}

    <f:if condition="{v:page.language()}==0">

            <f:link.page pageUid="{page.uid}" additionalParams="{L:0}">
                <f:image src="EXT:myext/Resources/Public/Icons/Flags/de.svg" width="18" height="14" alt="" />
                <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.de" />
            </f:link.page>

                    <f:link.page pageUid="{page.uid}" additionalParams="{L:1}">
                        <f:image src="EXT:myext/Resources/Public/Icons/Flags/gb.svg" width="18" height="14" alt="" />
                        <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.en" />
                    </f:link.page>

    </f:if>

    <f:if condition="{v:page.language()}==1">

            <f:link.page pageUid="{page.uid}" additionalParams="{L:1}">
                <f:image src="EXT:hellocode/Resources/Public/Icons/Flags/gb.svg" width="18" height="14"
                         alt="{f:translate(key: 'LLL:EXT:hellocode/Resources/Private/Language/locallang.xlf:language.en')}" />
                <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.en" />
            </f:link.page>

                    <f:link.page pageUid="{page.uid}" additionalParams="{L:0}">
                        <f:image src="EXT:myext/Resources/Public/Icons/Flags/de.svg" width="18" height="14" alt="" />
                        <f:translate key="LLL:EXT:myext/Resources/Private/Language/locallang.xlf:language.de" />
                    </f:link.page>

    </f:if>

At the moment the language switch is always shown. If there's no page translation, I'll get an 404 Error. Of course, the missing page aren't exist. How can I hide my language switch, if there's no translation?

In past I used USERDEF1 with TypoScript, but I need a solution with Fluid. I also see there's a viewhelper v:condition.page.isLanguage but this isn't working for me or I don't know how?! Is it possible to do this with Fluid or vhs?

I would be grateful for any advice. Otherwise I have to write typoscript again ...


问:
I have a date in "2017-05-26T04:08:00.000+05:30" in XMLGregorianCalendar i need to convert it to 2017-05-26T04:08:00.000z
I have a date in "2017-05-26T04:08:00.000+05:30" in XMLGregorianCalendar i need to convert it to 2017-05-26T04:08:00.000Z in XMLGregorianCalendar itself.</p>

答:
It turns out that you can set the fields of an XMLGregorianCalendar individually. So just do

```<code>    yourXmlGregorianCalendar.setTimezone(0);
    System.out.println(yourXmlGregorianCalendar);
</code>```

This prints:

```<code>2017-05-26T04:08:00.000Z
</code>```

I hope you are aware that the new time does not equal the old time. Rather it equals 2017-05-26T09:38 at your original time zone offset of +05:30.

Edit: How to get an XMLGregorianCalendar date without timezone "2017-05-26T04:08:00"? That is, I don’t want any milliseconds either!

Let me see, didn’t I see something in this in the documentation? It says: “Unset this field by invoking the setter with a parameter value of DatatypeConstants.FIELD_UNDEFINED,” In fact it says that for all the setters that take an int argument. Let’s try that:

```<code>    yourXmlGregorianCalendar.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
    yourXmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    System.out.println(yourXmlGregorianCalendar);
</code>```

This prints:

```<code>2017-05-26T04:08:00
</code>```

Aren’t we there?

Body:
It turns out that you can set the fields of an XMLGregorianCalendar individually. So just do

    yourXmlGregorianCalendar.setTimezone(0);
    System.out.println(yourXmlGregorianCalendar);

This prints:

2017-05-26T04:08:00.000Z

I hope you are aware that the new time does not equal the old time. Rather it equals 2017-05-26T09:38 at your original time zone offset of +05:30.

Edit: How to get an XMLGregorianCalendar date without timezone "2017-05-26T04:08:00"? That is, I don’t want any milliseconds either!

Let me see, didn’t I see something in this in the documentation? It says: “Unset this field by invoking the setter with a parameter value of DatatypeConstants.FIELD_UNDEFINED,” In fact it says that for all the setters that take an int argument. Let’s try that:

    yourXmlGregorianCalendar.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
    yourXmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    System.out.println(yourXmlGregorianCalendar);

This prints:

2017-05-26T04:08:00

Aren’t we there?


问:
How can I access to a button inside a customized AlertDialog?
I'm pretty new in Android programming, so I hope this question is easy for you guys.

I'm opening a custom AlertDialog with an extra button and a seekbar in order to display the progress of playing a song. My problem is that I cannot access to the onClick method of that button.

I'm opening the AlertDialog with the following code:

```<code>public void openAudioPlayer(View view){

    new AlertDialog.Builder(this)
            .setTitle(R.string.audio_player_title)
            .setMessage(R.string.audio_player_description)
            .setView(R.layout.dialog_audio_player)
            .setPositiveButton(R.string.confirm,null)
            .setNegativeButton(R.string.cancel, null).show();

}
</code>```

Where dialog_audio_player is the custom XLM file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/playerBox"
        android:layout_centerVertical="true">

        <ToggleButton
            android:id="@+id/playStateButton"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:background="@drawable/toggle_player"
            android:onClick="onPlayerClicked"
            android:checked="false"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:textOff=""
            android:textOn="" />

        <SeekBar
            android:id="@+id/seekBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/playStateButton" />
        </RelativeLayout>
</LinearLayout>
</code>```

So, I want to control the pushing of that button with my customized onPlayerCLicked method, which is included in the same activity that openAudioPlayer:

```<code>public void onPlayerClicked(View view){
    Toast.makeText(this,"clicked",Toast.LENGTH_LONG).show();
}
</code>```

But the program never enters there. In fact, the app closes.

How can I do it?

The crash is the following:

```<code>06-04 12:47:13.587 3928-3928/vmc.songbook E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: vmc.songbook, PID: 3928
                                                        java.lang.IllegalStateException: Could not execute method for android:onClick
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4698)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.reflect.InvocationTargetException
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.RuntimeException: stop failed.
                                                            at android.media.MediaRecorder.stop(Native Method)
                                                            at vmc.songbook.RecordAudio.stopRecording(RecordAudio.java:121)
                                                            at vmc.songbook.RecordAudio.onToggleClicked(RecordAudio.java:84)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
```<code>LayoutInflater layoutInflater = LayoutInflater.from(this);
View view = layoutInflater.inflate(R.layout.dialog_audio_player , null);
final AlertDialog alertD = new AlertDialog.Builder(this).create();
ToggleButton btn = (ToggleButton) view.findViewById(R.id.playStateButton);

btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

    // btn has been clicked

  }
});

 alertD.setView(view);
 alertD.show();
</code>```

Body:
I'm pretty new in Android programming, so I hope this question is easy for you guys.

I'm opening a custom AlertDialog with an extra button and a seekbar in order to display the progress of playing a song. My problem is that I cannot access to the onClick method of that button.

I'm opening the AlertDialog with the following code:

public void openAudioPlayer(View view){

    new AlertDialog.Builder(this)
            .setTitle(R.string.audio_player_title)
            .setMessage(R.string.audio_player_description)
            .setView(R.layout.dialog_audio_player)
            .setPositiveButton(R.string.confirm,null)
            .setNegativeButton(R.string.cancel, null).show();

}

Where dialog_audio_player is the custom XLM file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/playerBox"
        android:layout_centerVertical="true">

        <ToggleButton
            android:id="@+id/playStateButton"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:background="@drawable/toggle_player"
            android:onClick="onPlayerClicked"
            android:checked="false"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:textOff=""
            android:textOn="" />

        <SeekBar
            android:id="@+id/seekBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/playStateButton" />
        </RelativeLayout>
</LinearLayout>

So, I want to control the pushing of that button with my customized onPlayerCLicked method, which is included in the same activity that openAudioPlayer:

public void onPlayerClicked(View view){
    Toast.makeText(this,"clicked",Toast.LENGTH_LONG).show();
}

But the program never enters there. In fact, the app closes.

How can I do it?

The crash is the following:

06-04 12:47:13.587 3928-3928/vmc.songbook E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: vmc.songbook, PID: 3928
                                                        java.lang.IllegalStateException: Could not execute method for android:onClick
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4698)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.reflect.InvocationTargetException
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.RuntimeException: stop failed.
                                                            at android.media.MediaRecorder.stop(Native Method)
                                                            at vmc.songbook.RecordAudio.stopRecording(RecordAudio.java:121)
                                                            at vmc.songbook.RecordAudio.onToggleClicked(RecordAudio.java:84)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)


问:
Build database with .sql file with PHP
Ok, i have searched high and low and have been unable to find an answer that works for what i am trying to do.  I have two databases, we'll call them DB1 and DB2.  I have a cron job that runs every night at 4am that backs up DB1 and stores its data in a SQL file archive, we'll call this file db_backup.sql.  The file is stored in a folder on the server, we'll call it ROOT/backups/db_backup.sql.

Info

```<code>database names: DB1 and DB2
backup filename: db_backup.sql
backup file path: ROOT/backups/db_backup.sql
</code>```

What i'm trying to do:

I want to use the db_backup.sql file to build DB2.  I am basically trying to set up database replication where i replicate DB1 out to DB2.  Don't know of any other way to do this on shared hosting servers than what i'm trying to explain.  I am trying to use php to import the db_backup.sql file into DB2.

My Environment:

The website and databases are on a shared hosting account with godaddy (yes, i would love to get dedicated servers to set up real replication, but can't afford it for now).  The databases are mysql in phpmyadmin.

Is this something that is possible? Any help would be greatly appreciated!  Let me know if you have any questions as well.

答: Can you not avoid PHP altogether and connect directly to the database remotely to perform the backup either via the command line or using a scripting language more suitable for long running processes?</p>

Title: Build database with .sql file with PHP

Body:
Ok, i have searched high and low and have been unable to find an answer that works for what i am trying to do.  I have two databases, we'll call them DB1 and DB2.  I have a cron job that runs every night at 4am that backs up DB1 and stores its data in a SQL file archive, we'll call this file db_backup.sql.  The file is stored in a folder on the server, we'll call it ROOT/backups/db_backup.sql.

Info

database names: DB1 and DB2
backup filename: db_backup.sql
backup file path: ROOT/backups/db_backup.sql

What i'm trying to do:

I want to use the db_backup.sql file to build DB2.  I am basically trying to set up database replication where i replicate DB1 out to DB2.  Don't know of any other way to do this on shared hosting servers than what i'm trying to explain.  I am trying to use php to import the db_backup.sql file into DB2.

My Environment:

The website and databases are on a shared hosting account with godaddy (yes, i would love to get dedicated servers to set up real replication, but can't afford it for now).  The databases are mysql in phpmyadmin.

Is this something that is possible? Any help would be greatly appreciated!  Let me know if you have any questions as well.


问:
Scapy not sending IPv6 packets with global scope destination address
I'm trying to send IPv6 packets with scapy. I don't really care what higher-level protocol is used, so I simply send:

```<code>send(IPv6(dst="2001:db9:1::4"))
</code>```

I have a route toward that destination, running ip -6 route show I see:

```<code>2001:db9:1::4 dev vt0  metric 1024
</code>```

If I send a ping request from the command line, I can see it in tcpdump in the destination device. But if I send the IPv6 packet with scapy, I get these messages, and I don't see anything in tcpdump:

```<code>WARNING: No route found for IPv6 destination 2001:db9:1::4 (no default route?)
WARNING: No route found for IPv6 destination 2001:db9:1::4 (no default route?)
WARNING: more No route found for IPv6 destination 2001:db9:1::4 (no default route?)
.
Sent 1 packets.
</code>```

But it works if I use the link-local address of the destination device. I only get one warning message (similar to the first line in the messages above), and I see the packet in tcpdump.

Any idea why this happens, and how can I fix it?

答:
The sending interface needs to have a global IPv6 address.

Packets with a global destination address must have a global source address as well, otherwise the packet won't be forwarded.

Body:
I'm trying to send IPv6 packets with scapy. I don't really care what higher-level protocol is used, so I simply send:

send(IPv6(dst="2001:db9:1::4"))

I have a route toward that destination, running ip -6 route show I see:

2001:db9:1::4 dev vt0  metric 1024

If I send a ping request from the command line, I can see it in tcpdump in the destination device. But if I send the IPv6 packet with scapy, I get these messages, and I don't see anything in tcpdump:

WARNING: No route found for IPv6 destination 2001:db9:1::4 (no default route?)
WARNING: No route found for IPv6 destination 2001:db9:1::4 (no default route?)
WARNING: more No route found for IPv6 destination 2001:db9:1::4 (no default route?)
.
Sent 1 packets.

But it works if I use the link-local address of the destination device. I only get one warning message (similar to the first line in the messages above), and I see the packet in tcpdump.

Any idea why this happens, and how can I fix it?


问:
Unknown error using Swift 3 in xcode 8 - "Editor placeholder in source file"
I am creating a helper function to handle what happens when a register button is clicked. I am attempting to connect Firebase database and use the reference that I create to input the information that is inputed. I am getting the following two errors upon finishing the function...

```<code>"Editor placeholder in source file"
"Value of optional type 'String?' not unwrapped, did you mean '!' or '?'?"
</code>```

The first error is the one I am most concerned about, but all pointers would be appreciated.

Here is the function that I have created to handle the RegisterButtonClick action:

```<code>func handleRegisterClick(){
        guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else{
            print("Form is not valid...")
            return
        }

        FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
            if error != nil{
                print(error ?? "user was not created... something went wrong")
                return
            }
            // else... succesfully authernticated user

            var ref: FIRDatabaseReference!
            ref = FIRDatabase.database().reference()

            let values = ["name": name, "email": email]

            ref.updateChildValues(values, withCompletionBlock: { (err, ref) in
                if err != nil{
                    print(err ?? "Child values could not be updated... something went wrong")
                    return
                }
                print("Saved user successfully into the Firebase DB")
            })
        })
        print("Register Button was pressed.")
    }
</code>```

Up above is where the error is being called. The following block of code shows where this function is being called:

```<code>lazy var loginRegisterButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
        button.setTitle("Register", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

        button.addTarget(self, action: #selector(handleRegisterClick), for: .touchUpInside)

        // this next step is needed or else the constraints set later on will not work
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
</code>```

Any help fixing the first error would be extremely helpful. I just don't understand what the error is stating. Very new to iOS development, therefore apologies on any unclarity.

答:
This:

```<code>(user: FIRUser?, error)
</code>```

should be

```<code>(user, error)
</code>```

That should correct both errors. If not, please indicate the line the optional error is occurring on and I will update the answer.

Body:
I am creating a helper function to handle what happens when a register button is clicked. I am attempting to connect Firebase database and use the reference that I create to input the information that is inputed. I am getting the following two errors upon finishing the function...

"Editor placeholder in source file"
"Value of optional type 'String?' not unwrapped, did you mean '!' or '?'?"

The first error is the one I am most concerned about, but all pointers would be appreciated.

Here is the function that I have created to handle the RegisterButtonClick action:

func handleRegisterClick(){
        guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else{
            print("Form is not valid...")
            return
        }

        FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in
            if error != nil{
                print(error ?? "user was not created... something went wrong")
                return
            }
            // else... succesfully authernticated user

            var ref: FIRDatabaseReference!
            ref = FIRDatabase.database().reference()

            let values = ["name": name, "email": email]

            ref.updateChildValues(values, withCompletionBlock: { (err, ref) in
                if err != nil{
                    print(err ?? "Child values could not be updated... something went wrong")
                    return
                }
                print("Saved user successfully into the Firebase DB")
            })
        })
        print("Register Button was pressed.")
    }

Up above is where the error is being called. The following block of code shows where this function is being called:

lazy var loginRegisterButton: UIButton = {
        let button = UIButton(type: .system)
        button.backgroundColor = UIColor(r: 80, g: 101, b: 161)
        button.setTitle("Register", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

        button.addTarget(self, action: #selector(handleRegisterClick), for: .touchUpInside)

        // this next step is needed or else the constraints set later on will not work
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

Any help fixing the first error would be extremely helpful. I just don't understand what the error is stating. Very new to iOS development, therefore apologies on any unclarity.

Body:
This:

(user: FIRUser?, error)

should be

(user, error)

That should correct both errors. If not, please indicate the line the optional error is occurring on and I will update the answer.


问:
Single ant upload list item only
I am using ant design to upload csv with this form input:

```<code>ce(Form.Item, { className: 'form_input' },
        ce(Upload, { onChange: handleFileChange, className:'csv', multiple: false },
          ce(Button, { type: 'ghost' },
            ce(Icon, { type: 'upload' }), ' Choose File',
          )
        ),
      )
</code>```

The form allows multiple uploads and the new uploads get appended to "ant-upload-list-item". How can I prevent the append and only keep the latest item in there?

答:
The multiple prop you are specifying is concerning if we allow selecting multiple files in the file select popup, so it doesn't help you here.

There is no immediate way to show only the last upload, but using the fileList property you can implement your own display to accomplish that. See https://ant.design/components/upload/#components-upload-demo-fileList

Title: Single ant upload list item only

Body:
I am using ant design to upload csv with this form input:

ce(Form.Item, { className: 'form_input' },
        ce(Upload, { onChange: handleFileChange, className:'csv', multiple: false },
          ce(Button, { type: 'ghost' },
            ce(Icon, { type: 'upload' }), ' Choose File',
          )
        ),
      )

The form allows multiple uploads and the new uploads get appended to "ant-upload-list-item". How can I prevent the append and only keep the latest item in there?


问:
Extract image name from "img" tag source
I have html page has images like:

```<code><img src="media/lib/pics/1495343165.jpg" style="width: 600px; height: 400px; margin: 5px;" />
</code>```

I would like to extract the image name only "1495343165.jpg" to replace whole image tag with

```<code><img src="my/new/path/1495343165.jpg"  />
</code>```

How can i do that using regex and php?

Thanks

答:
You can use XPath to only target the img nodes you want:

```<code>$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTMLFile($filePath, LIBXML_HTML_NODEFDTD);
// or $dom->loadHTML($htmlString, LIBXML_HTML_NODEFDTD);

$xp = new DOMXPath($dom);

$nodeList = $xp->query('//img[starts-with(@src, "media/lib/pics/")]');

$newPath = 'my/new/path/';

foreach ($nodeList as $node) {
    $imgFileName = basename($node->getAttribute('src'));
    $imgNode = $dom->createElement('img'); // create a new img element to replace the old img node
    $imgNode->setAttribute('src', $newPath . $imgFileName);
    $node->parentNode->replaceChild($imgNode, $node);
}

$result = $dom->saveHTML();
</code>```

XPath query details:

```<code>//   # everywhere in the DOM tree
img  # an img element
[    # open a predicate
starts-with(@src, "media/lib/pics/") # with a src attribute that starts with "media/lib/pics/"
]    # close the predicate
</code>```

Body:
I have html page has images like:

I would like to extract the image name only "1495343165.jpg" to replace whole image tag with

How can i do that using regex and php?

Thanks

Body:
You can use XPath to only target the img nodes you want:

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTMLFile($filePath, LIBXML_HTML_NODEFDTD);
// or $dom->loadHTML($htmlString, LIBXML_HTML_NODEFDTD);

$xp = new DOMXPath($dom);

$nodeList = $xp->query('//img[starts-with(@src, "media/lib/pics/")]');

$newPath = 'my/new/path/';

foreach ($nodeList as $node) {
    $imgFileName = basename($node->getAttribute('src'));
    $imgNode = $dom->createElement('img'); // create a new img element to replace the old img node
    $imgNode->setAttribute('src', $newPath . $imgFileName);
    $node->parentNode->replaceChild($imgNode, $node);
}

$result = $dom->saveHTML();

XPath query details:

//   # everywhere in the DOM tree
img  # an img element
[    # open a predicate
starts-with(@src, "media/lib/pics/") # with a src attribute that starts with "media/lib/pics/"
]    # close the predicate


答:
I'm not sure if I understand your problem.  You need to copy the db_backup file to the second host where you have access to the database and load the sql file.

From a shell:

```<code>mysql -hhost -uusername -ppassword databasename < db_backup.sql
</code>```

This will restore the tables on the second machine.

Title: Build database with .sql file with PHP

Body:
I'm not sure if I understand your problem.  You need to copy the db_backup file to the second host where you have access to the database and load the sql file.

From a shell:

mysql -hhost -uusername -ppassword databasename < db_backup.sql

This will restore the tables on the second machine.


问:
Pycharm subprocess.Popen python under virtualenv
Calling subprocess.Popen(["python"]) spawns a process as if calling the global 2.7 python, instead of spawning a 3.6 version as defined in the virtualenv.
subprocess.Popen documentation says that execvp is called, but it seems to act as if a new clean shell is calling it.
Is there a way to enforce calling system calls within the code but under the virtualenv?

Running on macOS, project in a virtualenv directory which is recognized by Pycharm (Preferences->Project->Project Interpreter points to the python in the virtualenv). My global python command launches the 2.7 interpreter, but in the virtualenv python will launch the 3.6 interpreter.

答:
subprocess.Popen([sys.executable])

sys.executable is the Python interpreter running the current script. Using it to run a new script with the same interpreter is pretty natural.


问:
Azure App Service Mobile authentication not compatible with MVC/Forms
I have added a Web API service to a 'legacy' MVC project (not vNext), still using Membership and the forms authentication module.
All OK, until I decided to make the web api a mobile service using the latest SDKs for Azure App Services for Mobile.

I have so far narrowed the problem to this

```<code>  //app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
            //{

            //    SigningKey = CloudConfigurationManager.GetSetting("authSigningKey"),
            //    ValidAudiences = new[] { CloudConfigurationManager.GetSetting("authAudience") },
            //    ValidIssuers = new[] { CloudConfigurationManager.GetSetting("authIssuer") },
            //    TokenHandler = GlobalConfiguration.Configuration.GetAppServiceTokenHandler()
            //});
</code>```

This changes the rest of the app so that MVC + forms auth doesn't work. Running out of time to research the problem.
Any clues??

答:
The following solution is working for me:
In your Startup register call UseCookieAuthentication, UseExternalSignInCookie or UseOAuthAuthorizationServer before calling UseAppServiceAuthentication.

Second step:
Add the following class to your project:

```<code>private sealed class CustomAppServiceAuthenticationMiddleware : AppServiceAuthenticationMiddleware
{
    private readonly ILogger _logger;

    public CustomAppServiceAuthenticationMiddleware(OwinMiddleware next, IAppBuilder appBuilder, AppServiceAuthenticationOptions options) : base(next, appBuilder, options)
    {
        _logger = (ILogger)GetType().BaseType.GetField("logger", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);
    }

    protected override AuthenticationHandler<AppServiceAuthenticationOptions> CreateHandler()
    {
        return new AppServiceAuthenticationHandler(_logger);
    }

    public override Task Invoke(IOwinContext context)
    {
        string logLine = $"AppServiceAuthMiddleware: {context.Request.Path}";

        if (context.Request.Headers.TryGetValue("Authorization", out var values))
            logLine += $"; Authorization: {values.First().Split(' ').FirstOrDefault()}";
        if (context.Request.Headers.TryGetValue("X-ZUMO-AUTH", out values))
            logLine += $"; X-ZUMO-AUTH: {values.First()}";

        _logger.WriteVerbose(logLine);
        Debug.WriteLine(logLine);

        if (IsZumoAuth(context))
        {
            return base.Invoke(context);
        }

        return Next.Invoke(context);
    }

    private bool IsZumoAuth(IOwinContext context)
    {
        return context.Request.Headers.ContainsKey("X-ZUMO-AUTH");
    }
}
</code>```

Thrid step:
Replace the app.UseAppServiceAuthentication with the following:

```<code>        app.Use(typeof(CustomAppServiceAuthenticationMiddleware), app, new AppServiceAuthenticationOptions
        {
            SigningKey = ...,
            ValidAudiences = ...,
            ValidIssuers = ...,
            TokenHandler = ...
        });
</code>```

This will the owin pipline make call the AppServiceAuthenticationMiddleware just for ZUMO-AUTH auth.

I've got a mixed web & mobile app.
With this approach the membership auth on the web app is working.
In the app, some custom oauth (refresh token based) plus the azure auth (facebook, google, ...) is working too. All that within the same asp.net application.

Body:
I have added a Web API service to a 'legacy' MVC project (not vNext), still using Membership and the forms authentication module.
All OK, until I decided to make the web api a mobile service using the latest SDKs for Azure App Services for Mobile.

I have so far narrowed the problem to this

  //app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
            //{

            //    SigningKey = CloudConfigurationManager.GetSetting("authSigningKey"),
            //    ValidAudiences = new[] { CloudConfigurationManager.GetSetting("authAudience") },
            //    ValidIssuers = new[] { CloudConfigurationManager.GetSetting("authIssuer") },
            //    TokenHandler = GlobalConfiguration.Configuration.GetAppServiceTokenHandler()
            //});

This changes the rest of the app so that MVC + forms auth doesn't work. Running out of time to research the problem.
Any clues??

Body:
The following solution is working for me:
In your Startup register call UseCookieAuthentication, UseExternalSignInCookie or UseOAuthAuthorizationServer before calling UseAppServiceAuthentication.

Second step:
Add the following class to your project:

private sealed class CustomAppServiceAuthenticationMiddleware : AppServiceAuthenticationMiddleware
{
    private readonly ILogger _logger;

    public CustomAppServiceAuthenticationMiddleware(OwinMiddleware next, IAppBuilder appBuilder, AppServiceAuthenticationOptions options) : base(next, appBuilder, options)
    {
        _logger = (ILogger)GetType().BaseType.GetField("logger", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);
    }

    protected override AuthenticationHandler<AppServiceAuthenticationOptions> CreateHandler()
    {
        return new AppServiceAuthenticationHandler(_logger);
    }

    public override Task Invoke(IOwinContext context)
    {
        string logLine = $"AppServiceAuthMiddleware: {context.Request.Path}";

        if (context.Request.Headers.TryGetValue("Authorization", out var values))
            logLine += $"; Authorization: {values.First().Split(' ').FirstOrDefault()}";
        if (context.Request.Headers.TryGetValue("X-ZUMO-AUTH", out values))
            logLine += $"; X-ZUMO-AUTH: {values.First()}";

        _logger.WriteVerbose(logLine);
        Debug.WriteLine(logLine);

        if (IsZumoAuth(context))
        {
            return base.Invoke(context);
        }

        return Next.Invoke(context);
    }

    private bool IsZumoAuth(IOwinContext context)
    {
        return context.Request.Headers.ContainsKey("X-ZUMO-AUTH");
    }
}

Thrid step:
Replace the app.UseAppServiceAuthentication with the following:

        app.Use(typeof(CustomAppServiceAuthenticationMiddleware), app, new AppServiceAuthenticationOptions
        {
            SigningKey = ...,
            ValidAudiences = ...,
            ValidIssuers = ...,
            TokenHandler = ...
        });

This will the owin pipline make call the AppServiceAuthenticationMiddleware just for ZUMO-AUTH auth.

I've got a mixed web & mobile app.
With this approach the membership auth on the web app is working.
In the app, some custom oauth (refresh token based) plus the azure auth (facebook, google, ...) is working too. All that within the same asp.net application.


问:
C# - Windows Service EventMonitor function with parameters
I'm using PCSC library for SmartCard Readers events detection and trying to use it in Windows service.
Readers search function:

```<code> private void CheckPresentReaders()
    {
        using (var context = new SCardContext())
        {
            context.Establish(SCardScope.System);
            PresentCardReaders = context.GetReaders();
        }
    }
</code>```

SmartCard removed function:

```<code>private void SCardRemoved(object sender, CardStatusEventArgs e)
    {
        WriteToLog("Locking machine. SmartCard was removed.");
       // LockWorkStation();
    }
</code>```

Monitor creation:

```<code> CheckPresentReaders();
        if (PresentCardReaders.Length != 0)
        {
            SCardMonitor monitor = new SCardMonitor(ContextFactory.Instance, SCardScope.System);
            monitor.CardRemoved += new CardRemovedEvent(SCardRemoved);
            foreach (string reader in PresentCardReaders)
                monitor.Start(reader);
        }
</code>```

WriteToLog function is a simple Log Entry creation function.

When it is compiled - service starting and then stopping immediately.
I have two suspects - not delegated WriteToLog and/or SCardRemoved, which requires two parameters -

(object sender, CardStatusEventArgs e)
  Those are required by library.

Can this be a problem? Any other suggestions?
Thanks.

答:
I've implemented it properly into Topshelf Service and it does work.

https://github.com/35359595/SmartCardMonitorService

Body:
I'm using PCSC library for SmartCard Readers events detection and trying to use it in Windows service.
Readers search function:

 private void CheckPresentReaders()
    {
        using (var context = new SCardContext())
        {
            context.Establish(SCardScope.System);
            PresentCardReaders = context.GetReaders();
        }
    }

SmartCard removed function:

private void SCardRemoved(object sender, CardStatusEventArgs e)
    {
        WriteToLog("Locking machine. SmartCard was removed.");
       // LockWorkStation();
    }

Monitor creation:

 CheckPresentReaders();
        if (PresentCardReaders.Length != 0)
        {
            SCardMonitor monitor = new SCardMonitor(ContextFactory.Instance, SCardScope.System);
            monitor.CardRemoved += new CardRemovedEvent(SCardRemoved);
            foreach (string reader in PresentCardReaders)
                monitor.Start(reader);
        }

WriteToLog function is a simple Log Entry creation function.

When it is compiled - service starting and then stopping immediately.
I have two suspects - not delegated WriteToLog and/or SCardRemoved, which requires two parameters -

(object sender, CardStatusEventArgs e)
  Those are required by library.

Can this be a problem? Any other suggestions?
Thanks.