问:
Node.js logging multiple requests with relative ID's
In a nutshell: can one associate logs (throughout an entire node API) to a certain (dynamic) reference ID?

[Explained further]

So, here is the situation: I am writing an API that potentially handles up to hundreds of requests at one time. It is implemented in Node.js and Express. I have extensive logging throughout the API and each log has to have a unique reference ID so that I can related several logs to the same request.

One way I can do this is by randomly generating a string and passing it as a parameter to every function call (I am keeping this as a last resort). I do not want to do this

To reiterate,

request comes in

randomly generate string: aljsndci.json

append (Express) request.body to aljsndci.json

do internal logic in API

log in json format, each log must contain key { ... file: 'aljsndci.json' ... }

append (Express) response to aljsndci.json

response through express

I have stumbled upon solutions like continuation-local-storage, however, how does one generate a unique string (for namespace) and then reference that same string later? All the examples here hard code the string for the namespace. Is there are example, similar to the one here (found here)

```<code>var getNamespace = require('continuation-local-storage').getNamespace;
var session = getNamespace('my session');

var render = require('./lib/render.js')

function finish(response) {
  var user = session.get('user');
  render({user: user}).pipe(response);
}
</code>```

where instead of var session = getNamespace('my session');, it actually calls the names of the series of callbacks from this point on? Something like var thisNamespace = getNamespace(this);

Basically if I could set a global variable for every subsequent callback, that would solve this problem

答:
I think the same exactly problem was solved in this question:
How to identify request (by ID) through middleware chain in Express.
Check it and if you have any doubts say it here or in the other question.</p>

Body:
In a nutshell: can one associate logs (throughout an entire node API) to a certain (dynamic) reference ID?

[Explained further]

So, here is the situation: I am writing an API that potentially handles up to hundreds of requests at one time. It is implemented in Node.js and Express. I have extensive logging throughout the API and each log has to have a unique reference ID so that I can related several logs to the same request.

One way I can do this is by randomly generating a string and passing it as a parameter to every function call (I am keeping this as a last resort). I do not want to do this

To reiterate,

request comes in

randomly generate string: aljsndci.json

append (Express) request.body to aljsndci.json

do internal logic in API

log in json format, each log must contain key { ... file: 'aljsndci.json' ... }

append (Express) response to aljsndci.json

response through express

I have stumbled upon solutions like continuation-local-storage, however, how does one generate a unique string (for namespace) and then reference that same string later? All the examples here hard code the string for the namespace. Is there are example, similar to the one here (found here)

var getNamespace = require('continuation-local-storage').getNamespace;
var session = getNamespace('my session');

var render = require('./lib/render.js')

function finish(response) {
  var user = session.get('user');
  render({user: user}).pipe(response);
}

where instead of var session = getNamespace('my session');, it actually calls the names of the series of callbacks from this point on? Something like var thisNamespace = getNamespace(this);

Basically if I could set a global variable for every subsequent callback, that would solve this problem


来源: stackexchange

问:
Advanced transparency in a form
Im looking for a way to create form(s) similar in style to the following two..

Ive played with transparency keys, the windows API, but have not successfully done this in Windows Forms.

[broken image]

what im looking for with this post is any references to articles explaining how this can be done, or some code examples. -- but i will accept any kind of input.

I would use Windows Vista/7 Areo glass if it didnt have such horrible alpha-blending issues.

答:
You can tell the DWM to extend the "glass" area of your window.
See Figure 10 in this article

Or, by using DirectX, you can get this effect. Don't think you can with winforms, though.

ContentLicense: CC BY-SA 4.0

Title: Advanced transparency in a form

ContentLicense: CC BY-SA 2.5


