问:
Azure Mobile Services LoginAsync method not working with Microsoft Auth Token
I have successfully been able to get an access_token (or authenticationToken for Microsoft tokens) using the client side authentication in my Xamarin forms App.  I am able to get further user information (email, name, etc.) using the same access token.  Now, when I try to pass that token to my Azure Mobile Service backend, I get a 401 error.

Here is my code:

```<code>        private async System.Threading.Tasks.Task<string> MSGetUserInfo(Account account)
    {
        // Reference: http://graph.microsoft.io/en-us/docs/overview/call_api
        // Note that Microsoft don't recognize the access_token header entry, but rely instead on an Authorization header entry

        var client = new HttpClient();
        var userInfoRequest = new HttpRequestMessage()
        {
            RequestUri = new Uri("https://graph.microsoft.com/v1.0/me"),
            Method = HttpMethod.Get,
        };
        // Add acccess Bearer
        userInfoRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", account.Properties["access_token"]);
        using (var response = await client.SendAsync(userInfoRequest).ConfigureAwait(false))
        {
            if (response.IsSuccessStatusCode)
            {
                Models.User user = new Models.User();
                var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var jobject = JObject.Parse(responseString);
                var userName = (string)jobject["userPrincipalName"];
                // Check username is valid
                if (String.IsNullOrEmpty(userName))
                {
                    throw new Exception("Username was not set for authenticated user");
                }
                else
                    user.ProviderLoginId = userName;

                var userDisplayName = (string)jobject["displayName"];
                // Replace display name if invalid
                if (String.IsNullOrWhiteSpace(userDisplayName))
                {
                    userDisplayName = userName;
                }
                else
                    user.Name = userDisplayName;
                var userEmail = (string)jobject["mail"];
                // Replace email if invalid
                if (String.IsNullOrWhiteSpace(userEmail))
                {
                    userEmail = userName;
                }
                else
                    user.Email = userEmail;

                Valufy.App.currentUser = user;
            }
            else
            {
                throw new Exception("OAuth2 request failed: " + await response.Content.ReadAsStringAsync().ConfigureAwait(false));
            }
        }
        return "success";
    }
</code>```

The above code snippet works in getting my user details.  Now when I try to use the same token in the subsequent call, I get a 404:

```<code>        public async Task<bool> Authenticate(string token)
    {
        string message = string.Empty;
        var success = false;
        JObject objToken = new JObject();
        //objToken.Add("access_token", token);  //for facebook and google
        objToken.Add("authenticationToken", token); //for microsoft

        try
        {
            // Sign in with Facebook login using a server-managed flow.
            if (user == null)
            {
                //ProviderAuth("MICROSOFT");
                user = await syncMgr.CurrentClient
                    .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, objToken);
                if (user != null)
                {
                    success = true;
                    message = string.Format("You are now signed-in as {0}.", user.UserId);
                }
            }

        }
        catch (Exception ex)
        {
            message = string.Format("Authentication Failed: {0}", ex.Message);
        }

        // Display the success or failure message.
   //     await new MessageDialog(message, "Sign-in result").ShowAsync();

        return success;
    }
</code>```

Is there something that I am doing wrong?  Any and all assistance is appreciated.

答:
According to your description, I followed this Git sample about Microsoft Graph Connect Sample for UWP (REST). I could get the access_token and it could work as expected with Microsoft Graph API (e.g. Get a user). But when I use this access_token as the authenticationToken token object for MobileServiceClient.LoginAsync, I could also get 401 Unauthorized.

Then I checked the managed client for Azure Mobile Apps about Authenticate users. For Client-managed authentication flow, I found that the official code sample about using Microsoft Account is working with Live SDK as follows:

```<code>// Request the authentication token from the Live authentication service.
// The wl.basic scope should always be requested.  Other scopes can be added
LiveLoginResult result = await liveIdClient.LoginAsync(new string[] { "wl.basic" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
    session = result.Session;

    // Get information about the logged-in user.
    LiveConnectClient client = new LiveConnectClient(session);
    LiveOperationResult meResult = await client.GetAsync("me");

    // Use the Microsoft account auth token to sign in to App Service.
    MobileServiceUser loginResult = await App.MobileService
        .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);
}
</code>```

Note: As LiveConnectSession states about AuthenticationToken:

The authentication token for a signed-in and connected user.

While check the authentication with Microsoft Graph, I could only find the access_token instead of AuthenticationToken.

UPDATE:

I have checked LiveLogin for WP8 and Microsoft Account Authentication for Mobile Apps via Fiddler to capture the authorize requests. I found that MS account authentication has the similar authorize request as Live SDK.

I assumed that you need to leverage Live SDK to authenticate the user when using client side authentication with Microsoft account. I found the Live SDK download page is not exist, you could follow the Live SDK for WP8 to get started with Live SDK.

UPDATE2:

For the client-flow authentication (Microsoft Account), you could leverage MobileServiceClient.LoginWithMicrosoftAccountAsync("{Live-SDK-session-authentication-token}"), also you could use LoginAsync with the token parameter of the value {"access_token":"{the_access_token}"} or {"authenticationToken":"{Live-SDK-session-authentication-token}"}. I have tested LoginAsync with the access_token from MSA and retrieve the logged info as follows:

Body:
I have successfully been able to get an access_token (or authenticationToken for Microsoft tokens) using the client side authentication in my Xamarin forms App.  I am able to get further user information (email, name, etc.) using the same access token.  Now, when I try to pass that token to my Azure Mobile Service backend, I get a 401 error.

Here is my code:

        private async System.Threading.Tasks.Task<string> MSGetUserInfo(Account account)
    {
        // Reference: http://graph.microsoft.io/en-us/docs/overview/call_api
        // Note that Microsoft don't recognize the access_token header entry, but rely instead on an Authorization header entry

        var client = new HttpClient();
        var userInfoRequest = new HttpRequestMessage()
        {
            RequestUri = new Uri("https://graph.microsoft.com/v1.0/me"),
            Method = HttpMethod.Get,
        };
        // Add acccess Bearer
        userInfoRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", account.Properties["access_token"]);
        using (var response = await client.SendAsync(userInfoRequest).ConfigureAwait(false))
        {
            if (response.IsSuccessStatusCode)
            {
                Models.User user = new Models.User();
                var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                var jobject = JObject.Parse(responseString);
                var userName = (string)jobject["userPrincipalName"];
                // Check username is valid
                if (String.IsNullOrEmpty(userName))
                {
                    throw new Exception("Username was not set for authenticated user");
                }
                else
                    user.ProviderLoginId = userName;

                var userDisplayName = (string)jobject["displayName"];
                // Replace display name if invalid
                if (String.IsNullOrWhiteSpace(userDisplayName))
                {
                    userDisplayName = userName;
                }
                else
                    user.Name = userDisplayName;
                var userEmail = (string)jobject["mail"];
                // Replace email if invalid
                if (String.IsNullOrWhiteSpace(userEmail))
                {
                    userEmail = userName;
                }
                else
                    user.Email = userEmail;

                Valufy.App.currentUser = user;
            }
            else
            {
                throw new Exception("OAuth2 request failed: " + await response.Content.ReadAsStringAsync().ConfigureAwait(false));
            }
        }
        return "success";
    }

The above code snippet works in getting my user details.  Now when I try to use the same token in the subsequent call, I get a 404:

        public async Task<bool> Authenticate(string token)
    {
        string message = string.Empty;
        var success = false;
        JObject objToken = new JObject();
        //objToken.Add("access_token", token);  //for facebook and google
        objToken.Add("authenticationToken", token); //for microsoft

        try
        {
            // Sign in with Facebook login using a server-managed flow.
            if (user == null)
            {
                //ProviderAuth("MICROSOFT");
                user = await syncMgr.CurrentClient
                    .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, objToken);
                if (user != null)
                {
                    success = true;
                    message = string.Format("You are now signed-in as {0}.", user.UserId);
                }
            }

        }
        catch (Exception ex)
        {
            message = string.Format("Authentication Failed: {0}", ex.Message);
        }

        // Display the success or failure message.
   //     await new MessageDialog(message, "Sign-in result").ShowAsync();

        return success;
    }

Is there something that I am doing wrong?  Any and all assistance is appreciated.

Body:
According to your description, I followed this Git sample about Microsoft Graph Connect Sample for UWP (REST). I could get the access_token and it could work as expected with Microsoft Graph API (e.g. Get a user). But when I use this access_token as the authenticationToken token object for MobileServiceClient.LoginAsync, I could also get 401 Unauthorized.

Then I checked the managed client for Azure Mobile Apps about Authenticate users. For Client-managed authentication flow, I found that the official code sample about using Microsoft Account is working with Live SDK as follows:

// Request the authentication token from the Live authentication service.
// The wl.basic scope should always be requested.  Other scopes can be added
LiveLoginResult result = await liveIdClient.LoginAsync(new string[] { "wl.basic" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
    session = result.Session;

    // Get information about the logged-in user.
    LiveConnectClient client = new LiveConnectClient(session);
    LiveOperationResult meResult = await client.GetAsync("me");

    // Use the Microsoft account auth token to sign in to App Service.
    MobileServiceUser loginResult = await App.MobileService
        .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);
}

Note: As LiveConnectSession states about AuthenticationToken:

The authentication token for a signed-in and connected user.

While check the authentication with Microsoft Graph, I could only find the access_token instead of AuthenticationToken.

UPDATE:

I have checked LiveLogin for WP8 and Microsoft Account Authentication for Mobile Apps via Fiddler to capture the authorize requests. I found that MS account authentication has the similar authorize request as Live SDK.

I assumed that you need to leverage Live SDK to authenticate the user when using client side authentication with Microsoft account. I found the Live SDK download page is not exist, you could follow the Live SDK for WP8 to get started with Live SDK.

UPDATE2:

For the client-flow authentication (Microsoft Account), you could leverage MobileServiceClient.LoginWithMicrosoftAccountAsync("{Live-SDK-session-authentication-token}"), also you could use LoginAsync with the token parameter of the value {"access_token":"{the_access_token}"} or {"authenticationToken":"{Live-SDK-session-authentication-token}"}. I have tested LoginAsync with the access_token from MSA and retrieve the logged info as follows:


来源: stackexchange

问:
MySQL auto-increment problem on master-master replication , and the logic to solve it
I had a auto-increment duplication issue for master-master replication.  Then, I set:

```<code>SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 99999;
</code>```

This skips 9999 queries.  Then I did:

```<code>SHOW SLAVE STATUS\G
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
</code>```

And it seems to be running OK.

But, of course, since I skipped 99999 statements...if I make a change on Database 1, it will not reflect it on Database 2...until 99999 statements are passed. Correct?

Well...I created a script to automatically insert 999999 rows into a dummy table.  This should be more than enough , right?  And my 2 databases should be in sync again???

But, I am on my 3 millionth row, and it doesn't seem to be working.  My Database 2 still does not have these 3 million rows that I just created on Database 1.

答:
What I do in instances like this is:

stop the slave (STOP SLAVE)

drop the slave table that is out of sync

stop the master (STOP MASTER)

dump the MASTER table that is correct

re-import the MASTER table into the SLAVE

restart master and slave

Tables should now be back in sync.

ContentLicense: CC BY-SA 2.5

Body:
I had a auto-increment duplication issue for master-master replication.  Then, I set:

SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 99999;

This skips 9999 queries.  Then I did:

SHOW SLAVE STATUS\G
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

And it seems to be running OK.

But, of course, since I skipped 99999 statements...if I make a change on Database 1, it will not reflect it on Database 2...until 99999 statements are passed. Correct?

Well...I created a script to automatically insert 999999 rows into a dummy table.  This should be more than enough , right?  And my 2 databases should be in sync again???

But, I am on my 3 millionth row, and it doesn't seem to be working.  My Database 2 still does not have these 3 million rows that I just created on Database 1.


问:
JavaFX Auto Open new Window
I have A.fxml and B.fxml. A runing with Java Application override start method. I want to every 40 min in loop(5 times) { open new stage B.fxml and wait stage.close, if stage close continue loop open new stage B fxml. Loop this five times. I try timer timertask i could not. I try JavaFX Service i could not. I create Mythread extend Thread object. This time i could not control loop for next stage. When for statement start opening 5 stage. But i want to loop wait for currentstage is close then go next loop.  This is my fail code;

```<code>public class Driver extends Application {

public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(View.SETTINGS));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.setTitle("Info Library");
    stage.setResizable(false);
    stage.show();
    RandomQuestionThread thread = new RandomQuestionThread();
    if (DBContext.settings.isAbbreviation() || DBContext.settings.isTranslation()) {
        thread.start();
    }
}

public static void main(String[] args) throws InterruptedException {
    DBContext.settings = DBContext.getInstance().settings().getSettings();

    launch(args);
    HibernateUtil.getSessionFactory().close();
}
</code>```

}

```<code>public class RandomQuestionThread extends Thread {
Thread randomThread = new Thread(this);
private String fxml;
private static String TITLE;

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(DBContext.settings.getAutoQuestionTime() * 6000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int i = 0; i<DBContext.settings.getAutoQuestionCount(); i++) {
            randomFxml();
            Platform.runLater(()->{
                Parent root = null;
                try {
                    root = new FXMLLoader(getClass().getResource(fxml)).load();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Stage stage = new Stage();
                stage.setScene(new Scene(root));
                stage.setTitle(TITLE);
                stage.show();
                System.out.println(currentThread().getName());
            });
        }
    }
}

private void randomFxml() {
    int start = 0;
    if (DBContext.settings.isTranslation() && DBContext.settings.isAbbreviation()) {
        start = new Random().nextInt(2);
    } else if (DBContext.settings.isTranslation()) {
        start = 1;
    }

    switch (start) {
    case 0:
        fxml = View.ABBREVIATION;
        break;
    case 1:
        fxml = View.TRANSLATION;
        break;

    default:
        break;
    }
    if (start == 0) {
        TITLE = "KISALTMA SORUSU";
    } else TITLE = "ÇEVİRİ SORUSU";
}
</code>```

}

I need to work more Java multi threads. But after fix this problem. Please explain where I'm doing wrong. In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.My brain gave blue screen error.

答:
In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.

Using Platform.runLater you schedule the Runnable to be executed on the javafx application thread instead of the current thread which allows you to modify the UI, but also results in the current thread being the javafx application thread instead of the thread you call Platform.runLater from...

If you want to continue the "loop" after the window has been closed, you should schedule opening the next window after the last one has been closed. Stage.showAndWait() is a convenient way to wait for the stage to be closed.

For scheduling I'd recommend using a ScheduledExecutorService:

```<code>private ScheduledExecutorService executor;

@Override
public void stop() throws Exception {
    // stop executor to allow the JVM to terminate
    executor.shutdownNow();
}

@Override
public void init() throws Exception {
    executor = Executors.newSingleThreadScheduledExecutor();
}

@Override
public void start(Stage primaryStage) {
    Button btn = new Button("Start");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent event) {
            // just display a "empty" scene
            Scene scene = new Scene(new Pane(), 100, 100);
            Stage stage = new Stage();
            stage.setScene(scene);

            // schedule showing the stage after 5 sec
            executor.schedule(new Runnable() {

                private int openCount = 5;

                @Override
                public void run() {
                    Platform.runLater(() -> {
                        stage.showAndWait();
                        if (--openCount > 0) {
                            // show again after 5 sec unless the window was already opened 5 times
                            executor.schedule(this, 5, TimeUnit.SECONDS);
                        }
                    });
                }

            }, 5, TimeUnit.SECONDS);

        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: JavaFX Auto Open new Window

Body:
I have A.fxml and B.fxml. A runing with Java Application override start method. I want to every 40 min in loop(5 times) { open new stage B.fxml and wait stage.close, if stage close continue loop open new stage B fxml. Loop this five times. I try timer timertask i could not. I try JavaFX Service i could not. I create Mythread extend Thread object. This time i could not control loop for next stage. When for statement start opening 5 stage. But i want to loop wait for currentstage is close then go next loop.  This is my fail code;

public class Driver extends Application {

public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(View.SETTINGS));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.setTitle("Info Library");
    stage.setResizable(false);
    stage.show();
    RandomQuestionThread thread = new RandomQuestionThread();
    if (DBContext.settings.isAbbreviation() || DBContext.settings.isTranslation()) {
        thread.start();
    }
}

public static void main(String[] args) throws InterruptedException {
    DBContext.settings = DBContext.getInstance().settings().getSettings();

    launch(args);
    HibernateUtil.getSessionFactory().close();
}

}

public class RandomQuestionThread extends Thread {
Thread randomThread = new Thread(this);
private String fxml;
private static String TITLE;

@Override
public void run() {
    while (true) {
        try {
            Thread.sleep(DBContext.settings.getAutoQuestionTime() * 6000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int i = 0; i<DBContext.settings.getAutoQuestionCount(); i++) {
            randomFxml();
            Platform.runLater(()->{
                Parent root = null;
                try {
                    root = new FXMLLoader(getClass().getResource(fxml)).load();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Stage stage = new Stage();
                stage.setScene(new Scene(root));
                stage.setTitle(TITLE);
                stage.show();
                System.out.println(currentThread().getName());
            });
        }
    }
}

private void randomFxml() {
    int start = 0;
    if (DBContext.settings.isTranslation() && DBContext.settings.isAbbreviation()) {
        start = new Random().nextInt(2);
    } else if (DBContext.settings.isTranslation()) {
        start = 1;
    }

    switch (start) {
    case 0:
        fxml = View.ABBREVIATION;
        break;
    case 1:
        fxml = View.TRANSLATION;
        break;

    default:
        break;
    }
    if (start == 0) {
        TITLE = "KISALTMA SORUSU";
    } else TITLE = "ÇEVİRİ SORUSU";
}

}

I need to work more Java multi threads. But after fix this problem. Please explain where I'm doing wrong. In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.My brain gave blue screen error.

Body:
In loop write console currentThread name console result "Java Apllication Thread". But i set my thread name "MyThread". I'm so confused.

Using Platform.runLater you schedule the Runnable to be executed on the javafx application thread instead of the current thread which allows you to modify the UI, but also results in the current thread being the javafx application thread instead of the thread you call Platform.runLater from...

If you want to continue the "loop" after the window has been closed, you should schedule opening the next window after the last one has been closed. Stage.showAndWait() is a convenient way to wait for the stage to be closed.

For scheduling I'd recommend using a ScheduledExecutorService:

private ScheduledExecutorService executor;

@Override
public void stop() throws Exception {
    // stop executor to allow the JVM to terminate
    executor.shutdownNow();
}

@Override
public void init() throws Exception {
    executor = Executors.newSingleThreadScheduledExecutor();
}

@Override
public void start(Stage primaryStage) {
    Button btn = new Button("Start");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent event) {
            // just display a "empty" scene
            Scene scene = new Scene(new Pane(), 100, 100);
            Stage stage = new Stage();
            stage.setScene(scene);

            // schedule showing the stage after 5 sec
            executor.schedule(new Runnable() {

                private int openCount = 5;

                @Override
                public void run() {
                    Platform.runLater(() -> {
                        stage.showAndWait();
                        if (--openCount > 0) {
                            // show again after 5 sec unless the window was already opened 5 times
                            executor.schedule(this, 5, TimeUnit.SECONDS);
                        }
                    });
                }

            }, 5, TimeUnit.SECONDS);

        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}


问:
Export the data in table to pdf file
I am creating a website through wordpress. In that, I have made a table which have multiple rows and contain inputs having same classes.

HTML:

```<code><table id="data">
  <tr>
    <th>S.No.</th>
    <th>Name</th>
    <th>Class</th>
  </tr>
  <tr>
    <td>1.</td>
    <td><input class="name"></td>
    <td><input class="class"></td>
  </tr>
  <tr>
    <td>2.</td>
    <td><input class="name"></td>
    <td><input class="class"></td>
  </tr>
  <tr>
    <td>3.</td>
    <td><input class="name"></td>
    <td><input class="class"></td>
  </tr>