问:
Adding yuml diagrams into wiki pages
Is it somehow possible to insert yuml (https://yuml.me/diagram/scruffy/class/samples) diagrams into vsts-wiki pages?

I've tried it using the image markdown syntax:

```<code>![image](http://yuml.me/diagram/scruffy/class/[Customer]->[Billing Address])
</code>```

Or a more complex one:

```<code>![image](http://yuml.me/diagram/scruffy/class/[Customer]<>1->*[Order], [Customer]-[note: Aggregate Root{bg:cornsilk}])
</code>```

But the wiki page doesn't render it, instead the markdown is shown in plain text.

答:
Yes, yuml diagrams are supported for VSTS wiki page.

Just use the default yuml syntax , such as:

```<code><img src="http://yuml.me/diagram/scruffy/class/[Customer]->[Billing Address]" >
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding yuml diagrams into wiki pages

Body:
Is it somehow possible to insert yuml (https://yuml.me/diagram/scruffy/class/samples) diagrams into vsts-wiki pages?

I've tried it using the image markdown syntax:

![image](http://yuml.me/diagram/scruffy/class/[Customer]->[Billing Address])

Or a more complex one:

![image](http://yuml.me/diagram/scruffy/class/[Customer]<>1->*[Order], [Customer]-[note: Aggregate Root{bg:cornsilk}])

But the wiki page doesn't render it, instead the markdown is shown in plain text.

Body:
Yes, yuml diagrams are supported for VSTS wiki page.

Just use the default yuml syntax , such as:

<img src="http://yuml.me/diagram/scruffy/class/[Customer]->[Billing Address]" >


问:
How to assign a variable in the WHERE clause of a sub-query in SQL Server
```<code>SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp
</code>```

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

答:
Do you mean you want to compare against each Settlement_id from table PScData?.

From my understanding of the question, you might do a self join on the table PScData or use the below query.

This query will compare the settlement_id against all settlement_ids from the same table. I dont understand why you want to do this.

Please check the script and let me know if I get you wrong.

```<code>SELECT
        SUM(Total_Males) [Total_males],  SETTLEMENT_ID,URI, _PARENT_AURI
    FROM
        (SELECT
             COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
             t2._PARENT_AURI
         FROM
             PScData t1
         INNER JOIN
             PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
         WHERE
             t1.SETTLEMENT_ID in (SELECT DISTINCT SETTLEMENT_ID FROM PScData)
             AND t2.SEX = '1'
         GROUP BY
             t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp
group by
     SETTLEMENT_ID,URI, _PARENT_AURI
</code>```

Body:
SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

Body:
Do you mean you want to compare against each Settlement_id from table PScData?.

From my understanding of the question, you might do a self join on the table PScData or use the below query.

This query will compare the settlement_id against all settlement_ids from the same table. I dont understand why you want to do this.

Please check the script and let me know if I get you wrong.

SELECT
        SUM(Total_Males) [Total_males],  SETTLEMENT_ID,URI, _PARENT_AURI
    FROM
        (SELECT
             COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
             t2._PARENT_AURI
         FROM
             PScData t1
         INNER JOIN
             PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
         WHERE
             t1.SETTLEMENT_ID in (SELECT DISTINCT SETTLEMENT_ID FROM PScData)
             AND t2.SEX = '1'
         GROUP BY
             t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp
group by
     SETTLEMENT_ID,URI, _PARENT_AURI


问:
Combine two integer arrays into one array in java
I've seen similar questions and none provide the answer that I'm looking for, so I apologize in advance if this is considered a duplicate.
I'm trying to combine arrays {1, 2, 3} and {4, 5, 6} into {1, 2, 3, 4, 5, 6}. What am I doing incorrectly? I'm super new to java. Sorry if the question is stupid.   </p>

```<code>public class combine {
  public static void main(String[]args){

  int[]a = {1, 2, 3};
  int[]b = {4, 5, 6};
  int[]c = new int[a+b];
  for(int i=0; i<a.length; i++)
  System.out.print(c[i]+" ");
}
public static int[]merge(int[]a, int[]b){
  int[]c = new int[a.length+b.length];
  int i;
  for(i=0; i<a.length; i++)
     c[i] = a[i];

     for(int j=0; j<b.length; j++)
        c[i++]=b[j];
        return c;
}
}
</code>```

答:
```<code> public class MergeArrays {
    public static void main(String[]args){
         int[] a = {1, 2, 3};
         int[] b = {4, 5, 6};
         int[] c = new int[a.length+b.length];// Here length of int[] c will be 6
         int count = 0;

         //looping to store the value length of i
         for(int i = 0; i<a.length; i++) {
             c[i] = a[i];
             count++;
          }
        //looping to store the value length of j
          for(int j = 0;j<b.length;j++) {
             c[count++] = b[j];
          }
        //looping to retrieve the value of c
          for(int i = 0;i<c.length;i++)
              System.out.print(c[i]);// Displaying looped value/output in single line at console

    }
}
</code>```

Body:
I've seen similar questions and none provide the answer that I'm looking for, so I apologize in advance if this is considered a duplicate.
I'm trying to combine arrays {1, 2, 3} and {4, 5, 6} into {1, 2, 3, 4, 5, 6}. What am I doing incorrectly? I'm super new to java. Sorry if the question is stupid.

public class combine {
  public static void main(String[]args){

  int[]a = {1, 2, 3};
  int[]b = {4, 5, 6};
  int[]c = new int[a+b];
  for(int i=0; i<a.length; i++)
  System.out.print(c[i]+" ");
}
public static int[]merge(int[]a, int[]b){
  int[]c = new int[a.length+b.length];
  int i;
  for(i=0; i<a.length; i++)
     c[i] = a[i];

     for(int j=0; j<b.length; j++)
        c[i++]=b[j];
        return c;
}
}


问:
How do I prove the simplified Chinese Remainder Theorem?
I've managed to prove

```<code>Theorem modulo_inv : forall m n : Z, rel_prime m n -> exists x : Z, (m * x == 1 [n]). Admitted.
</code>```

My question is how to finish the following proof (maybe using the modulo_inv theorem?):

```<code>Variables m n : Z.
Hypothesis co_prime : rel_prime m n.

Theorem SimpleChineseRemainder :
  forall a b : Z, exists x : Z, (x == a [m]) /\ (x == b [n]).
</code>```

Here is what I tried, but I don't know whether it is correct or not.

```<code>Proof.
    intros a b.
    exists ((a * n) * (n ^ (-1) mod m) + (b * m) * (m ^ (-1) mod n)).
    refine (conj _ _).
        (* case : ((a * n) * (n ^ (-1) mod m) + (b * m) * (m ^ (-1) mod n) == a [m]) *)
        red.
        rewrite Z.add_sub_swap.
        apply Z.divide_add_r.

        (* case : ((a * n) * (n ^ (-1) mod m) + (b * m) * (m ^ (-1) mod n) == b [n]) *)
</code>```

Can anybody provide any suggestions?

答:
Code-golfing Anton's answer, I was hoping that ring would be clever enough to use the Eq information, and that the proof would simply be

```<code>Theorem SimpleChineseRemainder' a b :  exists x : Z, (x == a [m]) /\ (x == b [n]).
Proof.
  destruct (rel_prime_bezout _ _ co_prime) as [u v Eq];
  exists (a * v * n + b * u * m); split ; [ exists ((b-a)*u) | exists ((a-b)*v)]; ring.
Qed.
</code>```

Unfortunately it didn't automatically exploit that u * m + v * n = 1 -> u * m = 1 - v * n. So until we have a stronger tactic, I guess that has to be added manually, like so:

```<code>Theorem SimpleChineseRemainder' a b : exists x : Z, (x == a [m]) /\ (x == b [n]).
Proof.
  destruct (rel_prime_bezout _ _ co_prime) as [u v Eq].
  exists (a * (v * n) + b * (u * m)); split ; [ exists ((b-a)*u) | exists ((a-b)*v)].
  - replace (v*n) with (1-u*m) by (rewrite <- Eq; ring); ring.
  - replace (u*m) with (1-v*n) by (rewrite <- Eq; ring); ring.
Qed.
</code>```

EDIT:  The nsatz tactic is able to solve the equation system.  However, it introduces a notation for [ ... ] that conflicts with the notation introduced above, and I don't know  how to handle that.  However, by changing the notation to i.e. [[ ... ]], the proof becomes just two lines:

```<code>Require Import Nsatz.
Theorem SimpleChineseRemainder' a b :
  exists x : Z, (x == a [[m]]) /\ (x == b [[n]]).
Proof.
  destruct (rel_prime_bezout _ _ co_prime) as [u v Eq];
  exists (a * v * n + b * u * m); split ; [ exists ((b-a)*u) | exists ((a-b)*v)]; nsatz.
Qed.
</code>```

Body:
I've managed to prove

Theorem modulo_inv : forall m n : Z, rel_prime m n -> exists x : Z, (m * x == 1 [n]). Admitted.

My question is how to finish the following proof (maybe using the modulo_inv theorem?):

Variables m n : Z.
Hypothesis co_prime : rel_prime m n.

Theorem SimpleChineseRemainder :
  forall a b : Z, exists x : Z, (x == a [m]) /\ (x == b [n]).

Here is what I tried, but I don't know whether it is correct or not.

Proof.
    intros a b.
    exists ((a * n) * (n ^ (-1) mod m) + (b * m) * (m ^ (-1) mod n)).
    refine (conj _ _).
        (* case : ((a * n) * (n ^ (-1) mod m) + (b * m) * (m ^ (-1) mod n) == a [m]) *)
        red.
        rewrite Z.add_sub_swap.
        apply Z.divide_add_r.

        (* case : ((a * n) * (n ^ (-1) mod m) + (b * m) * (m ^ (-1) mod n) == b [n]) *)

Can anybody provide any suggestions?

Body:
Code-golfing Anton's answer, I was hoping that ring would be clever enough to use the Eq information, and that the proof would simply be

Theorem SimpleChineseRemainder' a b :  exists x : Z, (x == a [m]) /\ (x == b [n]).
Proof.
  destruct (rel_prime_bezout _ _ co_prime) as [u v Eq];
  exists (a * v * n + b * u * m); split ; [ exists ((b-a)*u) | exists ((a-b)*v)]; ring.
Qed.

Unfortunately it didn't automatically exploit that u * m + v * n = 1 -> u * m = 1 - v * n. So until we have a stronger tactic, I guess that has to be added manually, like so:

Theorem SimpleChineseRemainder' a b : exists x : Z, (x == a [m]) /\ (x == b [n]).
Proof.
  destruct (rel_prime_bezout _ _ co_prime) as [u v Eq].
  exists (a * (v * n) + b * (u * m)); split ; [ exists ((b-a)*u) | exists ((a-b)*v)].
  - replace (v*n) with (1-u*m) by (rewrite <- Eq; ring); ring.
  - replace (u*m) with (1-v*n) by (rewrite <- Eq; ring); ring.
Qed.

EDIT:  The nsatz tactic is able to solve the equation system.  However, it introduces a notation for [ ... ] that conflicts with the notation introduced above, and I don't know  how to handle that.  However, by changing the notation to i.e. [[ ... ]], the proof becomes just two lines:

Require Import Nsatz.
Theorem SimpleChineseRemainder' a b :
  exists x : Z, (x == a [[m]]) /\ (x == b [[n]]).
Proof.
  destruct (rel_prime_bezout _ _ co_prime) as [u v Eq];
  exists (a * v * n + b * u * m); split ; [ exists ((b-a)*u) | exists ((a-b)*v)]; nsatz.
Qed.


问:
How do I print a text file in .net
How do I print a .txt file in vb.net? Hopefully without using any third parties. </p>

答:
See How to print batch file in vb.net?. There's a VB.NET code sample which you should be able to use verbatim.

If you don't already know how to pull text out of a file, use File.ReadAllText, like this:

```<code>Imports System.IO
Dim path As String = "c:\temp\MyTest.txt"
RawPrinterHelper.SendStringToPrinter("WindowsPrinterName", File.ReadAllText(path))
</code>```

RawPrinterHelper is the class described in the other question linked above.  "WindowsPrinterName" is the name of the printer you want to print to.

Title: How do I print a text file in .net

Body:
See How to print batch file in vb.net?. There's a VB.NET code sample which you should be able to use verbatim.

If you don't already know how to pull text out of a file, use File.ReadAllText, like this:

Imports System.IO
Dim path As String = "c:\temp\MyTest.txt"
RawPrinterHelper.SendStringToPrinter("WindowsPrinterName", File.ReadAllText(path))

RawPrinterHelper is the class described in the other question linked above.  "WindowsPrinterName" is the name of the printer you want to print to.


问:
WPF MVVM DataGrid Row to Another DataGrid
In my WPF application using MVVM, I have one DataGrid (dgSelectCase) filled with a bound ObservableCollection from my ViewModel. A Button appears in the first column that, when clicked, should add the selected row to the second DataGrid (dgCaseSelected).

The View DataContext is bound to the ViewModel in its code behind, and I know it works because the other Controls on the page (Comboboxes, Textboxes, etc.) work perfectly. The "Add" Button Command in dgSelectCase is bound to the AddTo method in the ViewModel and the "Remove" Button Command in dgCaseSelected is bound to the RemoveFrom method in the ViewModel.

The "Add" Button is not working, but, more importantly, it looks like I have selection Binding issues in the dgSelectCase DataGrid because I get a red box around the DataGrid when I click on a row. Where have I gone wrong? Thanks for any and all help, as I'm still learning.... slowly :).  Following are Code Snippets.

XAML

```<code>        <DataGrid>
            <DataGrid.Columns>
            <DataGridTemplateColumn Header="Select">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Add" Command="{Binding AddTo}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
            <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
            <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
            <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>

        <DataGrid x:Name="dgCaseSelected"
              AutoGenerateColumns="False"
              ItemsSource="{Binding DGCaseBookingsSelected}"
              >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Select">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Remove" Command="{Binding RemoveFrom}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
                <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
                <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
                <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>
</code>```

VIEWMODEL

```<code>    private ObservableCollection<DGCaseBookings> _dgCaseBookingsList;
    private ObservableCollection<DGCaseBookings> _dgSelectedCaseBookings;
    private ObservableCollection<DGCaseBookings> _dgCaseBookingsSelected;

    public ObservableCollection<DGCaseBookings> DGCaseBookingsList
    {
        get { return _dgCaseBookingsList; }
        set
        {
            SetProperty(ref _dgCaseBookingsList, value, () => DGCaseBookingsList);
        }
    }

    public ObservableCollection<DGCaseBookings> DGSelectedCaseBookings
    {
        get { return _dgSelectedCaseBookings; }
        set
        {
            SetProperty(ref _dgSelectedCaseBookings, value, () => DGSelectedCaseBookings);
        }
    }

    public ObservableCollection<DGCaseBookings> DGCaseBookingsSelected
    {
        get { return _dgCaseBookingsSelected; }
        set
        {
            SetProperty(ref _dgCaseBookingsSelected, value, () => DGCaseBookingsSelected);
        }
    }

    public CMBookingSelectVM() : base()
    {
        DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
        DGCaseBookingsSelected = new ObservableCollection<DGCaseBookings>();
    }

    private void fillDGCaseBookingswithFacility()
    {
        using (MySqlConnection con = new MySqlConnection(dbConnectionString))
        {
            DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
            con.Open();
            string Query = ///SELECT STATEMENT WORKS FINE///
            MySqlCommand createCommand = new MySqlCommand(Query, con);
            MySqlDataReader dr = createCommand.ExecuteReader();
            int count = 1;
            while (dr.Read())
            {
                int FacilityIDNum = dr.GetInt32(0);
                int CaseBookingNum = dr.GetInt32(1);
                int BookingTypeNum = dr.GetInt32(2);
                string BookingType = dr.GetString(3);
                DGCaseBookings dgcb = new DGCaseBookings(count, FacilityIDNum, CaseBookingNum, BookingTypeNum, BookingType);
                DGCaseBookingsList.Add(dgcb);
                count++;
            }
            con.Close();
        }
    }

    public void AddTo(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsSelected.Add(dgcb);
            DGCaseBookingsList.Remove(dgcb);
        }
    }

    public void RemoveFrom(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsList.Add(dgcb);
            DGCaseBookingsSelected.Remove(dgcb);
        }
    }