</table>
</code>```

Now, I want to create a button on my webpage which on click exports the data entered in the inputs of the table to a pdf file. I am trying to use jspdf but when I click the button, it doesn't do anything.

How can I create the button?

答:
it can done use this http://www.fpdf.org/ php library
tutorials http://www.fpdf.org/en/tutorial/tuto1.htm

Title: Export the data in table to pdf file

Body:
I am creating a website through wordpress. In that, I have made a table which have multiple rows and contain inputs having same classes.

HTML:

    S.No.
    Name
    Class

    1.
    <input class="name">
    <input class="class">

    2.
    <input class="name">
    <input class="class">

    3.
    <input class="name">
    <input class="class">

Now, I want to create a button on my webpage which on click exports the data entered in the inputs of the table to a pdf file. I am trying to use jspdf but when I click the button, it doesn't do anything.

How can I create the button?


问:
How to fill out grouped data by day?
From events table, I get grouped events count by day and for this I use

```<code>SELECT event_date, COUNT(event_id) event_count FROM events
WHERE event_date >= TRUNC(SYSDATE-1, 'DD')
GROUP BY event_date
ORDER BY event_date
</code>```

My problem here is that this returns only these days, where are some events

2017-04-03 , 4

2017-04-05 , 2

but I need get all consecutive days from Yesterday to next 30 day, and fill out this days from my grouped events data, like this

2017-03-31 ,

2017-04-01 ,

2017-04-02 ,

2017-04-03 , 4

2017-04-04 ,

2017-04-05 , 2

2017-04-06 ,

... Next 30 days (with events count when events exists in my table)
...

How to do that? Thank you for any help

答:
So, you can generate next 30 days from yesterday (see first subquery) and then simply left join it to your existing query.

Try this:

```<code>select  all_days.days  ,  certain_days.event_count from (
    select  TRUNC( sysdate + level - 2, 'DD') as days from DUAL connect by level <= 30
) all_days
left join (
    SELECT event_date, COUNT(event_id) event_count FROM events
    WHERE event_date >= TRUNC(SYSDATE-1, 'DD')
    GROUP BY event_date
) certain_days
on   all_days.days  =  certain_days.event_date
order by  all_days.days
</code>```

Title: How to fill out grouped data by day?

Body:
From events table, I get grouped events count by day and for this I use

SELECT event_date, COUNT(event_id) event_count FROM events
WHERE event_date >= TRUNC(SYSDATE-1, 'DD')
GROUP BY event_date
ORDER BY event_date

My problem here is that this returns only these days, where are some events

2017-04-03 , 4

2017-04-05 , 2

but I need get all consecutive days from Yesterday to next 30 day, and fill out this days from my grouped events data, like this

2017-03-31 ,

2017-04-01 ,

2017-04-02 ,

2017-04-03 , 4

2017-04-04 ,

2017-04-05 , 2

2017-04-06 ,

... Next 30 days (with events count when events exists in my table)
...

How to do that? Thank you for any help

Body:
So, you can generate next 30 days from yesterday (see first subquery) and then simply left join it to your existing query.

Try this:

select  all_days.days  ,  certain_days.event_count from (
    select  TRUNC( sysdate + level - 2, 'DD') as days from DUAL connect by level <= 30
) all_days
left join (
    SELECT event_date, COUNT(event_id) event_count FROM events
    WHERE event_date >= TRUNC(SYSDATE-1, 'DD')
    GROUP BY event_date
) certain_days
on   all_days.days  =  certain_days.event_date
order by  all_days.days


问:
Subtracting current from previous row by date and ID
I'd like to extend this answer here by including an ID as a grouping column. I tried including a 'group by' clause without success.

+----------+--------------+----------
|NAV_Date  |NetAssetValue |  ID      |
+----------+--------------+---------+
|12/31/2012|        $4,000|     A     |
+----------+--------------+---------+
|03/31/2013|        $5,000|     A     |
+----------+--------------+---------+
|12/31/2012|        $4,000|     B     |
+----------+--------------+---------+
|03/31/2013|        $5,000|     B     |
+----------+--------------+---------+
```

```select NAV_date, NAV_value, (NAV_value / prev_value) - 1
from (select t.*,
             (select top 1 NAV_value
              from YOURTABLENAMEGOESHERE as t2
              where t2.NAV_date < t.NAV_date
              group by Nav_ID, Nav_value
              order by t2.NAV_date desc
             ) as prev_value
      from YOURTABLENAMEGOESHERE as t
     ) as t
```

答:
Try this:</p>

```<code>select
    NAV_date,
    NAV_value,
    (NAV_value /
        (select top 1 NAV_value
        from YOURTABLENAMEGOESHERE as t2
        where t2.NAV_date < t.NAV_date
        order by t2.NAV_date desc) - 1
from
    YOURTABLENAMEGOESHERE as t
</code>```

Body:
I'd like to extend this answer here by including an ID as a grouping column. I tried including a 'group by' clause without success.

+----------+--------------+----------
|NAV_Date  |NetAssetValue |  ID      |
+----------+--------------+---------+
|12/31/2012|        $4,000|     A     |
+----------+--------------+---------+
|03/31/2013|        $5,000|     A     |
+----------+--------------+---------+
|12/31/2012|        $4,000|     B     |
+----------+--------------+---------+
|03/31/2013|        $5,000|     B     |
+----------+--------------+---------+

select NAV_date, NAV_value, (NAV_value / prev_value) - 1
from (select t.*,
             (select top 1 NAV_value
              from YOURTABLENAMEGOESHERE as t2
              where t2.NAV_date < t.NAV_date
              group by Nav_ID, Nav_value
              order by t2.NAV_date desc
             ) as prev_value
      from YOURTABLENAMEGOESHERE as t
     ) as t

Body:
Try this:

select
    NAV_date,
    NAV_value,
    (NAV_value /
        (select top 1 NAV_value
        from YOURTABLENAMEGOESHERE as t2
        where t2.NAV_date < t.NAV_date
        order by t2.NAV_date desc) - 1
from
    YOURTABLENAMEGOESHERE as t


问:
Objective-C Programming: Will Learning C and/or Smalltalk Help?
Objective-C is an object-oriented programming language that adds Smalltalk-style messaging to the C programming language. I understand that learning Smalltalk might be good in the same way that learning Lisp is good for one's knowledge, but I want to know if learning Smalltalk-specific concepts will help me to understand Objective-C more completely, given Smalltalk's role in its "origin story". If so, what specifically?

Assuming that one already knows C programming, what can we learn from Smalltalk? Obviously, there's a lot of concepts in Objective-C that just aren't in C (ie. messaging, interfaces, protocols, dynamic typing, delegation, reflection; it's object-oriented!) but are derived from Smalltalk.

Edit: I've added the C programming language to the question, as the general consensus is that learning C is a better use of one's time than learning Smalltalk (when it comes to programming in Objective-C).

答: Getting used to passing messages to objects instead of calling methods is pretty easy without a SmallTalk background. However, SmallTalk doesn't look anything like C (except for the SuperCollider variant) and the language even treats code blocks and other crazy stuff as first-class objects: e.g. in SuperCollider {i < 5}.while({ // do stuff }) This behavior did not come over to Objective-C and will likely just confuse you as it does me.


问:
jQuery validate only the elements which are visible?
In my html page i have 24 fields which have their class = "emi".

Out of these 24  0 , 6 ,12 ,18 or 24 of them can be visible based on the value of a dropdown on my page.

Now i have to perform validations only on the elements which are visible.

I have used jQuery's .hide() and  .show() to hide and show these elements

答:
This should be like

```<code>$("#myForm").validate({ignore:":not(:visible)"});
</code>```

use

```<code>not(:visible)
</code>```

instead of ":hidden"

Body:
This should be like

$("#myForm").validate({ignore:":not(:visible)"});

use

not(:visible)

instead of ":hidden"


问:
how to calculate term-document matrix?
I know that Term-Document Matrix is a mathematical matrix that describes the frequency of terms that occur in a collection of documents. In a document-term matrix, rows correspond to documents in the collection and columns correspond to terms.

I am using sklearn's CountVectorizer to extract features from strings( text file ) to ease my task. The following code returns a term-document matrix according to the sklearn_documentation

```<code>from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
vectorizer = CountVectorizer(min_df=1)
print(vectorizer)
content = ["how to format my hard disk", "hard disk format problems"]
X = vectorizer.fit_transform(content) #X is Term-document matrix
print(X)
</code>```

The output is as follows

 I am not getting how this matrix has been calculated.please discuss the example shown in the code.  I have read one more example from the Wikipedia but could not understand.

答:
The output of a CountVectorizer().fit_transform() is a sparse matrix. It means that it will only store the non-zero elements of a matrix. When you do print(X), only the non-zero entries are displayed as you observe in the image.

As for how the calculation is done, you can have a look at the official documentation here.

The CountVectorizer in its default configuration, tokenize the given document or raw text (It will take only terms which have 2 or more characters in it) and count the word occurrences.

Basically, the steps are as follow:

Step1 - Collect all different terms from all the documents present in fit().

For your data, they are
[u'disk', u'format', u'hard', u'how', u'my', u'problems', u'to']
This is available from vectorizer.get_feature_names()

Step2 - In the transform(), count the number of terms in each document which were present in the fit() output it in the term-frequency matrix.

In your case, you are supplying both documents to transform() (fit_transform() is a shorthand for fit() and then transform()). So, the result is

[u'disk', u'format', u'hard', u'how', u'my', u'problems', u'to']

First  1          1         1        1      1         0          1

Sec    0          1         1        0      0         1          0

You can get the above result by calling X.toarray().

In the image of the print(X) you posted, the first column represents the index of the term-freq matrix and second represents the frequencey of that term.

<0,0> means first row, first column i.e frequencies of term "disk" (first term in our tokens) in first document = 1

<0,2> means first row, third column i.e frequencies of term "hard" (third term in our tokens) in first document = 1

<0,5> means first row, sixth column i.e frequencies of term "problems" (sixth term in our tokens) in first document = 0. But since it is 0, it is not displayed in your image.

Title: how to calculate term-document matrix?

Body:
I know that Term-Document Matrix is a mathematical matrix that describes the frequency of terms that occur in a collection of documents. In a document-term matrix, rows correspond to documents in the collection and columns correspond to terms.

I am using sklearn's CountVectorizer to extract features from strings( text file ) to ease my task. The following code returns a term-document matrix according to the sklearn_documentation

from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
vectorizer = CountVectorizer(min_df=1)
print(vectorizer)
content = ["how to format my hard disk", "hard disk format problems"]
X = vectorizer.fit_transform(content) #X is Term-document matrix
print(X)

The output is as follows

 I am not getting how this matrix has been calculated.please discuss the example shown in the code.  I have read one more example from the Wikipedia but could not understand.


问:
Angular 2 Checkbox value with Reactive form
i have checkbox in angular 2 reactive form i need to pass the values of these checkbox in POST api , Right now they will pass value on status.
below are checkbox code it only passed the status like true or false instead of value like 1,2 something like that.

```<code><input type="checkbox" formControlName="servicelatest"  [value]="CatArry[i].id" (change)="serviceCheckBox($event)"/>
</code>```

-------------------**------------------------

```<code><div *ngFor="let serviceType of laceDetailFrom.controls.serviceType.controls; let i=index" >
<div  [formGroupName]="i">

<input type="checkbox" formControlName="servicelatest"  [value]="CatArry[i].id" (change)="services[$event.target.getAttribute('value')]=$event.target.checked"> {{CatArry[i].cat_name}}
                             </div>
                           </div>
</code>```

答:
Template Side :

```<code><input type="checkbox" formControlName="servicelatest"  [value]="CatArry[i].id"
(change)="services[$event.target.getAttribute('value')]=$event.target.checked"/>
</code>```

Component Side :

```<code>services = {};
</code>```

And then use services as your selected checkboxes values

Body:
i have checkbox in angular 2 reactive form i need to pass the values of these checkbox in POST api , Right now they will pass value on status.
below are checkbox code it only passed the status like true or false instead of value like 1,2 something like that.

<input type="checkbox" formControlName="servicelatest"  [value]="CatArry[i].id" (change)="serviceCheckBox($event)"/>

-------------------**------------------------

<input type="checkbox" formControlName="servicelatest"  [value]="CatArry[i].id" (change)="services[$event.target.getAttribute('value')]=$event.target.checked"> {{CatArry[i].cat_name}}

Body:
Template Side :

<input type="checkbox" formControlName="servicelatest"  [value]="CatArry[i].id"
(change)="services[$event.target.getAttribute('value')]=$event.target.checked"/>

Component Side :

services = {};

And then use services as your selected checkboxes values


问:
how to make a vectorized file in python. I need to convert tweets to vector form inorder to run a code in bayesian network
Is it possible to make a dataset atleast? I am doing sentiment analysis and is getting polarity of the message
I was following this tutorial. But it is not the data set required.
http://machinelearningmastery.com/naive-bayes-classifier-scratch-python/

It would be great if anyone could explain the csv file given here.

答:
Basically, the process of converting a collection of text documents into numerical feature vectors is called vectorization. There are several techniques or concepts that can be used to vectorize text documents(for eg. word embeddings, bag of words, etc.).

Bag of words is one of the simplest ways to vectorize text into numerical features. TfIdf is an effective vectorization technique based on the bag of words concept.

On a very basic level, TfIdf uses a set of unigrams or bigrams(n-grams in general) from the entire text corpus and uses them as the features for all your text documents(tweets in your case). So if you imagine your text corpus as a table of numerical values then each row would be a text document(a tweet in your case) and each column would be a unigram(which is basically a word) and the value of each cell (i,j) in the table would depend on the term frequency of unigram j in the tweet i(the number of times that the particular unigram occurs in the tweet) and the inverse of the document frequency of the unigram j(the number of tweets that the particular unigram occurs in all the tweets combined). Hence, you would have a list of tweets as vectors which would have a numerical tfidf values corresponding to each feature(unigram).

For more information on how to implement tfidf look at the following links:

http://scikit-learn.org/stable/modules/feature_extraction.html#the-bag-of-words-representation

http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html


问:
How to assign SQLiteOpenHelper in Custom Adapter?
I have searched an answer to this question quite long, but haven't found yet.
I'm doing project with SQLiteDatabase. Everything works fine, except assigning SQLiteOpenHelper to my CustomAdapter. I'm about two months in Android studio and all that Java thing, so I'm just searching almost everything on the internet. Here are fragments of my project.

SQLiteOpenHelper:

public class ActivitiesDataBase extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "database.db";
    public static final String ACTIVITIES_COLUMN_ID = "id";
    public static final String ACTIVITIES_TABLE_NAME = "create_activity";
    public static final String ACTIVITIES_COLUMN_NAME = "activity";
    public static final String ACTIVITIES_COLUMN_NUMBER = "number";
    public static final String ACTIVITIES_COLUMN_DESCRIPTION = "description";

    //Created command to create items
    public void addactivity(String activity, String description, String number){

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put(ACTIVITIES_COLUMN_NAME, activity);
        cv.put(ACTIVITIES_COLUMN_NUMBER, number);
        cv.put(ACTIVITIES_COLUMN_DESCRIPTION, description);

        db.insert(ACTIVITIES_TABLE_NAME, null, cv);
        db.close();
    }

    //Constructor
        public ActivitiesDataBase(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE create_activity" +
                "(id INTEGER PRIMARY KEY, " +
                "activity TEXT, " +
                "number TEXT, " +
                "description TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS create_activity");

    }
}```
</div>
</div>
</p>

<p><strong>Small part of ActivityMain:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class MainActivity extends AppCompatActivity implements DrawerLocker {

//Assigning SQLiteOpenHelper, no errors, result is fine.
    final ActivitiesDataBase db = new ActivitiesDataBase(this);

    private SQLiteDatabase sql;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//Here I call command addactivity and it works fine, because I
//assigned SQLiteOpenHelper well.
    db.addactivity(activitysubject, activitydesc, activitynum);

    }
}</code>```