</code>```

答:
In background of this you can setup the event when you click on button and add the current row (like param of the event). Take the current row select it from the datasource/ObservableCollection and add it in another dataset e.g  _dgSelectedCaseBookings. </p>

<p>After that you can refresh the new _dgSelectedCaseBookings on UI. </p>

Body:
In my WPF application using MVVM, I have one DataGrid (dgSelectCase) filled with a bound ObservableCollection from my ViewModel. A Button appears in the first column that, when clicked, should add the selected row to the second DataGrid (dgCaseSelected).

The View DataContext is bound to the ViewModel in its code behind, and I know it works because the other Controls on the page (Comboboxes, Textboxes, etc.) work perfectly. The "Add" Button Command in dgSelectCase is bound to the AddTo method in the ViewModel and the "Remove" Button Command in dgCaseSelected is bound to the RemoveFrom method in the ViewModel.

The "Add" Button is not working, but, more importantly, it looks like I have selection Binding issues in the dgSelectCase DataGrid because I get a red box around the DataGrid when I click on a row. Where have I gone wrong? Thanks for any and all help, as I'm still learning.... slowly :).  Following are Code Snippets.

XAML

        <DataGrid>
            <DataGrid.Columns>
            <DataGridTemplateColumn Header="Select">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Content="Add" Command="{Binding AddTo}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
            <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
            <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
            <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>

        <DataGrid x:Name="dgCaseSelected"
              AutoGenerateColumns="False"
              ItemsSource="{Binding DGCaseBookingsSelected}"
              >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Select">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Remove" Command="{Binding RemoveFrom}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Fac ID #" Binding="{Binding FacilityIDNum}"/>
                <DataGridTextColumn Header="OP Case #" Binding="{Binding CaseBookingNum}"/>
                <DataGridTextColumn Header="Booking Type #" Binding="{Binding BookingTypeNum}"/>
                <DataGridTextColumn Header="Booking Type" Binding="{Binding BookingType}"/>
            </DataGrid.Columns>
        </DataGrid>

VIEWMODEL

    private ObservableCollection<DGCaseBookings> _dgCaseBookingsList;
    private ObservableCollection<DGCaseBookings> _dgSelectedCaseBookings;
    private ObservableCollection<DGCaseBookings> _dgCaseBookingsSelected;

    public ObservableCollection<DGCaseBookings> DGCaseBookingsList
    {
        get { return _dgCaseBookingsList; }
        set
        {
            SetProperty(ref _dgCaseBookingsList, value, () => DGCaseBookingsList);
        }
    }

    public ObservableCollection<DGCaseBookings> DGSelectedCaseBookings
    {
        get { return _dgSelectedCaseBookings; }
        set
        {
            SetProperty(ref _dgSelectedCaseBookings, value, () => DGSelectedCaseBookings);
        }
    }

    public ObservableCollection<DGCaseBookings> DGCaseBookingsSelected
    {
        get { return _dgCaseBookingsSelected; }
        set
        {
            SetProperty(ref _dgCaseBookingsSelected, value, () => DGCaseBookingsSelected);
        }
    }

    public CMBookingSelectVM() : base()
    {
        DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
        DGCaseBookingsSelected = new ObservableCollection<DGCaseBookings>();
    }

    private void fillDGCaseBookingswithFacility()
    {
        using (MySqlConnection con = new MySqlConnection(dbConnectionString))
        {
            DGCaseBookingsList = new ObservableCollection<DGCaseBookings>();
            con.Open();
            string Query = ///SELECT STATEMENT WORKS FINE///
            MySqlCommand createCommand = new MySqlCommand(Query, con);
            MySqlDataReader dr = createCommand.ExecuteReader();
            int count = 1;
            while (dr.Read())
            {
                int FacilityIDNum = dr.GetInt32(0);
                int CaseBookingNum = dr.GetInt32(1);
                int BookingTypeNum = dr.GetInt32(2);
                string BookingType = dr.GetString(3);
                DGCaseBookings dgcb = new DGCaseBookings(count, FacilityIDNum, CaseBookingNum, BookingTypeNum, BookingType);
                DGCaseBookingsList.Add(dgcb);
                count++;
            }
            con.Close();
        }
    }

    public void AddTo(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsSelected.Add(dgcb);
            DGCaseBookingsList.Remove(dgcb);
        }
    }

    public void RemoveFrom(DGCaseBookings dgcb)
    {
        if (dgcb != null)
        {
            DGCaseBookingsList.Add(dgcb);
            DGCaseBookingsSelected.Remove(dgcb);
        }
    }

Body:
In background of this you can setup the event when you click on button and add the current row (like param of the event). Take the current row select it from the datasource/ObservableCollection and add it in another dataset e.g  _dgSelectedCaseBookings.

After that you can refresh the new _dgSelectedCaseBookings on UI.


问:
HTML Table with curved linked heading

I'm trying to achieve this type of table so that I can have extended labels for columns. But I don't even know what it's called to try and describe it in a search.

Edit
I can find how to round html borders with CSS. But that doesn't help with linking rows to columns. I can rotate the column header text, but again, that isn't what I'm after.

The closest thing I can come up with is a full table with borders or a background colour to highlight the connection, but this would be squared instead of rounded.

I'm wondering if there is a method of achieving this with css. Or alternatively a library which would do the same thing.

答:
I have never heard about something like this. In general, you cannot curve any element like that, supposing that link is normal part of table (tr/td).

I have created some small thing here, making the curvers, than you can add it over your table to make that feeling, but note, that you cannot write inside it, and most umportantly, it will not work, as this will not look precise across browsers and zoom (tested on another projects, where I needed also some circled things)

So you should better design your table in other way.

Anyway, here is a snippet with rounded linked things

.circ, .circ2, .circ3 {
  position:absolute;

  border-radius: 50%;

  display: inline-block;
  background-color: transparent;
  border-top: 1px solid black;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-bottom: 1px solid transparent;
  transform: rotate(45deg);
}

.circ{width: 180px;
  height: 180px; top:0; left:0;}
  .circ2{width: 135px;
  height: 135px; top:23px; left:22px}
  .circ3{width: 80px;
  height: 80px;  top:50px; left:50px;}

  .container{position:absolute; top:20px; left:20px; border:1px dotted black;width:200px; height:200px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

<div class="circ"></div>
<div class="circ2"></div>
<div class="circ3"></div>
</div></code>```

Als read this - this is full list of transforms, that browsers supports:
https://www.w3schools.com/cssref/css3_pr_transform.asp

Title: HTML Table with curved linked heading

Body:
I have never heard about something like this. In general, you cannot curve any element like that, supposing that link is normal part of table (tr/td).

I have created some small thing here, making the curvers, than you can add it over your table to make that feeling, but note, that you cannot write inside it, and most umportantly, it will not work, as this will not look precise across browsers and zoom (tested on another projects, where I needed also some circled things)

So you should better design your table in other way.

Anyway, here is a snippet with rounded linked things

.circ, .circ2, .circ3 {
  position:absolute;

  border-radius: 50%;

  display: inline-block;
  background-color: transparent;
  border-top: 1px solid black;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-bottom: 1px solid transparent;
  transform: rotate(45deg);
}

.circ{width: 180px;
  height: 180px; top:0; left:0;}
  .circ2{width: 135px;
  height: 135px; top:23px; left:22px}
  .circ3{width: 80px;
  height: 80px;  top:50px; left:50px;}

  .container{position:absolute; top:20px; left:20px; border:1px dotted black;width:200px; height:200px;}

<div class="container">

<div class="circ"></div>
<div class="circ2"></div>
<div class="circ3"></div>
</div>

Als read this - this is full list of transforms, that browsers supports:
https://www.w3schools.com/cssref/css3_pr_transform.asp


问:
Best way handle result from thread on UI
I want to save data to DB in new Thread and after that show toast on the UI.

Method for saving:

```<code>public void addToBasket(String text) {

        new Thread(() -> {

                //emulate save
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              //after that I need say ti UI thread - show Toast!
        }).start();
    }
</code>```

I call this method:

```<code>BasketService.me().addToBasket(result.getContents());
</code>```

I do now want use AsyncTask for this. Please tell me the best way to implement such tasks

答:
batter to use:

```<code>runOnUiThread(new Runnable() {
                public void run() {
                //Do what ever you want do man
            }
        });
</code>```

runOnUiThread() method to manipulate your UserInterface from background threads.

Body:
I want to save data to DB in new Thread and after that show toast on the UI.

Method for saving:

public void addToBasket(String text) {

        new Thread(() -> {

                //emulate save
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              //after that I need say ti UI thread - show Toast!
        }).start();
    }

I call this method:

BasketService.me().addToBasket(result.getContents());

I do now want use AsyncTask for this. Please tell me the best way to implement such tasks

Body:
batter to use:

runOnUiThread(new Runnable() {
                public void run() {
                //Do what ever you want do man
            }
        });

runOnUiThread() method to manipulate your UserInterface from background threads.


问:
Insert data into database using JSP
I have displayed data from a database table and in each row i have put check box and here user will check products and at the end of the press of save button whereas data should be inserted to another table in database using JSP.

How can i do this?

My JSP code:

```<code><%
pds=new Products();
for(int i=0;i<listpds.size();i++){

pds=(Products)listpds.get(i);
%>

<TR>

<TD><%=pds.getP_id()%></TD>
<TD><%=pds.getP_name()%></TD>
<TD><%=pds.getP_details()%></TD>
<TD><%=pds.getP_price()%></TD>

<TD><input type="checkbox" name="product" value="Bike"> Select </TD>
</TR>

<% } %>
</code>```

答:
I prefer using ORM frameworks such as spring data, hibernate, etc. I sharing primitive technique for starting point below:</p>

```<code>import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/mydb?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false");
dataSource.setUsername("root");
dataSource.setPassword("pass");
JdbcTemplate jdbc = new JdbcTemplate(dataSource)
jdbc.execute("INSERT INTO mytable (field1, field2) VALUES ('stringvalue',integervalue)");
</code>```

Title: Insert data into database using JSP

Body:
I have displayed data from a database table and in each row i have put check box and here user will check products and at the end of the press of save button whereas data should be inserted to another table in database using JSP.

How can i do this?

My JSP code:

<%
pds=new Products();
for(int i=0;i<listpds.size();i++){

pds=(Products)listpds.get(i);
%>

<%=pds.getP_id()%>
<%=pds.getP_name()%>
<%=pds.getP_details()%>
<%=pds.getP_price()%>

<input type="checkbox" name="product" value="Bike"> Select

<% } %>

Body:
I prefer using ORM frameworks such as spring data, hibernate, etc. I sharing primitive technique for starting point below:

import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/mydb?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false");
dataSource.setUsername("root");
dataSource.setPassword("pass");
JdbcTemplate jdbc = new JdbcTemplate(dataSource)
jdbc.execute("INSERT INTO mytable (field1, field2) VALUES ('stringvalue',integervalue)");


问:
Change zoom on map update (JS)
I have function for map updating

Here is  code

```<code>function update() {

            ajaxLoader.removeClass('mc-warning-noConnection');
            ajaxLoader.show();

            $.ajax({
                url: '/Mobile/Map/GetMapData',
                type: 'GET',
                timeout: 10000,
                success: function (data) {
                    if (data.redirectUrl) window.location.replace(data.redirectUrl);
                    else if (data.error) alert(data.error);
                    else {
                        setTimeout(function () { ajaxLoader.hide() }, 300);
                        data.forEach(function (vehicleData) {
                            mapWrapper.getEntity(vehicleData.Imei).update(vehicleData);
                        });
                    }
                },
                error: function () {
                    ajaxLoader.addClass('mc-warning-noConnection');
                },
                complete: function () {
                    timeout = setTimeout(update, 10000);
                }
            });
        }
</code>```

It need to get values from db via controller

Here is controller code.

```<code> public async Task<ActionResult> GetMapData()
    {
        var mapData = await repository.GetVehicleMapData(15, null).ConfigureAwait(false);
        Session["PreviousMapQueryTime"] = DateTime.Now.AddMinutes(-5); //5 minutes offset because tables aren't always up-to-date

        return CreateJsonDataResult(mapData);
    }
</code>```

And than pass them to map and update markers.

Here is MapWrapper script

MapWrapper

With markers all okay, but zoom when updating not works.

When I reload map all okay. But not from updating without reloading whole page.

Where is problem and how I can fix it?

答:
You should use mapWrapper.zoomToLayer(layerID) function after update entities, where Layerid is ID of layer where your entities placed.

```<code>success: function (data) {
                    if (data.redirectUrl) window.location.replace(data.redirectUrl);
                    else if (data.error) alert(data.error);
                    else {
                        setTimeout(function () { ajaxLoader.hide() }, 300);
                        data.forEach(function (vehicleData) {
                            mapWrapper.getEntity(vehicleData.Imei).update(vehicleData);
                        });
                          mapWrapper.zoomToLayer(layerID);
                    }
                },
</code>```

Title: Change zoom on map update (JS)

Body:
I have function for map updating

Here is  code

function update() {

            ajaxLoader.removeClass('mc-warning-noConnection');
            ajaxLoader.show();

            $.ajax({
                url: '/Mobile/Map/GetMapData',
                type: 'GET',
                timeout: 10000,
                success: function (data) {
                    if (data.redirectUrl) window.location.replace(data.redirectUrl);
                    else if (data.error) alert(data.error);
                    else {
                        setTimeout(function () { ajaxLoader.hide() }, 300);
                        data.forEach(function (vehicleData) {
                            mapWrapper.getEntity(vehicleData.Imei).update(vehicleData);
                        });
                    }
                },
                error: function () {
                    ajaxLoader.addClass('mc-warning-noConnection');
                },
                complete: function () {
                    timeout = setTimeout(update, 10000);
                }
            });
        }

It need to get values from db via controller

Here is controller code.

 public async Task<ActionResult> GetMapData()
    {
        var mapData = await repository.GetVehicleMapData(15, null).ConfigureAwait(false);
        Session["PreviousMapQueryTime"] = DateTime.Now.AddMinutes(-5); //5 minutes offset because tables aren't always up-to-date

        return CreateJsonDataResult(mapData);
    }

And than pass them to map and update markers.

Here is MapWrapper script

MapWrapper

With markers all okay, but zoom when updating not works.

When I reload map all okay. But not from updating without reloading whole page.

Where is problem and how I can fix it?

Body:
You should use mapWrapper.zoomToLayer(layerID) function after update entities, where Layerid is ID of layer where your entities placed.

success: function (data) {
                    if (data.redirectUrl) window.location.replace(data.redirectUrl);
                    else if (data.error) alert(data.error);
                    else {
                        setTimeout(function () { ajaxLoader.hide() }, 300);
                        data.forEach(function (vehicleData) {
                            mapWrapper.getEntity(vehicleData.Imei).update(vehicleData);
                        });
                          mapWrapper.zoomToLayer(layerID);
                    }
                },


问:
Cannot read certain block transactions
I was playing with the blochain using the python librairy 'bitcoinrpc' and bitcoin-core, however I can never read the transaction in block 9.

I even downloaded the blockchain a 2nd time thinking mine had a problem with a 2nd installation of bitcoin-core pointing to a different data directory and I still can't read block 9.

Can you reproduce this problem? Any idea why?

Script for reading and displaying block 7, 8, 9, 10 :

```<code>from bitcoinrpc.authproxy import AuthServiceProxy
import traceback

RPC_ADDRESS="127.0.0.1:8332"
RPC_USER="u"
RPC_PASSWORD="p"

def display_block_info(rpc, block_number):
    print "-------- block {} start -------".format(block_number)
    block_hash = rpc.getblockhash(block_number)
    print "Block hash : " + block_hash
    block = rpc.getblock(block_hash)
    for tx in block[u'tx']:
        print "processing transaction " + tx
        print rpc.getrawtransaction(tx, True)
    print "-------- block {} end -------".format(block_number)
    print ""

if __name__ == "__main__":
    rpc = AuthServiceProxy("http://%s:%s@%s"%(RPC_USER, RPC_PASSWORD, RPC_ADDRESS))
    block_numbers = [7, 8, 9, 10]
    for block_number in block_numbers:
        try:
            display_block_info(rpc, block_number)
        except Exception as e:
            traceback.print_exc()
            print "-------- block {} end -------".format(block_number)
            print ""
</code>```

Result:

```<code>-------- block 7 start -------
Block hash : 0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444
processing transaction 8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f
{u'hash': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blockhash': u'0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac', u'addresses': [u'16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM'], u'asm': u'04a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555 OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d012bffffffff0100f2052a01000000434104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac00000000', u'vin': [{u'coinbase': u'04ffff001d012b', u'sequence': 4294967295L}], u'txid': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blocktime': 1231472369, u'version': 1, u'confirmations': 3677, u'time': 1231472369, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 7 end -------

-------- block 8 start -------
Block hash : 00000000408c48f847aa786c2268fc3e6ec2af68e8468a34a28c61b7f1de0dc6
processing transaction a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3
{u'hash': u'a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3', u'blockhash': u'00000000408c48f847aa786c2268fc3e6ec2af68e8468a34a28c61b7f1de0dc6', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1ac', u'addresses': [u'1J6PYEzr4CUoGbnXrELyHszoTSz3wCsCaj'], u'asm': u'04cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1 OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d012cffffffff0100f2052a01000000434104cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1ac00000000', u'vin': [{u'coinbase': u'04ffff001d012c', u'sequence': 4294967295L}], u'txid': u'a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3', u'blocktime': 1231472743, u'version': 1, u'confirmations': 3681, u'time': 1231472743, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 8 end -------

-------- block 9 start -------
Block hash : 000000008d9dc510f23c2657fc4f67bea30078cc05a90eb89e84cc475c080805
processing transaction 0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9
Traceback (most recent call last):
  File "blocReader.py", line 24, in <module>
    display_block_info(rpc, block_number)
  File "blocReader.py", line 15, in display_block_info
    print rpc.getrawtransaction(tx, True)
  File "c:\Python27\lib\site-packages\bitcoinrpc\authproxy.py", line 116, in __call__
    raise JSONRPCException(response['error'])
JSONRPCException
-------- block 9 end -------

-------- block 10 start -------
Block hash : 000000002c05cc2e78923c34df87fd108b22221ac6076c18f3ade378a4d915e9
processing transaction d3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11
{u'hash': u'd3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11', u'blockhash': u'000000002c05cc2e78923c34df87fd108b22221ac6076c18f3ade378a4d915e9', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425ddac', u'addresses': [u'15yN7NPEpu82sHhB6TzCW5z5aXoamiKeGy'], u'asm': u'04fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425dd OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0136ffffffff0100f2052a01000000434104fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425ddac00000000', u'vin': [{u'coinbase': u'04ffff001d0136', u'sequence': 4294967295L}], u'txid': u'd3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11', u'blocktime': 1231473952, u'version': 1, u'confirmations': 3687, u'time': 1231473952, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 10 end -------
</code>```

As you can see the transaction '0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9' cannot be read using rpc.getrawtransaction(tx, True)

答:
The issue is most likely due to the fact that you are running bitcoind without the -txindex command line flag. Without it bitcoind will only track unspent transaction outputs and transactions that it received. The reason why the first few blocks work, is because they only contain unspent genesis outputs, i.e., newly generated coins. The transaction you are failing to parse is the first ever transaction from Satoshi to Hal Finney, which was spent, hence no longer in the index.

Try either running with -txindex or better use getblock(block_hash, 0) to get the hex serialized block and then parse it locally (e.g., with bitcoinlib), instead of using bitcoind to retrieve every single transaction. You'll be a lot faster this way.

Title: Cannot read certain block transactions

Body:
I was playing with the blochain using the python librairy 'bitcoinrpc' and bitcoin-core, however I can never read the transaction in block 9.

I even downloaded the blockchain a 2nd time thinking mine had a problem with a 2nd installation of bitcoin-core pointing to a different data directory and I still can't read block 9.

Can you reproduce this problem? Any idea why?

Script for reading and displaying block 7, 8, 9, 10 :

from bitcoinrpc.authproxy import AuthServiceProxy
import traceback

RPC_ADDRESS="127.0.0.1:8332"
RPC_USER="u"
RPC_PASSWORD="p"

def display_block_info(rpc, block_number):
    print "-------- block {} start -------".format(block_number)
    block_hash = rpc.getblockhash(block_number)
    print "Block hash : " + block_hash
    block = rpc.getblock(block_hash)
    for tx in block[u'tx']:
        print "processing transaction " + tx
        print rpc.getrawtransaction(tx, True)
    print "-------- block {} end -------".format(block_number)
    print ""

if __name__ == "__main__":
    rpc = AuthServiceProxy("http://%s:%s@%s"%(RPC_USER, RPC_PASSWORD, RPC_ADDRESS))
    block_numbers = [7, 8, 9, 10]
    for block_number in block_numbers:
        try:
            display_block_info(rpc, block_number)
        except Exception as e:
            traceback.print_exc()
            print "-------- block {} end -------".format(block_number)
            print ""

Result:

-------- block 7 start -------
Block hash : 0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444
processing transaction 8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f
{u'hash': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blockhash': u'0000000071966c2b1d065fd446b1e485b2c9d9594acd2007ccbd5441cfc89444', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac', u'addresses': [u'16LoW7y83wtawMg5XmT4M3Q7EdjjUmenjM'], u'asm': u'04a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555 OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d012bffffffff0100f2052a01000000434104a59e64c774923d003fae7491b2a7f75d6b7aa3f35606a8ff1cf06cd3317d16a41aa16928b1df1f631f31f28c7da35d4edad3603adb2338c4d4dd268f31530555ac00000000', u'vin': [{u'coinbase': u'04ffff001d012b', u'sequence': 4294967295L}], u'txid': u'8aa673bc752f2851fd645d6a0a92917e967083007d9c1684f9423b100540673f', u'blocktime': 1231472369, u'version': 1, u'confirmations': 3677, u'time': 1231472369, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 7 end -------

-------- block 8 start -------
Block hash : 00000000408c48f847aa786c2268fc3e6ec2af68e8468a34a28c61b7f1de0dc6
processing transaction a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3
{u'hash': u'a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3', u'blockhash': u'00000000408c48f847aa786c2268fc3e6ec2af68e8468a34a28c61b7f1de0dc6', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1ac', u'addresses': [u'1J6PYEzr4CUoGbnXrELyHszoTSz3wCsCaj'], u'asm': u'04cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1 OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d012cffffffff0100f2052a01000000434104cc8d85f5e7933cb18f13b97d165e1189c1fb3e9c98b0dd5446b2a1989883ff9e740a8a75da99cc59a21016caf7a7afd3e4e9e7952983e18d1ff70529d62e0ba1ac00000000', u'vin': [{u'coinbase': u'04ffff001d012c', u'sequence': 4294967295L}], u'txid': u'a6f7f1c0dad0f2eb6b13c4f33de664b1b0e9f22efad5994a6d5b6086d85e85e3', u'blocktime': 1231472743, u'version': 1, u'confirmations': 3681, u'time': 1231472743, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 8 end -------

-------- block 9 start -------
Block hash : 000000008d9dc510f23c2657fc4f67bea30078cc05a90eb89e84cc475c080805
processing transaction 0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9
Traceback (most recent call last):
  File "blocReader.py", line 24, in <module>
    display_block_info(rpc, block_number)
  File "blocReader.py", line 15, in display_block_info
    print rpc.getrawtransaction(tx, True)
  File "c:\Python27\lib\site-packages\bitcoinrpc\authproxy.py", line 116, in __call__
    raise JSONRPCException(response['error'])
JSONRPCException
-------- block 9 end -------

-------- block 10 start -------
Block hash : 000000002c05cc2e78923c34df87fd108b22221ac6076c18f3ade378a4d915e9
processing transaction d3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11
{u'hash': u'd3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11', u'blockhash': u'000000002c05cc2e78923c34df87fd108b22221ac6076c18f3ade378a4d915e9', u'vout': [{u'scriptPubKey': {u'reqSigs': 1, u'hex': u'4104fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425ddac', u'addresses': [u'15yN7NPEpu82sHhB6TzCW5z5aXoamiKeGy'], u'asm': u'04fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425dd OP_CHECKSIG', u'type': u'pubkey'}, u'value': Decimal('50.00000000'), u'n': 0}], u'hex': u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0136ffffffff0100f2052a01000000434104fcc2888ca91cf0103d8c5797c256bf976e81f280205d002d85b9b622ed1a6f820866c7b5fe12285cfa78c035355d752fc94a398b67597dc4fbb5b386816425ddac00000000', u'vin': [{u'coinbase': u'04ffff001d0136', u'sequence': 4294967295L}], u'txid': u'd3ad39fa52a89997ac7381c95eeffeaf40b66af7a57e9eba144be0a175a12b11', u'blocktime': 1231473952, u'version': 1, u'confirmations': 3687, u'time': 1231473952, u'locktime': 0, u'vsize': 134, u'size': 134}
-------- block 10 end -------

As you can see the transaction '0437cd7f8525ceed2324359c2d0ba26006d92d856a9c20fa0241106ee5a597c9' cannot be read using rpc.getrawtransaction(tx, True)


问:
Confused! What are the differences between code first and code only?
I'm kind of confusing about these two term. Could someone have a bit explain these terms?

I know the one is like, that we define our POCO classes, and then create a class that has a set of DbSet which inherited from DbContext.

答: Code-only development and code-first development are the same thing, both are utilizing Entity Framework without a physical EDMX file, everything is handled in code.</p>


问:
Activity Lifecycle. When application already opened (Collapsed) is closing and starting again on icon click?
Can you please explain to me why my activity which is currently (onStop) is go to OnDestroy event and restarting again after clicking on the app icon in the interface.
Because of that i have problem with user data saving. I'm using event OnDestroy to ask user if he want to save the data. Because of my misunderstanding when i collapse the app and click to it again i am waiting to my activity to have all the data in it but instead  i see saving dialog from the previous activity whiсh goes to onDestroy event.
Other apps don't act like this.
What should i check?

答:
Your description is not very clear, so my answer may not help you.

Research the app life cycle here: https://developer.android.com/guide/components/activities/activity-lifecycle.html

Your app will enter onStop is before onDestroy. This can happen if user activates another app. (So the user may no longer see any prompts that you display e.g. To ask to save or not.) Android may choose to destroy your app based on its rules after that point, even if the user clicks on the app icon to start it again.

Perhaps you can test what happens if the user switches back to the app (not clicking the icon), but use the "Recent apps" button and select it.


问:
Mysql Stored procedure table variable, incorrect syntax error
I want to create a stored procedure in mysql. but when creating getting error like  incorrect syntax error near DECLARE @TableVar my code below

```<code>CREATE PROCEDURE `testproc`()
BEGIN
DECLARE @TableVar TABLE
(Col1 VARCHAR(100),
Col2 VARCHAR(100),
Col3 VARCHAR(100),
Col4 VARCHAR(100),
Col5 VARCHAR(100),
Col6 VARCHAR(100),
Col7 VARCHAR(100),
Col8 VARCHAR(100),
Col9 VARCHAR(100));

  FOR v_row AS SELECT art_no as Article,barcode as Barcode,i.item_name,b.brand_name,s.size_name,sd.quantity,mrp,mlp,si.received_date,si.gino,si.inv_no,sd.brand_supplier_id,bs.name as party_name FROM stock_inward_details sd left join stock_inward si on sd.inv_id=si.id left join items i on i.id=sd.item_id left join size s on sd.size_id=s.id left join brands b on sd.brand_id=b.id left join brand_supplier bs on sd.brand_supplier_id=bs.id where si.received_date<='2017-11-30'  order by si.id
    DO
      INSERT INTO @TableVar VALUES (Article,Barcode,item_name,brand_name,size_name,quantity,mrp,gino,party_name);
    END FOR
     SELECT *
FROM @TableVar
END
</code>```

Please help me to clear this issue.

答:
If your query is working then,

Try this:

```<code>CREATE PROCEDURE testproc()

BEGIN

    DECLARE done INT DEFAULT FALSE;
    Declare Article_var VARCHAR(100);
    Declare Barcode_var VARCHAR(100);
    Declare item_name_var VARCHAR(100);
    Declare brand_name_var VARCHAR(100);
    Declare size_name_var VARCHAR(100);
    Declare quantity_var VARCHAR(100);
    Declare mrp_var VARCHAR(100);
    Declare gino_var VARCHAR(100);
    Declare party_name_var VARCHAR(100);

    DECLARE  dec_cur  CURSOR FOR SELECT art_no as Article,barcode as Barcode,i.item_name,b.brand_name,s.size_name,sd.quantity,mrp,mlp,si.received_date,si.gino,si.inv_no,sd.brand_supplier_id,bs.name as party_name FROM stock_inward_details sd left join stock_inward si on sd.inv_id=si.id left join items i on i.id=sd.item_id left join size s on sd.size_id=s.id left join brands b on sd.brand_id=b.id left join brand_supplier bs on sd.brand_supplier_id=bs.id where si.received_date<='2017-11-30'  order by si.id;

    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

    create TEMPORARY table temp_temptable( Col1 VARCHAR(100),Col2 VARCHAR(100),Col3 VARCHAR(100),Col4 VARCHAR(100),Col5 VARCHAR(100),Col6 VARCHAR(100),Col7 VARCHAR(100),Col8 VARCHAR(100),Col9 VARCHAR(100));

    OPEN dec_cur;

    REPEAT

    FETCH dec_cur INTO Article_var,Barcode_var,item_name_var,brand_name_var,size_name_var,quantity_var,mrp_var,gino_var,party_name_var;

                    insert into temp_temptable (Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9) values(Article_var,Barcode_var,item_name_var,brand_name_var,size_name_var,quantity_var,mrp_var,gino_var,party_name_var);

    UNTIL done END REPEAT;

    select * from temp_temptable;

    drop temporary table if exists temp_temptable;
    CLOSE  dec_cur;

END
</code>```

Make sure your query is working first before you proceed to this SP.

Body:
I want to create a stored procedure in mysql. but when creating getting error like  incorrect syntax error near DECLARE @TableVar my code below

CREATE PROCEDURE `testproc`()
BEGIN
DECLARE @TableVar TABLE
(Col1 VARCHAR(100),
Col2 VARCHAR(100),
Col3 VARCHAR(100),
Col4 VARCHAR(100),
Col5 VARCHAR(100),
Col6 VARCHAR(100),
Col7 VARCHAR(100),
Col8 VARCHAR(100),
Col9 VARCHAR(100));

  FOR v_row AS SELECT art_no as Article,barcode as Barcode,i.item_name,b.brand_name,s.size_name,sd.quantity,mrp,mlp,si.received_date,si.gino,si.inv_no,sd.brand_supplier_id,bs.name as party_name FROM stock_inward_details sd left join stock_inward si on sd.inv_id=si.id left join items i on i.id=sd.item_id left join size s on sd.size_id=s.id left join brands b on sd.brand_id=b.id left join brand_supplier bs on sd.brand_supplier_id=bs.id where si.received_date<='2017-11-30'  order by si.id
    DO
      INSERT INTO @TableVar VALUES (Article,Barcode,item_name,brand_name,size_name,quantity,mrp,gino,party_name);
    END FOR
     SELECT *
FROM @TableVar
END

Please help me to clear this issue.

Body:
If your query is working then,

Try this:

CREATE PROCEDURE testproc()

BEGIN

    DECLARE done INT DEFAULT FALSE;
    Declare Article_var VARCHAR(100);
    Declare Barcode_var VARCHAR(100);
    Declare item_name_var VARCHAR(100);
    Declare brand_name_var VARCHAR(100);
    Declare size_name_var VARCHAR(100);
    Declare quantity_var VARCHAR(100);
    Declare mrp_var VARCHAR(100);
    Declare gino_var VARCHAR(100);
    Declare party_name_var VARCHAR(100);

    DECLARE  dec_cur  CURSOR FOR SELECT art_no as Article,barcode as Barcode,i.item_name,b.brand_name,s.size_name,sd.quantity,mrp,mlp,si.received_date,si.gino,si.inv_no,sd.brand_supplier_id,bs.name as party_name FROM stock_inward_details sd left join stock_inward si on sd.inv_id=si.id left join items i on i.id=sd.item_id left join size s on sd.size_id=s.id left join brands b on sd.brand_id=b.id left join brand_supplier bs on sd.brand_supplier_id=bs.id where si.received_date<='2017-11-30'  order by si.id;

    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

    create TEMPORARY table temp_temptable( Col1 VARCHAR(100),Col2 VARCHAR(100),Col3 VARCHAR(100),Col4 VARCHAR(100),Col5 VARCHAR(100),Col6 VARCHAR(100),Col7 VARCHAR(100),Col8 VARCHAR(100),Col9 VARCHAR(100));

    OPEN dec_cur;

    REPEAT

    FETCH dec_cur INTO Article_var,Barcode_var,item_name_var,brand_name_var,size_name_var,quantity_var,mrp_var,gino_var,party_name_var;

                    insert into temp_temptable (Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9) values(Article_var,Barcode_var,item_name_var,brand_name_var,size_name_var,quantity_var,mrp_var,gino_var,party_name_var);

    UNTIL done END REPEAT;

    select * from temp_temptable;

    drop temporary table if exists temp_temptable;
    CLOSE  dec_cur;

END

Make sure your query is working first before you proceed to this SP.


问:
How to get selected option value in protractor
How can I get currently selected option value of selectbox?

I have tried below code but it's not working.

```<code>element(by.css('#selectbox')).all(by.tagName('option')).then(function (options) {
    options.forEach(option => {
        if (option.getAttribute('selected')) {
            console.log('selected option', option);
        }
    });
});
</code>```

Any help would be appreciated.

答:
Is "selected" and attribute or a class-value?

It would work as "get element, which is selected, then read out its value"

In code:

```<code>//if selected is an attribute
element(by.css('#selectbox option[selected]')).getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

//if selected is a class-attribute
element(by.css('#selectbox option.selected')).getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

//note, that "element(by.css())" === "$()", so this is the same as the first one
$('#selectbox option[selected]').getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})
</code>```

Read more here about locators and even more important here about CSS-Selectors

Body:
How can I get currently selected option value of selectbox?

I have tried below code but it's not working.

element(by.css('#selectbox')).all(by.tagName('option')).then(function (options) {
    options.forEach(option => {
        if (option.getAttribute('selected')) {
            console.log('selected option', option);
        }
    });
});

Any help would be appreciated.

Body:
Is "selected" and attribute or a class-value?

It would work as "get element, which is selected, then read out its value"

In code:

//if selected is an attribute
element(by.css('#selectbox option[selected]')).getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

//if selected is a class-attribute
element(by.css('#selectbox option.selected')).getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

//note, that "element(by.css())" === "$()", so this is the same as the first one
$('#selectbox option[selected]').getAttribute('value').then(function(value){
    console.log('selected option is '+value);
})

Read more here about locators and even more important here about CSS-Selectors


问:
Query for Bulk update in Mysql
Consider the following table(T) in mysql.

```<code>id c1  c2
1  10  100
2  20  200
3  30  300
</code>```

Suppose I want to update "c1" of the row with id=2. I can do the following.

```<code>UPDATE T set col1=20 where id=1;
</code>```

Suppose I want bulk update.

```<code>INSERT INTO T(id,c1) VALUES (1,20),(2,40) ON DUPLICATE KEY UPDATE c1=VALUES(c1);
</code>```

But this will give you an error if default value for "c2" is not set in the SCHEMA.

Is there another way to achieve the task?

答:
The error happens when you INSERT a value for the first time, meaning there's no duplicate key to update. Your c2 column is not nullable and has no default value. To fix this either

make c2 nullable or

provide a default value for c2 or

provide a value for c2 in your insert statement

When you don't want to insert into the table, insert the values into a temporary table, then use an update statement and join the two tables.

Title: Query for Bulk update in Mysql

Body:
Consider the following table(T) in mysql.

id c1  c2
1  10  100
2  20  200
3  30  300

Suppose I want to update "c1" of the row with id=2. I can do the following.

UPDATE T set col1=20 where id=1;

Suppose I want bulk update.

INSERT INTO T(id,c1) VALUES (1,20),(2,40) ON DUPLICATE KEY UPDATE c1=VALUES(c1);

But this will give you an error if default value for "c2" is not set in the SCHEMA.

Is there another way to achieve the task?


问:
How to auto-update multiple sheets in Excel workbook?
I have an Excel workbook with two worksheets - "Upcoming Orders" and "Completed Orders". I used "Upcoming Orders" sheet for upcoming orders, and "Completed Orders" for completed orders.

Once the order is completed, I delete it from "Upcoming Orders" sheet and paste it into "Completed Orders".

Is there a way to automate it by creating a macro that would do it it automatically for me, once I mark order as completed in the "Upcoming Orders" sheet it will be automatically add into the " Completed Orders" sheet.

I went over a few tutorial on macros, but I couldn't find the right method. Please help.

答:
How about double click, With double click on single cell you can copy the row to "Completed Orders" Sheet and delete it from "Upcoming Orders"

Example Workbook.SheetBeforeDoubleClick Event (Excel)

```<code>Option Explicit
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sht As Object, _
                                            ByVal Target As Range, _
                                                  Cancel As Boolean)

    Dim LastRow As Long
    Dim RngCopy As Range
    Dim Target_Sht As Worksheet

    Cancel = True

    Set Target_Sht = Sheets("Completed Orders")

    Set RngCopy = Sht.Range("A" & Target.Row, Sht.Cells _
                           (Target.Row, Sht.UsedRange.Column + _
                            Sht.UsedRange.Columns.Count).Address)

    With Target_Sht
        LastRow = .Cells(Rows.Count, "A").End(xlUp).Row + 1
        RngCopy.Copy Destination:=.Range("A" & LastRow)
        Sht.Rows(Target.Row).Delete
    End With

End Sub
</code>```

Body:
How about double click, With double click on single cell you can copy the row to "Completed Orders" Sheet and delete it from "Upcoming Orders"

Example Workbook.SheetBeforeDoubleClick Event (Excel)

Option Explicit
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sht As Object, _
                                            ByVal Target As Range, _
                                                  Cancel As Boolean)

    Dim LastRow As Long
    Dim RngCopy As Range
    Dim Target_Sht As Worksheet

    Cancel = True

    Set Target_Sht = Sheets("Completed Orders")

    Set RngCopy = Sht.Range("A" & Target.Row, Sht.Cells _
                           (Target.Row, Sht.UsedRange.Column + _
                            Sht.UsedRange.Columns.Count).Address)

    With Target_Sht
        LastRow = .Cells(Rows.Count, "A").End(xlUp).Row + 1
        RngCopy.Copy Destination:=.Range("A" & LastRow)
        Sht.Rows(Target.Row).Delete
    End With

End Sub


问:
multiply two arrays with different size in matlab
I want to call a product of two arrays with different sizes but I get an error. This is the data:

```<code>A = [1 1 1 1;1 2 2 2;1 2 3 3;1 2 3 4];
B = [-4 -7 -9 -10];
X = [5 5 5 5];
</code>```

I want to calculate this :

```<code>C = A*X+B
</code>```

I have this error :

```<code>??? Error using ==> mtimes
Inner matrix dimensions must agree.
</code>```

答:
You need to transpose X and 'B' to get the correct result. Try the following:

```<code>C = A * (X.') + B.';
</code>```

Body:
I want to call a product of two arrays with different sizes but I get an error. This is the data:

A = [1 1 1 1;1 2 2 2;1 2 3 3;1 2 3 4];
B = [-4 -7 -9 -10];
X = [5 5 5 5];

I want to calculate this :

C = A*X+B

I have this error :

??? Error using ==> mtimes
Inner matrix dimensions must agree.

Body:
You need to transpose X and 'B' to get the correct result. Try the following:

C = A * (X.') + B.';


问:
SubGit: use svn.svnCommitMessage option
Just seen this feature in the SubGit 3.2.4 release notes:

Support for svn.gitCommitMessage and svn.svnCommitMessage options that allow specifying message patterns used by SubGit while generating commit messages.

But i cannot find any example on the syntax.
I want to do a one time import, so i guess i run

```<code>subgit configure SVN_REPO repo.git
</code>```

then edit repo.git/subgit/config and add gitCommitMessage to the svn section. But what are the variables/placeholders i can use?

答:
sorry to answer that late.
Now the information is available in the documentation, namely:

the svnCommitMessage option description:

https://subgit.com/config-options.html#svn.svnCommitMessage

available placeholders:

```<code>%author = Git author
%committer = Git committer
%date = Git commit date
%message = original message
%note = Git commit note stored under refs/notes/commits
%note(refs/notes/namespace) = Git commit note stored under
refs/notes/namespace
%commit = Git commit hash
%svnUser = Subversion username
%branch = Subversion branch
\n = newline feed
</code>```

the gitCommitMessage option description:

https://subgit.com/config-options.html#svn.gitCommitMessage

supported placeholders:

```<code>%author = Git author
%committer = Git committer
%date = date of revision
%message = original message
%svnUser = Subversion username
%revision = Subversion revision, GRN in your notation
%branch = Subversion branch
\n = newline feed
</code>```

Title: SubGit: use svn.svnCommitMessage option

Body:
Just seen this feature in the SubGit 3.2.4 release notes:

Support for svn.gitCommitMessage and svn.svnCommitMessage options that allow specifying message patterns used by SubGit while generating commit messages.

But i cannot find any example on the syntax.
I want to do a one time import, so i guess i run

subgit configure SVN_REPO repo.git

then edit repo.git/subgit/config and add gitCommitMessage to the svn section. But what are the variables/placeholders i can use?

Body:
sorry to answer that late.
Now the information is available in the documentation, namely:

the svnCommitMessage option description:

https://subgit.com/config-options.html#svn.svnCommitMessage

available placeholders:

%author = Git author
%committer = Git committer
%date = Git commit date
%message = original message
%note = Git commit note stored under refs/notes/commits
%note(refs/notes/namespace) = Git commit note stored under
refs/notes/namespace
%commit = Git commit hash
%svnUser = Subversion username
%branch = Subversion branch
\n = newline feed

the gitCommitMessage option description:

https://subgit.com/config-options.html#svn.gitCommitMessage

supported placeholders:

%author = Git author
%committer = Git committer
%date = date of revision
%message = original message
%svnUser = Subversion username
%revision = Subversion revision, GRN in your notation
%branch = Subversion branch
\n = newline feed


问:
How to mock a method inside an object in a directive
Given the following directive:

This will load a simple html template with 2 buttons to call the goTo function with diferent arguments.

```<code>function simpleMenu() {
    return {
        scope: {
            state: '='
        },
        controller: Controller,
        controllerAs: 'vm',
    };
}

function Controller($scope, $state) {
        var vm = this;
        var options = optionsService.options;
        function goTo(state) {
            switch (state){
                case 'video':
                    return $state.go('app.video');
                case 'chat':
                    return $state.go('app.chat');
            }
        }

    }
</code>```

I want to make a test that ensure $state is being called when the goTo function is executed.

My test uses the directiveElement to save a compiled angular element and the directiveScope to get the scope of that element :

```<code>var directiveElem, compile, scope, directiveScope, $state;
$state = {
    go: jasmine.createSpy().and.returnValue('asd')
};
beforeEach(function() {
    bard.inject('$timeout', '$state');
    inject(function($compile, $rootScope, $httpBackend, $state) {
        compile = $compile;
        scope = $rootScope.$new();
        $state =  $state;
    });
});
beforeEach(function() {
    directiveElem = getCompiledElement();
});

function getCompiledElement() {
    var element = angular.element('<simpleMenu></simpleMenu>');
    var compiledElement = compile(element)(scope);
    scope.$digest();
    directiveScope = element.isolateScope();
    //Here is where I suposedly inject the mocked $state
    directiveScope.$state = $state;
    return compiledElement;
}
it('should increment value on click of button', function () {
    var output = directiveScope.vm.goTo('video-specialties');
    expect($state.go).toHaveBeenCalled();
});
</code>```

The last test is returning:

Expected spy unknown to have been called.

It seems $scope is getting the correct mocked value in the directiveScope but when the return $state.go is executed it takes the $state item from some other place, maybe it is being injected by the simpleMenu()? How can i mock this object to spy it?

答:
The solution to this problem was that, Bard.js was injecting the real object into the execution, so my mock was overwritten every test. The syntax that allows to inject a mocked object is:</p>

```<code>    beforeEach(module(function ($provide) {
        $provide.value('$state', $state);
    })
</code>```

Body:
Given the following directive:

This will load a simple html template with 2 buttons to call the goTo function with diferent arguments.

function simpleMenu() {
    return {
        scope: {
            state: '='
        },
        controller: Controller,
        controllerAs: 'vm',
    };
}

function Controller($scope, $state) {
        var vm = this;
        var options = optionsService.options;
        function goTo(state) {
            switch (state){
                case 'video':
                    return $state.go('app.video');
                case 'chat':
                    return $state.go('app.chat');
            }
        }

    }

I want to make a test that ensure $state is being called when the goTo function is executed.

My test uses the directiveElement to save a compiled angular element and the directiveScope to get the scope of that element :

var directiveElem, compile, scope, directiveScope, $state;
$state = {
    go: jasmine.createSpy().and.returnValue('asd')
};
beforeEach(function() {
    bard.inject('$timeout', '$state');
    inject(function($compile, $rootScope, $httpBackend, $state) {
        compile = $compile;
        scope = $rootScope.$new();
        $state =  $state;
    });
});
beforeEach(function() {
    directiveElem = getCompiledElement();
});

function getCompiledElement() {
    var element = angular.element('<simpleMenu></simpleMenu>');
    var compiledElement = compile(element)(scope);
    scope.$digest();
    directiveScope = element.isolateScope();
    //Here is where I suposedly inject the mocked $state
    directiveScope.$state = $state;
    return compiledElement;
}
it('should increment value on click of button', function () {
    var output = directiveScope.vm.goTo('video-specialties');
    expect($state.go).toHaveBeenCalled();
});

The last test is returning:

Expected spy unknown to have been called.

It seems $scope is getting the correct mocked value in the directiveScope but when the return $state.go is executed it takes the $state item from some other place, maybe it is being injected by the simpleMenu()? How can i mock this object to spy it?

Body:
The solution to this problem was that, Bard.js was injecting the real object into the execution, so my mock was overwritten every test. The syntax that allows to inject a mocked object is:

    beforeEach(module(function ($provide) {
        $provide.value('$state', $state);
    })


问:
Get short claim type name
I am using Asp.Net Core and ASP.NET Identity and when I get a Claim type I get something like

```<code>"type":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
"value":"123"
</code>```

How to get only the simple type name, e.g.:

```<code>"type":"nameidentifier",
"value":"123"
</code>```

I know this is possible I just can't find the solution.

答:
I was looking for this answer when I came across this documentation:

When you inspect the claims on the about page, you will notice two things: some claims have odd long type names and there are more claims than you probably need in your application.

The long claim names come from Microsoft’s JWT handler trying to map some claim types to .NET’s ClaimTypes class types. You can turn off this behavior with the following line of code (in Startup).

This also means that you need to adjust the configuration for anti-CSRF protection to the new unique sub claim type:

```<code>AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
</code>```

I added this code to the Startup.cs of my client and it shortened the claimtypes.

Update:

For newer versions of IdentityModel, the property is called DefaultInboundClaimTypeMap:

```<code>JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
</code>```

Make sure you run this line before you set up your Identity configuration.

Title: Get short claim type name

Body:
I am using Asp.Net Core and ASP.NET Identity and when I get a Claim type I get something like

"type":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
"value":"123"

How to get only the simple type name, e.g.:

"type":"nameidentifier",
"value":"123"

I know this is possible I just can't find the solution.

Body:
I was looking for this answer when I came across this documentation:

When you inspect the claims on the about page, you will notice two things: some claims have odd long type names and there are more claims than you probably need in your application.

The long claim names come from Microsoft’s JWT handler trying to map some claim types to .NET’s ClaimTypes class types. You can turn off this behavior with the following line of code (in Startup).

This also means that you need to adjust the configuration for anti-CSRF protection to the new unique sub claim type:

AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

I added this code to the Startup.cs of my client and it shortened the claimtypes.

Update:

For newer versions of IdentityModel, the property is called DefaultInboundClaimTypeMap:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

Make sure you run this line before you set up your Identity configuration.


问:
Scala List function for grouping consecutive identical elements
Given e.g.:

```<code>List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
</code>```

I'd like to get to:

```<code>List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))
</code>```

I would assume there is a simple List function that does this, but am unable to find it.

答:
```<code>list.foldRight(List[List[Int]]()){
  (e, l) => l match {
    case (`e` :: xs) :: fs => (e :: e :: xs) :: fs
    case _ => List(e) :: l
  }
}
</code>```

Or

```<code>list.zip(false :: list.sliding(2).collect{case List(a,b) => a == b}.toList)
 .foldLeft(List[List[Int]]())((l,e) => if(e._2) (e._1 :: l.head) :: l.tail
                                       else List(e._1) :: l ).reverse
</code>```

[Edit]

```<code>//find the hidden way
//the beauty must be somewhere
//when we talk scala

def split(l: List[Int]): List[List[Int]] =
  l.headOption.map{x => val (h,t)=l.span{x==}; h::split(t)}.getOrElse(Nil)
</code>```

Body:
Given e.g.:

List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)

I'd like to get to:

List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))

I would assume there is a simple List function that does this, but am unable to find it.

Body:
list.foldRight(List[List[Int]]()){
  (e, l) => l match {
    case (`e` :: xs) :: fs => (e :: e :: xs) :: fs
    case _ => List(e) :: l
  }
}

Or

list.zip(false :: list.sliding(2).collect{case List(a,b) => a == b}.toList)
 .foldLeft(List[List[Int]]())((l,e) => if(e._2) (e._1 :: l.head) :: l.tail
                                       else List(e._1) :: l ).reverse

[Edit]

//find the hidden way
//the beauty must be somewhere
//when we talk scala

def split(l: List[Int]): List[List[Int]] =
  l.headOption.map{x => val (h,t)=l.span{x==}; h::split(t)}.getOrElse(Nil)


问:
How does java virtual machine connect user level function to its internal functions?
How does JVM translate API to its implementation inside JVM?

Is it similar to "Linux Kernel syscall" implementation? If so, where are these interfaces? Hope to see the source code.

Figure from https://www.artima.com/insidejvm/ed2/introarch4.html

e.g. ,

Any Java virtual machine implementation must take care to connect these methods of class ClassLoader to the internal class loader subsystem.

https://www.artima.com/insidejvm/ed2/jvmP.html

答:
The API you have linked (https://docs.oracle.com/javase/7/docs/api/), is basically an ordinary class library. When you have installed a JDK, there will be file, src.zip or src.jar, depending on the version, containing the plain Java source code of most of this library. In all versions up to and including Java 8, the compiled API classes are delivered as ordinary jar files, the majority of the API classes being in rt.jar. Starting with Java 9, new module files are used, still, the majority of the API is implemented as ordinary Java code.

You can even browse the source code of certain versions online, e.g. this is the implementation of Object.toString() of version 8, update 40, beta 25, hosted at grepcode.com.

So for most methods, there is nothing “similar to ‘Linux Kernel syscall’” involved when you invoke an API method. It works like an ordinary method invocation and the optimizer may even inline the JRE specific code into your application’s code at runtime. You may also step into the JRE’s code while debugging.

Only a few methods are not implemented as plain Java code, e.g. Object.getClass() is a native method that can only be implemented in a JVM specific way.

There are two general ways to implement these methods. There is a standardized interface, JNI, allowing the interaction of arbitrary native code and Java code. It includes a special linkage between invocations of Java methods declared native and their implementation via JNI. But some methods are handled as intrinsic operations by the JVM instead, which implies that the invocations of these well-known methods (e.g. getClass()) is handled directly by the interpreter/optimizer like a dedicated bytecode instruction. This very efficient handling is sometimes even used for methods, which have an ordinary Java implementation, when there is a platform specific, more efficient alternative. E.g, Integer.rotateLeft and rotateRight have a pure Java implementation, but if the actual CPU used at runtime has dedicated instructions for bitwise rotation, all optimizing JVMs will replace the invocations of these method with intrinsic operations using these CPU instructions.


问:
AngularJS post request send option request but I've considered server side headers
This is my angularJs request:

```<code>url = root + "/products";
$http.post(url, params)
 .then(function(response) {
         console.log('Successfull...');
});
</code>```

This is my server side headers in python tornado:

```<code>self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
</code>```

And this is my option method:

```<code>def options(self, *args, **kwargs):
    self.set_status(204)
    self.finish()
</code>```

Why angularJS sends only an option request and no post request?

答:
I belive your problem is related with this question

At the server side, my web method is adding 'Access-Control-Allow-Origin: *' to the HTTP response. I can see that responses do include this header now. My question is: How do I 'preflight' a request (OPTIONS)? I am using jQuery.getJSON to make the GET request but the browser cancels the request right away with the infamous:

When you make a http request related with CORS, request making a OPTION call first.

Body:
This is my angularJs request:

url = root + "/products";
$http.post(url, params)
 .then(function(response) {
         console.log('Successfull...');
});

This is my server side headers in python tornado:

self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")

And this is my option method:

def options(self, *args, **kwargs):
    self.set_status(204)
    self.finish()

Why angularJS sends only an option request and no post request?


问:
Trouble with QTableWidget right-click event
I was able to simulate the Right-Click event by subclassing the QTableWidget:

header file:

```<code>#ifndef QRIGHCLICKTABLE_H
#define QRIGHCLICKTABLE_H

#include <QTableWidget>
#include <QMouseEvent>

class QRightClickTable : public QTableWidget
{
    Q_OBJECT

public:
    explicit QRightClickTable(QWidget *parent = 0);

private slots:
    void mousePressEvent(QMouseEvent *e);

signals:
    void rightClicked();

public slots:

};

#endif // QRIGHCLICKTABLE_H
</code>```

cpp file

```<code>QRightClickTable::QRightClickTable(QWidget *parent) :
    QPushButton(parent)
{
}

void QRightClickTable::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::RightButton)
        emit rightClicked();
}

QRightClickTable *button = new QRightClickTable(this);
ui->gridLayout->addWidget(button);
connect(button, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));

void MainWindow::onRightClicked()
{
    qDebug() << "User right clicked me";
}
</code>```

Now, right-click works correctly, but there are other problems with QTableWidget: all other mouse events, such as the left click to select a cell, no longer work.
Can you help me?

答:
```<code>    softwareTableWidget = new QTableWidget();
    softwareTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    QObject::connect(softwareTableWidget, &QTableWidget::customContextMenuRequested, this, [this](){
        QMenu *menu = new QMenu;
        auto a = menu->addAction("Test");
        QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
            qDebug() << "Test";
            a->deleteLater();
            menu->deleteLater();
        });
        menu->exec(QCursor::pos());
        menu->clear();
    });
</code>```

If you want to show context menu only at item click then add this:

```<code>if (softwareTableWidget->itemAt(softwareTableWidget->mapFromGlobal(QCursor::pos())))
        {
            QMenu *menu = new QMenu;
            auto a = menu->addAction("Test");
            QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
                qDebug() << "Test";
                a->deleteLater();
                menu->deleteLater();
            });
            menu->exec(QCursor::pos());
            menu->clear();
        }
</code>```

Of course you can do whatever you want instead of showing context menu

Body:
I was able to simulate the Right-Click event by subclassing the QTableWidget:

header file:

#ifndef QRIGHCLICKTABLE_H
#define QRIGHCLICKTABLE_H

#include <QTableWidget>
#include <QMouseEvent>

class QRightClickTable : public QTableWidget
{
    Q_OBJECT

public:
    explicit QRightClickTable(QWidget *parent = 0);

private slots:
    void mousePressEvent(QMouseEvent *e);

signals:
    void rightClicked();

public slots:

};

#endif // QRIGHCLICKTABLE_H

cpp file

QRightClickTable::QRightClickTable(QWidget *parent) :
    QPushButton(parent)
{
}

void QRightClickTable::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::RightButton)
        emit rightClicked();
}