And here is my Custom Adapter:

public class CustomAdapter extends ArrayAdapter {

    private List sarasas = new ArrayList();

    public CustomAdapter(Context context, int resource) {
        super(context, resource);
    }

    @Override
    public void add(Object object) {
        super.add(object);
        sarasas.add(object);
    }

    @Override
    public int getCount() {
        return this.sarasas.size();
    }

    @Override
    public Object getItem(int position) {
        return this.sarasas.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        final Duomenys pavadinimas;

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

            pavadinimas = new Duomenys();
//I have missed some unnecessary text here, hope it doesn't change
//contex a lot

//So, crap starts here. Don't mind that pavadinimas after dots.
//Basically it's written here similarly to MainActivity, but it
//shows errors because assigning is different :(

//           (SQLiteOpenHelper assigning is below)
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pavadinimas.db.addactivity(name, description, number);
                }
            });

            v.setTag(pavadinimas);
        }else {
            pavadinimas = (Duomenys) v.getTag();
        }

        DataActivity perdavimas = (DataActivity) this.getItem(position);
        pavadinimas.txt1.setText(perdavimas.getNamee());

        return v;

    }

    static class Duomenys{

        SQLiteDatabase sql;

        //Here i don't know how to assign my SQLiteOpenHelper,
        // so actually, I NEED HELP HERE
        ActivitiesDataBase db;

    }
}```
</div>
</div>
</p>

<p>So, I really would like to know, how to assign (if possible) SQLiteOpenHelper in Custom Adapter. Any help is apreciated.</p>

<blockquote>
  <p>So, this is my edited version. Everything is fine with static class Duomenys, but there is some underlines in that part:</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

//Here it underlines mContext and i really don't know from where to get it
        final Duomenys pavadinimas = new Duomenys(mContext);

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

//Then it underlines () after Duomenys
            pavadinimas = new Duomenys();
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

pavadinimas.db.assactivity(name, description, number);

                }
            });

           v.setTag(pavadinimas);
        }else {

//And it underlines pavadinimas, saying
//"Cannot assign a value to final variable 'pavadinimas'  "
            pavadinimas = (Duomenys) v.getTag();
        }</code>```

答:
So, with help of @AgiMaulana i solved the problem. Code changed only in CustomAdapter, so here it is:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        final Duomenys pavadinimas;

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

            pavadinimas = new Duomenys(getContext());
            pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    pavadinimas.db.modifyNumber(name, newNumber);
                }
            });

        v.setTag(pavadinimas);
        }else {
            pavadinimas = (Duomenys) v.getTag();
        }```

Thank you guys very much!

Body:
I have searched an answer to this question quite long, but haven't found yet.
I'm doing project with SQLiteDatabase. Everything works fine, except assigning SQLiteOpenHelper to my CustomAdapter. I'm about two months in Android studio and all that Java thing, so I'm just searching almost everything on the internet. Here are fragments of my project.

SQLiteOpenHelper:

public class ActivitiesDataBase extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "database.db";
    public static final String ACTIVITIES_COLUMN_ID = "id";
    public static final String ACTIVITIES_TABLE_NAME = "create_activity";
    public static final String ACTIVITIES_COLUMN_NAME = "activity";
    public static final String ACTIVITIES_COLUMN_NUMBER = "number";
    public static final String ACTIVITIES_COLUMN_DESCRIPTION = "description";

    //Created command to create items
    public void addactivity(String activity, String description, String number){

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv =new ContentValues();
        cv.put(ACTIVITIES_COLUMN_NAME, activity);
        cv.put(ACTIVITIES_COLUMN_NUMBER, number);
        cv.put(ACTIVITIES_COLUMN_DESCRIPTION, description);

        db.insert(ACTIVITIES_TABLE_NAME, null, cv);
        db.close();
    }

    //Constructor
        public ActivitiesDataBase(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE create_activity" +
                "(id INTEGER PRIMARY KEY, " +
                "activity TEXT, " +
                "number TEXT, " +
                "description TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS create_activity");

    }
}

Small part of ActivityMain:

public class MainActivity extends AppCompatActivity implements DrawerLocker {

//Assigning SQLiteOpenHelper, no errors, result is fine.
    final ActivitiesDataBase db = new ActivitiesDataBase(this);

    private SQLiteDatabase sql;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//Here I call command addactivity and it works fine, because I
//assigned SQLiteOpenHelper well.
    db.addactivity(activitysubject, activitydesc, activitynum);

    }
}

And here is my Custom Adapter:

public class CustomAdapter extends ArrayAdapter {

    private List sarasas = new ArrayList();

    public CustomAdapter(Context context, int resource) {
        super(context, resource);
    }

    @Override
    public void add(Object object) {
        super.add(object);
        sarasas.add(object);
    }

    @Override
    public int getCount() {
        return this.sarasas.size();
    }

    @Override
    public Object getItem(int position) {
        return this.sarasas.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        final Duomenys pavadinimas;

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

            pavadinimas = new Duomenys();
//I have missed some unnecessary text here, hope it doesn't change
//contex a lot

//So, crap starts here. Don't mind that pavadinimas after dots.
//Basically it's written here similarly to MainActivity, but it
//shows errors because assigning is different :(

//           (SQLiteOpenHelper assigning is below)
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pavadinimas.db.addactivity(name, description, number);
                }
            });

            v.setTag(pavadinimas);
        }else {
            pavadinimas = (Duomenys) v.getTag();
        }

        DataActivity perdavimas = (DataActivity) this.getItem(position);
        pavadinimas.txt1.setText(perdavimas.getNamee());

        return v;

    }

    static class Duomenys{

        SQLiteDatabase sql;

        //Here i don't know how to assign my SQLiteOpenHelper,
        // so actually, I NEED HELP HERE
        ActivitiesDataBase db;

    }
}

So, I really would like to know, how to assign (if possible) SQLiteOpenHelper in Custom Adapter. Any help is apreciated.

So, this is my edited version. Everything is fine with static class Duomenys, but there is some underlines in that part:

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

//Here it underlines mContext and i really don't know from where to get it
        final Duomenys pavadinimas = new Duomenys(mContext);

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

//Then it underlines () after Duomenys
            pavadinimas = new Duomenys();
pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

pavadinimas.db.assactivity(name, description, number);

                }
            });

           v.setTag(pavadinimas);
        }else {

//And it underlines pavadinimas, saying
//"Cannot assign a value to final variable 'pavadinimas'  "
            pavadinimas = (Duomenys) v.getTag();
        }

Body:
So, with help of @AgiMaulana i solved the problem. Code changed only in CustomAdapter, so here it is:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        final Duomenys pavadinimas;

        if (v == null){
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.listview_layout, parent, false);

            pavadinimas = new Duomenys(getContext());
            pavadinimas.plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    pavadinimas.db.modifyNumber(name, newNumber);
                }
            });

        v.setTag(pavadinimas);
        }else {
            pavadinimas = (Duomenys) v.getTag();
        }

Thank you guys very much!


问:
Local mirror of Pypi that can download package on demand as Nexus
I'm finding some application to provide me a local mirror of Pypi on internet repository. But I'm not interested to download the entire Pypi repository, I need build my local repo on demand like Nexus external repositories.

For example:
my local.repo have package A, B then when I request package C, the package C and their dependencies are downloaded from an external repo (some pypi internet repo) and are stored on local.repo.

Anybody know some alternatives to do it?

答:
Actually you can use directly Nexus as PyPi repo provider in both host/proxy mode. It has been requested here:
https://issues.sonatype.org/browse/NEXUS-6037

And docs are available here:
https://books.sonatype.com/nexus-book/3.0/reference/pypi.html

NOTE: Not all Nexus 2 functionalities are available in Nexus 3, some of them are slowly migrated, some of them will never be migrated, so we end-up running temporarily both version in parallel each for different purpose, but in case of pure PyPi integration, Nexus 3 is production ready.


问:
How to Replace null with "-" using single line in Jquery
How to Replace null with -  using single line in jQuery

For Example

```<code>    var obj={
        "Key1":null,
        "key2":"I have null",
        "key3":null

    }