QRightClickTable *button = new QRightClickTable(this);
ui->gridLayout->addWidget(button);
connect(button, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));

void MainWindow::onRightClicked()
{
    qDebug() << "User right clicked me";
}

Now, right-click works correctly, but there are other problems with QTableWidget: all other mouse events, such as the left click to select a cell, no longer work.
Can you help me?

Body:
    softwareTableWidget = new QTableWidget();
    softwareTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    QObject::connect(softwareTableWidget, &QTableWidget::customContextMenuRequested, this, [this](){
        QMenu *menu = new QMenu;
        auto a = menu->addAction("Test");
        QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
            qDebug() << "Test";
            a->deleteLater();
            menu->deleteLater();
        });
        menu->exec(QCursor::pos());
        menu->clear();
    });

If you want to show context menu only at item click then add this:

if (softwareTableWidget->itemAt(softwareTableWidget->mapFromGlobal(QCursor::pos())))
        {
            QMenu *menu = new QMenu;
            auto a = menu->addAction("Test");
            QObject::connect(a, &QAction::triggered, this, [this, menu, a](){
                qDebug() << "Test";
                a->deleteLater();
                menu->deleteLater();
            });
            menu->exec(QCursor::pos());
            menu->clear();
        }

Of course you can do whatever you want instead of showing context menu