</code>```

Expected Output:

```<code>var obj={
    "Key1":"-",
    "key2":"I have null",
    "key3":"-"

}
</code>```

答:
In one line, It would look something like

```<code>JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"')));
</code>```

var obj = {
  "Key1": null,
  "key2": "I have null",
  "key3": null
}

var obj1=JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"')));

console.log(obj1)```
</div>
</div>
</p>

<p>To make the code generic </p>

```$.each( obj, function( key, value ) {
 if (value == null)
   value = "-";
});
```

Body:
How to Replace null with -  using single line in jQuery

For Example

    var obj={
        "Key1":null,
        "key2":"I have null",
        "key3":null

    }

Expected Output:

var obj={
    "Key1":"-",
    "key2":"I have null",
    "key3":"-"

}

Body:
In one line, It would look something like

JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"')));

var obj = {
  "Key1": null,
  "key2": "I have null",
  "key3": null
}

var obj1=JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"')));

console.log(obj1)

To make the code generic

$.each( obj, function( key, value ) {
 if (value == null)
   value = "-";
});


问:
creating a program and getting these errors
Can any one help with the errors im receiving

c55 error:general error

c55 error:faliure

I'm trying to compile the code and these are the errors im receiving and I dont know how to correct them at all

failed to locate output file 'pic control 1.obj'

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

unsigned char state, nxtstate, inbyte,g1,g2;

void checkS1S2()
{
    inbyte=porta;

    if ((inByte & 0x0F) == 0x07) //70%
    {
        nextstate =1; // turn on G1
    }

    if ((inByte & 0xF0) == 0x20) // 50%
    {
        nextstate =2; // turn on G2
    }

    if ((inByte & 0xF0) == 0xFF) // 100%
    {
        nextstate =3; // turn on G1 and G2
    }

    if (((inByte & 0xF0) == 0x00) || ((inByte & 0xF0) == 0x01))
    {
        nextState = 4; // TurnoFF G2
    }

    if (((inByte & 0x0F) == 0x00) || ((inByte & 0x0F) == 0x01)  || ((inByte & 0x0F) == 0x02) )
    {
        nextState = 5; // TurnoFF G1
    }
}

void state1(void)
{
    bitset(portb1); // switch on G1
    nextstate = 1;
    g1 =1;
}//end of state1.

void state2(void)
{
    bitset(portb2); // switch on G2
    nextstate = 1;
    g2 =1;
}//end of state2

void state3(void)
{
    checktime;
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6;
        else
            state1;
    }
}

void state6(void)
{
    // switch OFF G0,G1,G2
    bitclear(portb,0);
    bitclear(portb,1);
    bitclear(portb,2);
    bitset(portb3);
    nextstate = 1;
    g1 =0;
    g2=0;
}//end of state6

void state4(void)
{
    bitclear(portb,1); // Switch OFF G1
    nextstate =1;
    g1 =0;
}

void state5()
{
    bitclear(portb,2); // Switch OFF G2
    g2 =0;
}

int main(void)
{
    // Configure RA0-RA3 as S1 , RA4-RA7 as S2
    // Configure RB0 as G0 , RB1 as G1 , RB2 as G2 and RB3 as LED
    config();
    nxtstate=0;
}
</code>```

答:
Your function state3 contains line that are not valid C code:

```<code>void state3(void)
{
    checktime;
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6;
        else
            state1;
    }
}
</code>```

I assume that your intention was to add a comment and to invoke functions. In thart case you should do this:

```<code>void state3(void)
{
    /* checktime */
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6();
        else
            state1();
    }
}
</code>```

Probably the checktime should be an boolean expression:

```<code>void state3(void)
{
    if (checktime)
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6();
        else
            state1();
    }
}
</code>```

As you can see, the question left enough room for guessing.

Body:
Can any one help with the errors im receiving

c55 error:general error

c55 error:faliure

I'm trying to compile the code and these are the errors im receiving and I dont know how to correct them at all

failed to locate output file 'pic control 1.obj'

#include <system.h>
#include <stdio.h>

unsigned char state, nxtstate, inbyte,g1,g2;

void checkS1S2()
{
    inbyte=porta;

    if ((inByte & 0x0F) == 0x07) //70%
    {
        nextstate =1; // turn on G1
    }

    if ((inByte & 0xF0) == 0x20) // 50%
    {
        nextstate =2; // turn on G2
    }

    if ((inByte & 0xF0) == 0xFF) // 100%
    {
        nextstate =3; // turn on G1 and G2
    }

    if (((inByte & 0xF0) == 0x00) || ((inByte & 0xF0) == 0x01))
    {
        nextState = 4; // TurnoFF G2
    }

    if (((inByte & 0x0F) == 0x00) || ((inByte & 0x0F) == 0x01)  || ((inByte & 0x0F) == 0x02) )
    {
        nextState = 5; // TurnoFF G1
    }
}

void state1(void)
{
    bitset(portb1); // switch on G1
    nextstate = 1;
    g1 =1;
}//end of state1.

void state2(void)
{
    bitset(portb2); // switch on G2
    nextstate = 1;
    g2 =1;
}//end of state2

void state3(void)
{
    checktime;
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6;
        else
            state1;
    }
}

void state6(void)
{
    // switch OFF G0,G1,G2
    bitclear(portb,0);
    bitclear(portb,1);
    bitclear(portb,2);
    bitset(portb3);
    nextstate = 1;
    g1 =0;
    g2=0;
}//end of state6

void state4(void)
{
    bitclear(portb,1); // Switch OFF G1
    nextstate =1;
    g1 =0;
}

void state5()
{
    bitclear(portb,2); // Switch OFF G2
    g2 =0;
}

int main(void)
{
    // Configure RA0-RA3 as S1 , RA4-RA7 as S2
    // Configure RB0 as G0 , RB1 as G1 , RB2 as G2 and RB3 as LED
    config();
    nxtstate=0;
}

Body:
Your function state3 contains line that are not valid C code:

void state3(void)
{
    checktime;
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6;
        else
            state1;
    }
}

I assume that your intention was to add a comment and to invoke functions. In thart case you should do this:

void state3(void)
{
    /* checktime */
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6();
        else
            state1();
    }
}

Probably the checktime should be an boolean expression:

void state3(void)
{
    if (checktime)
    {
        if time up && (g1 ==1) && (g2 ==1);
            state6();
        else
            state1();
    }
}

As you can see, the question left enough room for guessing.


问:
Fixed Element Overflow in css

Hello,

I have an header that its position is fixed. When I scroll the page, the paragraph below decreases its opacity. when the paragraph goes up, it overlays the header instead of "going under it". How can I fix it.

Thank you very much

答:
Try adding z-index to your header.

```<code>z-index: 9999;
</code>```

Header z-index should be more than you content's z-index.
hope this helps

Title: Fixed Element Overflow in css

Body:
Try adding z-index to your header.

z-index: 9999;

Header z-index should be more than you content's z-index.
hope this helps


答:
You could use Object.keys and check the value. with a recursive function with a closure over the iterating object.

var iter = o => k => o[k] && typeof o[k] === 'object' && Object.keys(o[k]).forEach(iter(o[k])) || o[k] === null && (o[k] = '-'),
    object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } };

Object.keys(object).forEach(iter(object));
console.log(object);```
</div>
</div>
</p>

<p>which basically resolves with ES5 in</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } };

Object.keys(object).forEach(function iter(o) {
    return function (k) {
        if (o[k] && typeof o[k] === 'object') {
            Object.keys(o[k]).forEach(iter(o[k]));
            return;
        }
        o[k] === null && (o[k] = '-');
    };
}(object));
console.log(object);</code>```

Title: How to Replace null with "-" using single line in Jquery

Body:
You could use Object.keys and check the value. with a recursive function with a closure over the iterating object.

var iter = o => k => o[k] && typeof o[k] === 'object' && Object.keys(o[k]).forEach(iter(o[k])) || o[k] === null && (o[k] = '-'),
    object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } };

Object.keys(object).forEach(iter(object));
console.log(object);

which basically resolves with ES5 in

var object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } };

Object.keys(object).forEach(function iter(o) {
    return function (k) {
        if (o[k] && typeof o[k] === 'object') {
            Object.keys(o[k]).forEach(iter(o[k]));
            return;
        }
        o[k] === null && (o[k] = '-');
    };
}(object));
console.log(object);


问:
How can you write a power Enum with visitor semantics in Scala?
There is a pattern I use often to make code simpler that I like to call a Power Enum which is an enumeration that takes advantage of the visitor pattern as well as carries custom data. Here is an example in Java:

```<code>import java.security.SecureRandom;
import java.util.UUID;
import java.util.stream.IntStream;

public class PowerEnumDemo {
    private static final SecureRandom random = new SecureRandom();

    public static void main(String[] args) {
        for (int i = 0; i < 3 ; i++) {
            final Color selected = Color.values()[random.nextInt(3)];
            System.out.println("Selected: " + selected);
            System.out.println("rgb: " + selected.rgb);
            selected.visit();
        }
    }

    public enum Color {
        RED("0000ff") {
            @Override
            public void visit() {
                IntStream.range(1, 10).forEach(System.out::println);
            }
        },
        GREEN("00ff00") {
            @Override
            public void visit() {
                System.out.println(UUID.randomUUID().toString().chars().filter(c -> c == 'a').count());
                ;
            }
        },
        BLUE("ff0000") {
            @Override
            public void visit() {
                System.out.println("Hello World");
            }
        };
        final String rgb;

        Color(final String rgb) {
            this.rgb = rgb;
        }

        /**
         * This is where the enum implements the visitor pattern to do special stuff.
         */
        public abstract void visit();
    }
}
</code>```

If one runs this little program you will see how it works. We don't have to know which Enum is selected and we don't have to do any if loops which can be annoying to maintain. If a dev adds a new enum they have to define its data and implement the visit method or the code wont compile. But when they do it will work for everyone calling visit.

I want to implement this in Scala but I am at a loss of how to proceed. Here is the proscribed method of creating an enum which is a tad obscure:

```<code>object Color extends Enumeration{
  type Color = Value
  val RED, GREEN, BLUE = Value
}
</code>```

What I don't see is how I can define my custom data and my abstract visit method and have each val implement the visit method. (for those that don't get it in the java example each enum is kind of a subtype of the main Color enum.) So any of you scala gurus can get this working? :-)

答:
For enums in Scala I would go with sealed traits instead of the Enumeration class. Especially for use cases like this.

```<code>sealed trait Color {
  def visit: Unit
  def rgb: String
}
object Color {
  case object RED extends Color {
    def visit = println("Hello World!")
    val rgb = "ff0000"
  }
  ....
}
</code>```

Body:
There is a pattern I use often to make code simpler that I like to call a Power Enum which is an enumeration that takes advantage of the visitor pattern as well as carries custom data. Here is an example in Java:

import java.security.SecureRandom;
import java.util.UUID;
import java.util.stream.IntStream;

public class PowerEnumDemo {
    private static final SecureRandom random = new SecureRandom();

    public static void main(String[] args) {
        for (int i = 0; i < 3 ; i++) {
            final Color selected = Color.values()[random.nextInt(3)];
            System.out.println("Selected: " + selected);
            System.out.println("rgb: " + selected.rgb);
            selected.visit();
        }
    }

    public enum Color {
        RED("0000ff") {
            @Override
            public void visit() {
                IntStream.range(1, 10).forEach(System.out::println);
            }
        },
        GREEN("00ff00") {
            @Override
            public void visit() {
                System.out.println(UUID.randomUUID().toString().chars().filter(c -> c == 'a').count());
                ;
            }
        },
        BLUE("ff0000") {
            @Override
            public void visit() {
                System.out.println("Hello World");
            }
        };
        final String rgb;

        Color(final String rgb) {
            this.rgb = rgb;
        }

        /**
         * This is where the enum implements the visitor pattern to do special stuff.
         */
        public abstract void visit();
    }
}

If one runs this little program you will see how it works. We don't have to know which Enum is selected and we don't have to do any if loops which can be annoying to maintain. If a dev adds a new enum they have to define its data and implement the visit method or the code wont compile. But when they do it will work for everyone calling visit.

I want to implement this in Scala but I am at a loss of how to proceed. Here is the proscribed method of creating an enum which is a tad obscure:

object Color extends Enumeration{
  type Color = Value
  val RED, GREEN, BLUE = Value
}

What I don't see is how I can define my custom data and my abstract visit method and have each val implement the visit method. (for those that don't get it in the java example each enum is kind of a subtype of the main Color enum.) So any of you scala gurus can get this working? :-)

Body:
For enums in Scala I would go with sealed traits instead of the Enumeration class. Especially for use cases like this.

sealed trait Color {
  def visit: Unit
  def rgb: String
}
object Color {
  case object RED extends Color {
    def visit = println("Hello World!")
    val rgb = "ff0000"
  }
  ....
}


问:
joomla invitex menu
Just wondering, anyone can guest the problem.

I have joomla + invitex installed, so when i tried to create a menu for invitex in main menu, everthing looks fine.

But then the problem is, when i clicked on the invite menu, result in page not found. The url for invite menu looks funny, like this :

```<code>http://foxy.local/component/option,com_invitex/Itemid,35/view,invites/
</code>```

Anyone know how to fix?

答: You mean the foxy.local? If that looks wrong, it's a setting in your Joomla configuration.php file (the domain) or invitex settings.</p>

Title: joomla invitex menu

Body:
Just wondering, anyone can guest the problem.

I have joomla + invitex installed, so when i tried to create a menu for invitex in main menu, everthing looks fine.

But then the problem is, when i clicked on the invite menu, result in page not found. The url for invite menu looks funny, like this :

http://foxy.local/component/option,com_invitex/Itemid,35/view,invites/

Anyone know how to fix?


问:
How to preview what a XAML control with bound values looks like
I'm writing an app in XAML, and I'm using binding for getting values to the UI layer.  I'd like to see what my control will look like while making changes to the XAML, but because the data values are bound, many areas show up as blank (which, in turn, messes up the relative layout).

Is there any way to give XAML values to use for rendering the control review without replacing the Binding directives?

答:
Maybe you can set TargetNullValue or FallbackValue property in your binding, example:

```<code>  <TextBlock Text="{Binding NotExsitOrNullPropertyName, TargetNullValue=SomeDefaultValue, FallbackValue=SomeDefaultValue}" ></TextBlock>
</code>```

Hope it hepls.

Body:
Maybe you can set TargetNullValue or FallbackValue property in your binding, example:

  <TextBlock Text="{Binding NotExsitOrNullPropertyName, TargetNullValue=SomeDefaultValue, FallbackValue=SomeDefaultValue}" ></TextBlock>

Hope it hepls.


问:
How to read Assembly Opcode Reference?
I want to make Assembly compiler. To do that, I should make research about Assembly opcodes, so I found this on the Web. When I test to compile some codes with NASM, like this:

```<code>add eax, eax
</code>```

It outputs this on Binary:

6601C0

However, when I see the reference of Assembly Opcodes, it displays this screen:

Where ADD opcode is 00, 01, 02, 03, 04, 05.
Which opcode is right? Can I use all of them, or should I use 01 (based on binary compiled with NASM).

答:
What you found is just some reference that someone on the Internet put together. The authoritative reference comes from Intel and can be downloaded here: Intel® 64 and IA-32 Architectures Software Developer Manuals.

You obviously assembled the code for a 16-bit real-mode environment (like DOS), where it was assembled to 66 01 C0.

Look at the first byte 66. This is called by Intel "operand-size override prefix" and in your reference "OPSIZE". It changes the size of the operands from 16-bit to 32-bit (AX to EAX). That is why I guess the environment is a 16-bit system.

The second byte 01 is the ADD instruction in your reference on the second place in the first line. Your reference calls it ADD Ev Gv. The Intel manual calls it ADD r/m16, r16. With the operand-size override prefix you can read it as ADD r/m32, r32.

The third byte C0 is the "Ev Gv" in your reference (Intel: "r/m32, r32"). Intel calls it "ModR/M" byte. Some bits in this byte define the target("Ev"), some bits define the source ("Gv"). Look at the table "Table 2-1. 16-Bit Addressing Forms with the ModR/M Byte" in the Intel manual.

To answer your question: No, you have to use the specific ADD instruction for the specific purpose. The ADD instructions perform different operations.

ContentLicense: CC BY-SA 4.0

Title: How to read Assembly Opcode Reference?

Body:
I want to make Assembly compiler. To do that, I should make research about Assembly opcodes, so I found this on the Web. When I test to compile some codes with NASM, like this:

add eax, eax

It outputs this on Binary:

6601C0

However, when I see the reference of Assembly Opcodes, it displays this screen:

Where ADD opcode is 00, 01, 02, 03, 04, 05.
Which opcode is right? Can I use all of them, or should I use 01 (based on binary compiled with NASM).


问:
PHP - magic quotes gpc and stripslashes question
Okay my hosting company has magic_quotes_gpc turned ON and I coded my PHP script using stripslashes() in preparation of this. But now the hosting company says its going to turn magic_quotes_gpc OFF and I was wondering what will happen now to my data now when stripslashes() is present should I go through all my millions of lines of code and get rid of stripslashes()? or leave the stripslashes() function alone? will leaving the stripslashes() ruin my data?

答:
Your code should use get_magic_quotes_gpc to see if magic quotes are enabled, and only strip slashes if they are. You should run a block of code similar to the following in exactly one place, shared by all your scripts; if you're using stripslashes in multiple places you're doing it wrong.

```<code>// recursively strip slashes from an array
function stripslashes_r($array) {
  foreach ($array as $key => $value) {
    $array[$key] = is_array($value) ?
      stripslashes_r($value) :
      stripslashes($value);
  }
  return $array;
}