问:
Windows Phone 7 Pop-up window
Ive used an app which uses a type of popup window.
When you click on some specific, a 'popup' scrolls up from the bottom of the screen and fills the whole window. If i remember correctly its semi transparent. It has several text sections and a range of buttons on it. What sort of control is this?</p>

答:
The coding4fun Windows Phone Toolkit includes an example of doing a popup window (for an about box) that works correctly. I've found it very useful.

http://coding4fun.codeplex.com/

Title: Windows Phone 7 Pop-up window


问:
Why does this switch Statement not return anything when switching compilers from G++ to MSVC?
I was helping a friend with one of his C++ assignments and we found the following code snippet would throw exceptions in MSVC, but when compiling with G++, the exact same code would work fine. The exceptions were return because this function called getValue() wasn't returning anything.

```<code>string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
    case 11:
    {
        rtnValue = "J";
        break;
    }
    case 12:
    {
        rtnValue = "Q";
        break;
    }
    case 13:
    {
        rtnValue = "K";
        break;
    }
    case 14:
    {
        rtnValue = "A";
        break;
    }
    default:
    {
        //
        // if the value is a a number, we assume it is 2..10
        //
        convert << value;            // use a stream to convert the number
        rtnValue = convert.str();    // into a string
        if (value < 2 || value > 10)
        {
            rtnValue = "ERROR" + rtnValue + "ERROR";
        }
    }
    return rtnValue;
    }
}
</code>```

This program turns integers into strings. For the numbers 11-14 it uses switch statement (I know this isn't the best implementation but it's an introductory class).

We found that this could easily be solved by adding another return statement at the end.

```<code>string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
        case 11:
        {
            rtnValue = "J";
            break;
        }
        case 12:
        {
            rtnValue = "Q";
            break;
        }
        case 13:
        {
            rtnValue = "K";
            break;
        }
        case 14:
        {
            rtnValue = "A";
            break;
        }
        default:
        {
            //
            // if the value is a a number, we assume it is 2..10
            //
            convert << value;            // use a stream to convert the number
            rtnValue = convert.str();    // into a string
            if (value < 2 || value > 10)
            {
                rtnValue = "ERROR" + rtnValue + "ERROR";
            }
        }
        return rtnValue;
    }
    return rtnValue;
}
</code>```

And this now fixes it for MSVC (and I assume G++ if I checked).

Why did that fix work? Does MSVC and G++ treat parentheses differently with respect to switch statements?

答:
In the first example, the return rtnValue is in the wrong place, and will only ever work when the default case is hit.

In the second example, you have added the return rtnValue in the correct place (and the other can be safely removed).

As to why it worked on GCC and not on MSVC, I don't know, without the return being in the correct place, it's not valid C++ (not all paths have a return value), so you should have got a compilation error on any C++ compiler.

I would suggest the problem is actually the way the braces {} are being used, and your friend thought that the closing brace of the default case, actually closed the switch statement, but it doesn't.

Also, there is no need to have braces on any of the case statements.  Braces CAN be used in this way to introduce scoping (for example, temporary variables for a particular case), but in your example, just leads to confusion.

Body:
I was helping a friend with one of his C++ assignments and we found the following code snippet would throw exceptions in MSVC, but when compiling with G++, the exact same code would work fine. The exceptions were return because this function called getValue() wasn't returning anything.

string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
    case 11:
    {
        rtnValue = "J";
        break;
    }
    case 12:
    {
        rtnValue = "Q";
        break;
    }
    case 13:
    {
        rtnValue = "K";
        break;
    }
    case 14:
    {
        rtnValue = "A";
        break;
    }
    default:
    {
        //
        // if the value is a a number, we assume it is 2..10
        //
        convert << value;            // use a stream to convert the number
        rtnValue = convert.str();    // into a string
        if (value < 2 || value > 10)
        {
            rtnValue = "ERROR" + rtnValue + "ERROR";
        }
    }
    return rtnValue;
    }
}

This program turns integers into strings. For the numbers 11-14 it uses switch statement (I know this isn't the best implementation but it's an introductory class).

We found that this could easily be solved by adding another return statement at the end.

string getValue(int value) {

    ostringstream convert;

    string rtnValue;

    switch (value) {
        case 11:
        {
            rtnValue = "J";
            break;
        }
        case 12:
        {
            rtnValue = "Q";
            break;
        }
        case 13:
        {
            rtnValue = "K";
            break;
        }
        case 14:
        {
            rtnValue = "A";
            break;
        }
        default:
        {
            //
            // if the value is a a number, we assume it is 2..10
            //
            convert << value;            // use a stream to convert the number
            rtnValue = convert.str();    // into a string
            if (value < 2 || value > 10)
            {
                rtnValue = "ERROR" + rtnValue + "ERROR";
            }
        }
        return rtnValue;
    }
    return rtnValue;
}

And this now fixes it for MSVC (and I assume G++ if I checked).

Why did that fix work? Does MSVC and G++ treat parentheses differently with respect to switch statements?