if (get_magic_quotes_gpc()) {
  $_GET     = stripslashes_r($_GET);
  $_POST    = stripslashes_r($_POST);
  $_COOKIE  = stripslashes_r($_COOKIE)
  $_REQUEST = stripslashes_r($_REQUEST);
}
</code>```

Body:
Your code should use get_magic_quotes_gpc to see if magic quotes are enabled, and only strip slashes if they are. You should run a block of code similar to the following in exactly one place, shared by all your scripts; if you're using stripslashes in multiple places you're doing it wrong.

// recursively strip slashes from an array
function stripslashes_r($array) {
  foreach ($array as $key => $value) {
    $array[$key] = is_array($value) ?
      stripslashes_r($value) :
      stripslashes($value);
  }
  return $array;
}

if (get_magic_quotes_gpc()) {
  $_GET     = stripslashes_r($_GET);
  $_POST    = stripslashes_r($_POST);
  $_COOKIE  = stripslashes_r($_COOKIE)
  $_REQUEST = stripslashes_r($_REQUEST);
}


问:
Some files are not generating , while creating a Microservice application in JHipster
Some files are not generating , while creating a Microservice application in JHipster.

I created a Jhipster Microservice application, with MySQL DB, Hazelcast caching, Eureka server, Elastic search engine and Cucumber testing Tool.

I have installed all the pre-requisite before creating JHipster project (Java 8, Maven, Git hub, Node.js, Yeoman, Yard, gulp and Bower, jhipster generator)

But after creating the project, some files seems to be missing (like Gulpfile and Bower files).

Could anyone help me on this

答: A JHipster microservice appliocation has no UI so there's no frontend tooling needed (gulp, bower, ...). The UI is on a gateway which you probably haven't generated. See our documentation, there is a diagram that shows all the elements of our microservices architecture.</p>


问:
Big-O for while loops with user input
Suppose Module X requires p units of time to be executed, where p is a constant. Find the complexity of each of the following algorithm where n is the size of the input data and q is a positive integer greater than 1. What will be the time complexity?</p>

```<code>set i = 1
   `while i ≤ n`
      `Module X`
      `i = q * i`
    endwhile
</code>```

答:
log(n) where the base of the logarithmic function is q.

Hint: i increases exponentially.

Title: Big-O for while loops with user input

Body:
Suppose Module X requires p units of time to be executed, where p is a constant. Find the complexity of each of the following algorithm where n is the size of the input data and q is a positive integer greater than 1. What will be the time complexity?

set i = 1
   `while i ≤ n`
      `Module X`
      `i = q * i`
    endwhile


问:
How can I rename files in bulk based on their comma-separated contents in shell?
I have hundreds of files suffixed with ".txt". The "txt" files contain "id[0-9]" in a column with delimiter "," from other columns. What I want is to extract the "id[0-9]" as the file name of the corresponding file automatically one by one, any ideas?

for example:  ben.txt ,cotains:

aa,bb,cc,id2233,kk

And many files like this.

Then how can I extract id2233 to replace ben.txt to id2233.txt using shell or other methods？

thanks.

答:
Generate a script to rename files.

```<code># old.names: generate files with old and new names
# new.names:
# rename.sh: file with commands to rename

paste old.names new.names | awk '{o = $1; n = $2; print "mv", o, n}' > rename.sh

# if you like how rename.sh looks
sh rename.sh
</code>```

A fancier version which tolerates spaces in the file names

```<code>paste old.names new.names | \
    awk -v FS='\t' \
    '{ o = $1
       n = $2
       print "mv --", w(o), w(n)
     }
     function w(s) { return "'" s "'"} # wrap
    '
</code>```

Body:
Generate a script to rename files.

# old.names: generate files with old and new names
# new.names:
# rename.sh: file with commands to rename

paste old.names new.names | awk '{o = $1; n = $2; print "mv", o, n}' > rename.sh

# if you like how rename.sh looks
sh rename.sh

A fancier version which tolerates spaces in the file names

paste old.names new.names | \
    awk -v FS='\t' \
    '{ o = $1
       n = $2
       print "mv --", w(o), w(n)
     }
     function w(s) { return "'" s "'"} # wrap
    '


问:
SQL Server: Select Max for each sub group in result set
I am new to SQL Server. I have a table that contains user names, addresses and the update dates.

The following query gives me all required details from that table but my problem is that the table can contain multiple records for the same user / ID in case they changed their address more than once.

How can I only get the address from the latest update for each user / ID?  I tried with DISTINCT, TOP1 etc. but couldn't figure out a way to make this work.

My query:

```<code>SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC
</code>```

答:
Or you can do in an more intuitive old style fashion, just with a subselect:

```<code>SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u INNER JOIN
(
    -- here is where we get the last update
    select u.ID, max(u.updateDate) as lastUpdate from dbo.Users group by u.ID
) as s
on u.ID = s.ID
-- and here we force the address of the last update
WHERE u.updateDate = s.lastUpdate
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC
</code>```

You get the last update of each ID in a subselect, and filter this date in the WHERE clause.

Body:
I am new to SQL Server. I have a table that contains user names, addresses and the update dates.

The following query gives me all required details from that table but my problem is that the table can contain multiple records for the same user / ID in case they changed their address more than once.

How can I only get the address from the latest update for each user / ID?  I tried with DISTINCT, TOP1 etc. but couldn't figure out a way to make this work.

My query:

SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC

Body:
Or you can do in an more intuitive old style fashion, just with a subselect:

SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u INNER JOIN
(
    -- here is where we get the last update
    select u.ID, max(u.updateDate) as lastUpdate from dbo.Users group by u.ID
) as s
on u.ID = s.ID
-- and here we force the address of the last update
WHERE u.updateDate = s.lastUpdate
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC

You get the last update of each ID in a subselect, and filter this date in the WHERE clause.


问:
How to pass arguments to an included file?
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

```<code><?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.
</code>```

header.php

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>
</code>```

Obviously this doesn't work; how can I pass arguments to an included file?

答:
This is good approach. I however would do it a bit inside out. Define a layout, a wrapper for your webpage and include your content file into it:

```<code>layout.phtml

<html>
    <head>
      ... your headers go here
    </head>
    <body>
      <? include $content ?>
    </body>
</html>
</code>```

Your content template file can look like this e.g.

```<code>content.phtml

<h1>hello world</h1>

<p>My name is <?= $name ?></p>
</code>```

Then, you would have your main script (index) that will handle logic, connects to database etc.

```<code>index.php

$content = 'content.phtml';
$name = 'Marc'; //Can be pulled from database

include 'layout.phtml';
</code>```

This way, you can nicely separate business logic and presentation. And it can help you cut repetitive code for parts of page like logo or navigation which are repeated on the whole site.

Body:
I'm trying to make the whole  section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<link rel="shortcut icon" href="favicon.ico">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />

Obviously this doesn't work; how can I pass arguments to an included file?

Body:
This is good approach. I however would do it a bit inside out. Define a layout, a wrapper for your webpage and include your content file into it:

layout.phtml

<html>
    <head>
      ... your headers go here
    </head>
    <body>
      <? include $content ?>
    </body>
</html>

Your content template file can look like this e.g.

content.phtml

<h1>hello world</h1>

<p>My name is <?= $name ?></p>

Then, you would have your main script (index) that will handle logic, connects to database etc.

index.php

$content = 'content.phtml';
$name = 'Marc'; //Can be pulled from database

include 'layout.phtml';

This way, you can nicely separate business logic and presentation. And it can help you cut repetitive code for parts of page like logo or navigation which are repeated on the whole site.