问:
Dropdown(list) ComboBox control field options C#
I use a ComboBox DropDown to show a number of items that can be selected. I also use a default text "Select item". It works perfectly apart from the fact that once I picked an item from the list, I can select the text and remove it (using the backspace) so that the area for the selected item is blank (see image).

I would like to prevent this or, in case this is not possible, to have the default text shown again. The latter doesn't work so far, so I tried the DropDownList but then the background of the entire list becomes grey. If I then select OwnerDrawFixed or OwnerDrawVariable in DrawMode, the background turns white again but also the font color becomes white (instead of black).

I found that I have to use DrawItem to change the layout but even that doesn't work. I simply want the same style as I indicated for DropDown. Does anyone know how to do this or where to find a similar question that has already been answered?

答:
The suggested solution did not do the trick but I found a workaround to the initial problem, which is the manual deletion of the ComboBox Text, so I'll just put it here in case someone else has the same problem. When using

```<code>MyComboBox_TextChanged(object sender, EventArgs e)
</code>```

I can set a restriction myself: if the text is blank, it should show the default text. If the typed text is equal to one of the item in the ComboBox, it should set the selectedItem equal to the typed text.

I also included GotFocus and Leave EventHandlers.

Body:
The suggested solution did not do the trick but I found a workaround to the initial problem, which is the manual deletion of the ComboBox Text, so I'll just put it here in case someone else has the same problem. When using

MyComboBox_TextChanged(object sender, EventArgs e)

I can set a restriction myself: if the text is blank, it should show the default text. If the typed text is equal to one of the item in the ComboBox, it should set the selectedItem equal to the typed text.

I also included GotFocus and Leave EventHandlers.


来源: stackexchange

问:
View git diff from individual parents
Say, I've been presented with a merge conflict, and I managed to fix it, but haven't marked as resolved (i.e. I haven't done git add conflicted files yet). At this point, I can do git diff and I'll be shown how the resultant file differs from each parent, in a combined diff format.

All good so far. Now I wanted to separately inspect how resultant file differs from individual parent. Sure, for a merge conflict involving 2 parents (cherry-pick, rebase etc.), I can use git diff --ours or git diff --theirs, but how do I extend this to more parents?

In other words, if I get conflict from 3 parents, is it possible to view individual diffs w.r.t each parent?

Also, my discovery of --ours and --theirs was rather serendipitous; I couldn't find their usage documented in a diff context.

答:
If

```<code>git diff :1:foo.txt :3:foo.txt
</code>```

does not do what you want, I guess you have to do

```<code>git ls-files -u
</code>```

and the use git show $sha1 > $sha1.txt to create some temporary files and compare those.

See also: Git compare "base" version with "theirs" version of a conflicted file?

ContentLicense: CC BY-SA 3.0

Title: View git diff from individual parents

Body:
If

git diff :1:foo.txt :3:foo.txt

does not do what you want, I guess you have to do

git ls-files -u

and the use git show $sha1 > $sha1.txt to create some temporary files and compare those.

See also: Git compare "base" version with "theirs" version of a conflicted file?


问:
How to sort table by custom defined method
I'm using rails 5 with PostgeSQL and I have model with 2 columns:

```<code>amount: integer
interval_count: integer
</code>```

I have custom method defined in my model amount_per_interval that basically returns amount/interval_count (it calculates it on app level). Now I need to sort whole table by this amount_per_interval value, but I need to do it on database level, because I'm using pagination (and also I have millions of those records so I don't want to load all of them into memory).

Is there any possibility to define such custom ordering on this model? I can't find any solution.

Update:

I basically want to rewrite this SQL:

```<code>SELECT (amount / interval_count) as amount_per_interval FROM my_table ORDER BY amount_per_interval
</code>```

into ActiveRecord's interface and still keep compatibility with pagination and other AR methods.

答:
I'd suggest adding amount_per_interval to your table if you need it for sorting. You can calculate it every time you insert a record.
You can then do this in your SQL query :

```<code>SELECT (...) ORDER BY amount_per_interval
</code>```

or using Rails query interface :

```<code>YourModel.order(amount_per_interval: :desc)
</code>```

which generates this query

```<code>SELECT "table_name".* FROM "table_name" ORDER BY "table_name"."amount_per_interval" DESC
</code>```

This loads all records ordered by amount_per_interval from highest to lowest.

Body:
I'm using rails 5 with PostgeSQL and I have model with 2 columns:

amount: integer
interval_count: integer

I have custom method defined in my model amount_per_interval that basically returns amount/interval_count (it calculates it on app level). Now I need to sort whole table by this amount_per_interval value, but I need to do it on database level, because I'm using pagination (and also I have millions of those records so I don't want to load all of them into memory).

Is there any possibility to define such custom ordering on this model? I can't find any solution.

Update:

I basically want to rewrite this SQL:

SELECT (amount / interval_count) as amount_per_interval FROM my_table ORDER BY amount_per_interval

into ActiveRecord's interface and still keep compatibility with pagination and other AR methods.

Body:
I'd suggest adding amount_per_interval to your table if you need it for sorting. You can calculate it every time you insert a record.
You can then do this in your SQL query :

SELECT (...) ORDER BY amount_per_interval

or using Rails query interface :

YourModel.order(amount_per_interval: :desc)

which generates this query

SELECT "table_name".* FROM "table_name" ORDER BY "table_name"."amount_per_interval" DESC

This loads all records ordered by amount_per_interval from highest to lowest.


问:
Thymeleaf & AJAX mapping JSON data
I have a Spring-Boot project using Thymeleaf.

The HTML form has groups of fields for inputting personal details like:

```<code><button type="button" class="btn btn-default" id="btnGetPerson"><i class="fa fa-search"></i></button>
<Input type="text" id="id0" name="id" th:field="*{person[0].id}" />
<Input type="text" name="surname" th:field="*{person[0].surname}" />
<Input type="text" name="firstname" th:field="*{person[0].firstname}" />
...
<button type="button" class="btn btn-default" id="btnGetPerson"><i class="fa fa-search"></i></button>
<Input type="text" id="id1" name="id" th:field="*{person[1].id}" />
<Input type="text" name="surname" th:field"=*{person[1].surname}" />
<Input type="text" name=firstname" th:field="*{person[1].firstname}" />
etc
</code>```

The results are coming back from the server correctly as JSON and look like:

```<code>surname : Smith
firstname: Bob
</code>```

Then in the script file I got as far as:

```<code>    // GET AND RETURN PERSON
$( '#btnGetPerson').click(function() {
    var $theForm = $(this).closest('.panel-body');
    $.get('/person/' +$('#id0').val(), function(result) {
        $theForm.find('input[name="surname"]').val(result.surname);
    });
});
</code>```

I was then going to do something like:

```<code>Object.keys(result).forEach(function(key) {
$('[name="' + key + '"]').val(result[key]);
});
</code>```

To iterate over the keys and values in the JSON - but Thymeleaf renames the name fields in the HTML to match the form backing object, so my name="surname" gets over written with name="event.person[0].surname" where event is the backing object.

How should I approach mapping getting the JSON data that comes back from the server into the DOM?

UPDATE

A sample of the rendered html looks like:

```<code>                    <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Victim / Subject</h3>
                    </div>
                    <div class="panel-body">

                        <div class="row">
                            <input type="text" class="form-control hidden" id="personId0" name="persons[0].id" value="1" />
                            <div class="col-sm-5">
                                <div class="form-group">

                                    <label for="surname0" class="col-sm-2 control-label">Surname</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" id="surname0" placeholder="surname" name="persons[0].surname" value="EASTWOOD"/>
                                    </div>
                                </div>
                            </div
</code>```

I should also add that the form initially renders with three people (index 0,1,2) and then there is a button to add another set of people fields dynamically by cloning the html fragment.

答:
The JSON data coming back from server looks like:

```<code>{
"id":1,
"surname":"EASTWOOD",
"middlename":"James",
"firstname":"Clint",
"countryOfBirth":"US",
"occupation":"Actor",
"gender":"Male",
"phoneHome":"555-1234",
"dob":"1965-06-17"
}
</code>```

Map this to inputs, but the name and id's are renamed by thymeleaf. So in order to get around this use data-property field with names that match the key names in the JSON. So html inputs look like:

```<code><input type="text" class="form-control  person" data-property="surname" placeholder="surname" th:field="*{persons[0].surname}"/>
<input type="text" class="form-control  person" data-property="firstname" placeholder="Firstname" th:field="*{persons[0].firstname}"/>
<select class="selectpicker form-control person" data-property="countryOfBirth" data-live-search="true" title="Birth Country" th:field="*{persons[0].countryOfBirth}">
</code>```

Now the data-property provides tags that match the JSON names.

The jquery and javascript to find the closest panel-body and then update the inputs is below. Note that because of the way dropdowns are displayed in twitter-bootstrap as buttons I had to find a different class:

```<code>// GET AND RETURN PERSON
$( '#btnGetPerson').click(function() {
    var $theForm = $(this).closest('.panel-body');
    $.get('/person/' +$('#nia0').val(), function(result) {

        // LOOPS OVER THE PERSON INPUTS
        $theForm.find('.form-control.person').each(function()  {
            var formkey = $(this).attr('data-property');
            $(this).val(result[formkey]);
        });

        // LOOPS OVER THE SELECT PICKERS
        $theForm.find('.bootstrap-select').each(function() {
            var formkey = $(this).find('.selectpicker.form-control').attr('data-property');
            $(this).find('.filter-option').text(result[formkey]);
            $(this).find('.filter-option').val(result[formkey]);
        });
    });
});
</code>```

Thanks to all those that helped.

Hope this helps someone else.

Title: Thymeleaf & AJAX mapping JSON data

Body:
I have a Spring-Boot project using Thymeleaf.

The HTML form has groups of fields for inputting personal details like:

<button type="button" class="btn btn-default" id="btnGetPerson"></button>
<Input type="text" id="id0" name="id" th:field="*{person[0].id}" />
<Input type="text" name="surname" th:field="*{person[0].surname}" />
<Input type="text" name="firstname" th:field="*{person[0].firstname}" />
...
<button type="button" class="btn btn-default" id="btnGetPerson"></button>
<Input type="text" id="id1" name="id" th:field="*{person[1].id}" />
<Input type="text" name="surname" th:field"=*{person[1].surname}" />
<Input type="text" name=firstname" th:field="*{person[1].firstname}" />
etc

The results are coming back from the server correctly as JSON and look like:

surname : Smith
firstname: Bob

Then in the script file I got as far as:

    // GET AND RETURN PERSON
$( '#btnGetPerson').click(function() {
    var $theForm = $(this).closest('.panel-body');
    $.get('/person/' +$('#id0').val(), function(result) {
        $theForm.find('input[name="surname"]').val(result.surname);
    });
});

I was then going to do something like:

Object.keys(result).forEach(function(key) {
$('[name="' + key + '"]').val(result[key]);
});

To iterate over the keys and values in the JSON - but Thymeleaf renames the name fields in the HTML to match the form backing object, so my name="surname" gets over written with name="event.person[0].surname" where event is the backing object.

How should I approach mapping getting the JSON data that comes back from the server into the DOM?

UPDATE

A sample of the rendered html looks like:

Victim / Subject

                            <input type="text" class="form-control hidden" id="personId0" name="persons[0].id" value="1" />

                                    Surname

                                        <input type="text" class="form-control" id="surname0" placeholder="surname" name="persons[0].surname" value="EASTWOOD"/>

                            </div

I should also add that the form initially renders with three people (index 0,1,2) and then there is a button to add another set of people fields dynamically by cloning the html fragment.

Body:
The JSON data coming back from server looks like:

{
"id":1,
"surname":"EASTWOOD",
"middlename":"James",
"firstname":"Clint",
"countryOfBirth":"US",
"occupation":"Actor",
"gender":"Male",
"phoneHome":"555-1234",
"dob":"1965-06-17"
}

Map this to inputs, but the name and id's are renamed by thymeleaf. So in order to get around this use data-property field with names that match the key names in the JSON. So html inputs look like:

<input type="text" class="form-control  person" data-property="surname" placeholder="surname" th:field="*{persons[0].surname}"/>
<input type="text" class="form-control  person" data-property="firstname" placeholder="Firstname" th:field="*{persons[0].firstname}"/>
<select class="selectpicker form-control person" data-property="countryOfBirth" data-live-search="true" title="Birth Country" th:field="*{persons[0].countryOfBirth}">

Now the data-property provides tags that match the JSON names.

The jquery and javascript to find the closest panel-body and then update the inputs is below. Note that because of the way dropdowns are displayed in twitter-bootstrap as buttons I had to find a different class:

// GET AND RETURN PERSON
$( '#btnGetPerson').click(function() {
    var $theForm = $(this).closest('.panel-body');
    $.get('/person/' +$('#nia0').val(), function(result) {

        // LOOPS OVER THE PERSON INPUTS
        $theForm.find('.form-control.person').each(function()  {
            var formkey = $(this).attr('data-property');
            $(this).val(result[formkey]);
        });

        // LOOPS OVER THE SELECT PICKERS
        $theForm.find('.bootstrap-select').each(function() {
            var formkey = $(this).find('.selectpicker.form-control').attr('data-property');
            $(this).find('.filter-option').text(result[formkey]);
            $(this).find('.filter-option').val(result[formkey]);
        });
    });
});

Thanks to all those that helped.

Hope this helps someone else.


问:
Movie DB - storage of Actors / actress / Tags?
Creating a movie db and I dont like the idea of giving each actor/actress and also each tag its own row as if there are 10 million moives total, each has a cast of atleast 20-30 people we will have 200-300 million rows in the table.

And it gets more complex with tags which can be unlimited per movie. So how to best store these 3 items? Ideally these can be modeled as a Many to Many but still it will have hundreds of millions of rows. Any better suggestions on storing these? I am using MySQL.

I would dump it all in a textfile but I need to link actors between movies and do some analytics also and allow users to rate actors find movies by tag, etc so need to use a DB.

答:
It sounds perhaps a bit of premature optimization here. You could denormalize all actors into a TEXT column of some kind onto the Movie table, but your performance + search would suffer, as well as losing all benefits of relational data.

Suggest to keep the normalized schema, as you were originally thinking:

```<code>Movie (ID)
Actor (ID)
Tag (ID) --horror, comedy, etc.

MovieActor (MovieID, ActorID)
MovieTag (MovieID, TagID)
</code>```

Create indexes as per normal on the associative entities: MovieActor and MovieTag.

Load some dummy data in a Test environment. 10 million movies with 100 million actors with 1 million tags. Create associative entries for each as required.

Baseline and performance test.

Horizontal partitioning (sharding) if your performance metrics require more performance.

Regardless of the number of movies, or whether the data is DNA sequences: implement a design, test it, judge its performance based on your requirements (user acceptance, SLA, etc)

ContentLicense: CC BY-SA 2.5

Body:
It sounds perhaps a bit of premature optimization here. You could denormalize all actors into a TEXT column of some kind onto the Movie table, but your performance + search would suffer, as well as losing all benefits of relational data.

Suggest to keep the normalized schema, as you were originally thinking:

Movie (ID)
Actor (ID)
Tag (ID) --horror, comedy, etc.

MovieActor (MovieID, ActorID)
MovieTag (MovieID, TagID)

Create indexes as per normal on the associative entities: MovieActor and MovieTag.

Load some dummy data in a Test environment. 10 million movies with 100 million actors with 1 million tags. Create associative entries for each as required.

Baseline and performance test.

Horizontal partitioning (sharding) if your performance metrics require more performance.

Regardless of the number of movies, or whether the data is DNA sequences: implement a design, test it, judge its performance based on your requirements (user acceptance, SLA, etc)


问:
C# Error: OutOfMemoryException - Reading a large text file and replacing from dictionary
I'm new to C# and object-oriented programming in general. I have an application which parses text file.

The objective of the application is to read the contents of the provided text file and replace the matching values.

When a file about 800 MB to 1.2GB is provided as the input, the application crashes with error System.OutofMemoryException.

On researching, I came across couple of answers which recommend changing the Target Platform: to x64.

Same issue exists after changing the target platform.

Following is the code:

```<code>// Reading the text file
                var _data = string.Empty;
                using (StreamReader sr = new StreamReader(logF))
                {
                    _data = sr.ReadToEnd();
                    sr.Dispose();
                    sr.Close();
                }

                foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

                //Writing The text File
                using (StreamWriter sw = new StreamWriter(logF))
                {
                    sw.WriteLine(_data);
                    sw.Dispose();
                    sw.Close();
                }
</code>```

The error points to

_data = sr.ReadToEnd();

replacements is a dictionary. The Key contains the original word and the Value contains the word to be replaced.

The Key elements are replaced with the Value elements of the KeyValuePair.

The approached being followed is Reading the file, replacing and writing.

I tried using a StringBuilder instead of string yet the application crashed.

Can this be overcome by reading the file one line at a time, replacing and writing? What would be the efficient and faster way of doing the same.

Update: The system memory is 8 GB and on monitoring the performance it spikes upto 100% memory usage.

@Tim Schmelter answer works well.

However, the memory utilization spikes over 90%. It could be due to the following code:

```<code>            String[] arrayofLine = File.ReadAllLines(logF);
            // Generating Replacement Information
            Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                foreach (var replacement in replacements.Keys)
                {
                    if (arrayofLine[i].Contains(replacement))
                    {
                        arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
                        if (_replacementInfo.ContainsKey(i + 1))
                        {
                            _replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
                        }
                        else
                        {
                            _replacementInfo.Add(i + 1, replacement);
                        }
                    }
                }
            }

//Creating Replacement Information
                StringBuilder sb = new StringBuilder();
                foreach (var Replacement in _replacementInfo)
                {
                    foreach (var replacement in Replacement.Value.Split('|'))
                    {
                        sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
                    }
                }

                // Writing the replacement information
                if (sb.Length!=0)
                {
                using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
                {
                    swh.WriteLine(sb.ToString());
                    swh.Dispose();
                    swh.Close();
                }
                }
                sb.Clear();
</code>```

It finds the line number in which the replacement was made. Can this be captured using Tim's code in order to avoid loading the data into memory multiple times.

答:
An OutOfMemoryException is thrown whenever the application tries and fails to allocate memory to perform an operation. According to Microsoft's documentation, the following operations can potentially throw an OutOfMemoryException:

Boxing (i.e., wrapping a value type in an Object)
Creating an array
Creating an object
If you try to create an infinite number of objects, then it's pretty reasonable to assume that you're going to run out of memory sooner or later.

(Note: don't forget about the garbage collector. Depending on the lifetimes of the objects being created, it will delete some of them if it determines they're no longer in use.)

For What I suspect is this line :

```<code>  foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }
</code>```

That sooner or later u will run out of memory. Do u ever count how many it loop?

Try

Increase the available memory.

Reduce the amount of data you are    retrieving.

Body:
I'm new to C# and object-oriented programming in general. I have an application which parses text file.

The objective of the application is to read the contents of the provided text file and replace the matching values.

When a file about 800 MB to 1.2GB is provided as the input, the application crashes with error System.OutofMemoryException.

On researching, I came across couple of answers which recommend changing the Target Platform: to x64.

Same issue exists after changing the target platform.

Following is the code:

// Reading the text file
                var _data = string.Empty;
                using (StreamReader sr = new StreamReader(logF))
                {
                    _data = sr.ReadToEnd();
                    sr.Dispose();
                    sr.Close();
                }

                foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

                //Writing The text File
                using (StreamWriter sw = new StreamWriter(logF))
                {
                    sw.WriteLine(_data);
                    sw.Dispose();
                    sw.Close();
                }

The error points to

_data = sr.ReadToEnd();

replacements is a dictionary. The Key contains the original word and the Value contains the word to be replaced.

The Key elements are replaced with the Value elements of the KeyValuePair.

The approached being followed is Reading the file, replacing and writing.

I tried using a StringBuilder instead of string yet the application crashed.

Can this be overcome by reading the file one line at a time, replacing and writing? What would be the efficient and faster way of doing the same.

Update: The system memory is 8 GB and on monitoring the performance it spikes upto 100% memory usage.

@Tim Schmelter answer works well.

However, the memory utilization spikes over 90%. It could be due to the following code:

            String[] arrayofLine = File.ReadAllLines(logF);
            // Generating Replacement Information
            Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
            for (int i = 0; i < arrayofLine.Length; i++)
            {
                foreach (var replacement in replacements.Keys)
                {
                    if (arrayofLine[i].Contains(replacement))
                    {
                        arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
                        if (_replacementInfo.ContainsKey(i + 1))
                        {
                            _replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
                        }
                        else
                        {
                            _replacementInfo.Add(i + 1, replacement);
                        }
                    }
                }
            }

//Creating Replacement Information
                StringBuilder sb = new StringBuilder();
                foreach (var Replacement in _replacementInfo)
                {
                    foreach (var replacement in Replacement.Value.Split('|'))
                    {
                        sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
                    }
                }

                // Writing the replacement information
                if (sb.Length!=0)
                {
                using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
                {
                    swh.WriteLine(sb.ToString());
                    swh.Dispose();
                    swh.Close();
                }
                }
                sb.Clear();

It finds the line number in which the replacement was made. Can this be captured using Tim's code in order to avoid loading the data into memory multiple times.

Body:
An OutOfMemoryException is thrown whenever the application tries and fails to allocate memory to perform an operation. According to Microsoft's documentation, the following operations can potentially throw an OutOfMemoryException:

Boxing (i.e., wrapping a value type in an Object)
Creating an array
Creating an object
If you try to create an infinite number of objects, then it's pretty reasonable to assume that you're going to run out of memory sooner or later.

(Note: don't forget about the garbage collector. Depending on the lifetimes of the objects being created, it will delete some of them if it determines they're no longer in use.)

For What I suspect is this line :

  foreach (var replacement in replacements)
                {
                    _data = _data.Replace(replacement.Key, replacement.Value);
                }

That sooner or later u will run out of memory. Do u ever count how many it loop?

Try

Increase the available memory.

Reduce the amount of data you are    retrieving.


问:
How to use utils::stack() with data labbeled with Hmisc in R
Playing around with R, I came across this really weird behavior of the stack() function :

```<code>library(Hmisc)
df = data_frame(col1=c(1,2,3,4,5,6), col2=c(55,66,88,99,22,33))
stack(df) #works like a charm
label(df$col1)="column 1"
label(df$col2)="column 2"
stack(df) #Error in stack.data.frame(df) : no vector column selected
</code>```

I guess this is caused by class(df[1,1)=="numeric" at first, but class(df[1,1)=="labelled", "numeric" at last.

Is there any clean workaround for this ?

答:
I finally used Dominic Comtois's answer here to get rid of labels : </p>

```<code>stack(clear.labels(df)) #works fine
</code>```

Body:
Playing around with R, I came across this really weird behavior of the stack() function :

library(Hmisc)
df = data_frame(col1=c(1,2,3,4,5,6), col2=c(55,66,88,99,22,33))
stack(df) #works like a charm
label(df$col1)="column 1"
label(df$col2)="column 2"
stack(df) #Error in stack.data.frame(df) : no vector column selected

I guess this is caused by class(df[1,1)=="numeric" at first, but class(df[1,1)=="labelled", "numeric" at last.

Is there any clean workaround for this ?

Body:
I finally used Dominic Comtois's answer here to get rid of labels :

stack(clear.labels(df)) #works fine


问:
Spring boot default initalization relativePath
I have used the spring boot initializer to generate a project.

What does this line do?  Why is it used?  What would happen if its not used?

```<code><relativePath/> <!-- lookup parent from repository -->
</code>```

An extract from The pom looks like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rob.jpa.troubleshooting</groupId>
    <artifactId>jpademo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpademo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
     ...etc
</code>```

答:
It's the relative path from the module's pom.xml to the parent's pom.xml
(Ref: Maven Documentation)

In your case, its not required. because parent's pom is taken from JAR file.

Scenario :
If we have Application1 as parent to the module Application2, then we need to specifiy  to locate the pom of Parent in the module's pom.xml

Body:
I have used the spring boot initializer to generate a project.

What does this line do?  Why is it used?  What would happen if its not used?

<relativePath/>

An extract from The pom looks like this

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rob.jpa.troubleshooting</groupId>
    <artifactId>jpademo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpademo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
     ...etc

ContentLicense: CC BY-SA 4.0


问:
How to conditionally compute difference in column values between rows in R?
I have the following data set

(this is just sample, actual data set runs into rows)

Image of the data set in also attached in the snapshot
Dataset snapshot

```<code>User    Time    Flag    TimeDifference     Expected o/p (Seconds)
A   11:39:30    1
A   11:37:53    1
A   20:44:19    1
A   22:58:42    2   Calculate time difference?  8063
A   23:01:54    1   Calculate time difference?  192
B   23:03:00    1
B   23:03:33    1
B   23:03:53    1
B   15:00:42    3   Calculate time difference   28991
B   19:35:31    2   Calculate time difference   16489
B   19:35:34    1   Calculate time difference   3
C   10:19:06    1
C   10:59:50    1
C   10:59:50    1
C   12:16:36    1
C   12:16:36    1
</code>```

I need to calculate for each user

the time difference (in seconds) between rows whenever there is a 'Flag change' and store it in a new column called 'Time difference'

i.e. whenever flag changes from 1 to 2 , or 2 to 3 , or 2 to 1, or 3 to 1 , I need to compute time difference the time column between the current row and preceding row when flag change in encountered.

I have time in hh:mm:ss format.
Is there any for-loop function I can apply here?

Help appreciated.

答:
One way to do that is to turn your time variable into POSIXlt time object, calculate the time difference (for all rows) against a shifted time variable. Then use your flag variable to NA the ones you dont want. The important part is you need to diff the flag variable so you know when your flag has changed

I'm laying out all the steps here, but theres probably a quicker way to do it:

```<code># Create the data
flag <- c(1,1,1,2,1,1,1,1,3,2,1,1,1,1,1,1)
time <- c('11:39:30','11:37:53','20:44:19','22:58:42','23:01:54',
          '23:03:00','23:03:33','23:03:53','15:00:42','19:35:31',
          '19:35:34','10:19:06','10:59:50','10:59:50','12:16:36',
          '12:16:36')

# Shift the time
time_shift <- c(NA,time[1:length(time)-1])

# Turn into POSIXlt objects
time <- strptime(time, format='%H:%M:%S')
time_shift <- strptime(time_shift, format='%H:%M:%S')

data <- data.frame(time, time_shift, flag)

# Calculate diffs
data$time_diff <- as.numeric(abs(difftime(data$time, data$time_shift, units=('secs'))))
data$flag_diff <- c(NA,abs(diff(data$flag)))

# Set non 'flag change' diffs to NA
data$time_diff[data$flag_diff == 0] <- NA
</code>```

You'll probably want to remove the useless columns and convert time back into your original representation, which you can do with:

```<code>data$time <- format(data$time, "%H:%M:%S")
data <- data[c('time', 'flag', 'time_diff')]
</code>```

That will result in a dataframe that looks like this:

```<code>       time flag time_diff
1  11:39:30    1        NA
2  11:37:53    1        NA
3  20:44:19    1        NA
4  22:58:42    2      8063
5  23:01:54    1       192
6  23:03:00    1        NA
7  23:03:33    1        NA
8  23:03:53    1        NA
9  15:00:42    3     28991
10 19:35:31    2     16489
11 19:35:34    1         3
12 10:19:06    1        NA
13 10:59:50    1        NA
14 10:59:50    1        NA
15 12:16:36    1        NA
16 12:16:36    1        NA
</code>```

Body:
I have the following data set

(this is just sample, actual data set runs into rows)

Image of the data set in also attached in the snapshot
Dataset snapshot

User    Time    Flag    TimeDifference     Expected o/p (Seconds)
A   11:39:30    1
A   11:37:53    1
A   20:44:19    1
A   22:58:42    2   Calculate time difference?  8063
A   23:01:54    1   Calculate time difference?  192
B   23:03:00    1
B   23:03:33    1
B   23:03:53    1
B   15:00:42    3   Calculate time difference   28991
B   19:35:31    2   Calculate time difference   16489
B   19:35:34    1   Calculate time difference   3
C   10:19:06    1
C   10:59:50    1
C   10:59:50    1
C   12:16:36    1
C   12:16:36    1

I need to calculate for each user

the time difference (in seconds) between rows whenever there is a 'Flag change' and store it in a new column called 'Time difference'

i.e. whenever flag changes from 1 to 2 , or 2 to 3 , or 2 to 1, or 3 to 1 , I need to compute time difference the time column between the current row and preceding row when flag change in encountered.

I have time in hh:mm:ss format.
Is there any for-loop function I can apply here?

Help appreciated.

Body:
One way to do that is to turn your time variable into POSIXlt time object, calculate the time difference (for all rows) against a shifted time variable. Then use your flag variable to NA the ones you dont want. The important part is you need to diff the flag variable so you know when your flag has changed

I'm laying out all the steps here, but theres probably a quicker way to do it:

# Create the data
flag <- c(1,1,1,2,1,1,1,1,3,2,1,1,1,1,1,1)
time <- c('11:39:30','11:37:53','20:44:19','22:58:42','23:01:54',
          '23:03:00','23:03:33','23:03:53','15:00:42','19:35:31',
          '19:35:34','10:19:06','10:59:50','10:59:50','12:16:36',
          '12:16:36')

# Shift the time
time_shift <- c(NA,time[1:length(time)-1])

# Turn into POSIXlt objects
time <- strptime(time, format='%H:%M:%S')
time_shift <- strptime(time_shift, format='%H:%M:%S')

data <- data.frame(time, time_shift, flag)

# Calculate diffs
data$time_diff <- as.numeric(abs(difftime(data$time, data$time_shift, units=('secs'))))
data$flag_diff <- c(NA,abs(diff(data$flag)))

# Set non 'flag change' diffs to NA
data$time_diff[data$flag_diff == 0] <- NA

You'll probably want to remove the useless columns and convert time back into your original representation, which you can do with:

data$time <- format(data$time, "%H:%M:%S")
data <- data[c('time', 'flag', 'time_diff')]

That will result in a dataframe that looks like this:

       time flag time_diff
1  11:39:30    1        NA
2  11:37:53    1        NA
3  20:44:19    1        NA
4  22:58:42    2      8063
5  23:01:54    1       192
6  23:03:00    1        NA
7  23:03:33    1        NA
8  23:03:53    1        NA
9  15:00:42    3     28991
10 19:35:31    2     16489
11 19:35:34    1         3
12 10:19:06    1        NA
13 10:59:50    1        NA
14 10:59:50    1        NA
15 12:16:36    1        NA
16 12:16:36    1        NA


问:
Using [] with the Safe Navigation Operator in Ruby
I currently have a piece of code that looks like:

```<code>if match = request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)
  match[:slug]
end
</code>```

Is there a way to use the safe navigation operator (introduced in 2.3.0) to avoid this if conditional?

答:
For better readability I would pick #dig instead of the #[].

Like,

```<code>request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.dig(:slug)
</code>```

instead of

```<code>request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug)
</code>```

Body:
I currently have a piece of code that looks like:

if match = request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)
  match[:slug]
end

Is there a way to use the safe navigation operator (introduced in 2.3.0) to avoid this if conditional?

Body:
For better readability I would pick #dig instead of the #[].

Like,

request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.dig(:slug)

instead of

request.path.match(/\A\/(?<slug>(?!admin|assets)\w+)/)&.[](:slug)


问:
IBM MobileFirst Sever support load balancing?
i have read ibm mobilefirst documents but cannot found content about load balancing. Does MFP support load balancing ? </p>

答:
Yes. IBM MobileFirst Server support load balancing. Actually it is the underlying app servers on which MFP is running is responsible in handling.

MFP Server runs on AppServers like WebSphere Application Servers (Liberty Profile or Full profile) or Tomcat. So any of the load balancing related documentations for the above App servers would help you achieve the same.

Following links might be of help for your reference.

Typical MF Topologies

Session Independent mode in MFP Cluster


问:
how to ignore dir-prop-base in .svn folder?
I've read several posts here about ignoring files in Mercurial but I'm stumped on this one.

I have a couple of .svn files in my repository (I'm using hg for local commits, then pushing to svn). The files are:

```<code>Apps\.svn\dir-prop-base
Apps\.svn\entries
</code>```

I've got several ignore entries in my .hgignore but none of them seem to be covering these two files.

```<code>syntax: glob
.svn/*
**/.svn/**.*
syntax: regexp
\.svn\\*
</code>```

I'm trying a couple of things to see which sticks there. To me, it looks like those files should be ignored twice. The strange thing is that Apps\.svn\all-wcprops is being ignored. Clearly I'm missing something. I'm checking whether the files are ignored by opening a new status window using TortoiseHg. I can't detect any difference between that and hg status.

答:
Oben pointed me in the right direction. He declined making an answer, so here it is:

The files that you want to ignore can't be in an Add state when you are editing the ignore file (since Add takes precedence over Ignore apparently). So my solution was to do hg revert, edit the ignore file, then use hg status [directory] -i to see which files in the target directory would be ignored. Repeat until all the correct files are ignored, then use hg add.

Body:
I've read several posts here about ignoring files in Mercurial but I'm stumped on this one.

I have a couple of .svn files in my repository (I'm using hg for local commits, then pushing to svn). The files are:

Apps\.svn\dir-prop-base
Apps\.svn\entries

I've got several ignore entries in my .hgignore but none of them seem to be covering these two files.

syntax: glob
.svn/*
**/.svn/**.*
syntax: regexp
\.svn\\*

I'm trying a couple of things to see which sticks there. To me, it looks like those files should be ignored twice. The strange thing is that Apps\.svn\all-wcprops is being ignored. Clearly I'm missing something. I'm checking whether the files are ignored by opening a new status window using TortoiseHg. I can't detect any difference between that and hg status.


问:
MSSQL collation conflict stored procedure
I have an error with a query like

```<code>Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_100_CS_AS" in the equal to operation.
</code>```

I know that I can resolve this error with this SQL statement:

```<code>ALTER TABLE [TableA]
ALTER COLUMN [ColumnX]
VARCHAR(20) COLLATE SQL_Latin1_General_CP1_CI_AS;
</code>```

The problem I have is that I have a stored procedure where I have added the SQL statement to alter the column and then the query I'm getting the error, but the alter statement don't seem to be executed. The code in the stored procedure is as follows:

```<code>ALTER TABLE [TableA]
ALTER COLUMN [ColumnX]
VARCHAR(20) COLLATE SQL_Latin1_General_CP1_CI_AS;

INSERT INTO [TableC]
([ColumT] )
SELECT
 [TableB].[Account]
FROM [TableA], [TableB]
WHERE
 Left(TableA.[ColumnX],1)=TableB.[ColumnY];
</code>```

If I have run the ALTER and INSERT SQL code independently, then the INSERT statement works. If I run them together in a stored procedure, then I get the error.

Why is the stored procedure not running the first ALTER SQL statement?

答:
Either you change the table to have the proper collation by executing the alter statement outside the scope of a stored procedure (i.e. standalone). This only has to be done once.

Doing this in the stored procedure is not the right place. You would alter this table column each time the stored procedure is executed, which is not necessary. Also it can be problematic if you later decide this column has to change in another way; you would have to remember and change the stored procedure as well. That is not desirable.

Or, you specify the collation that is needed in the SQL statement

```<code>INSERT INTO [TableC]
    ([ColumT] )
SELECT
    [TableB].[Account]
FROM
    [TableA]
    INNER JOIN [TableB] ON
        LEFT(TableA.[ColumnX],1) COLLATE SQL_Latin1_General_CP1_CI_AS = TableB.[ColumnY];
</code>```

Body:
I have an error with a query like

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_100_CS_AS" in the equal to operation.

I know that I can resolve this error with this SQL statement:

ALTER TABLE [TableA]
ALTER COLUMN [ColumnX]
VARCHAR(20) COLLATE SQL_Latin1_General_CP1_CI_AS;

The problem I have is that I have a stored procedure where I have added the SQL statement to alter the column and then the query I'm getting the error, but the alter statement don't seem to be executed. The code in the stored procedure is as follows:

ALTER TABLE [TableA]
ALTER COLUMN [ColumnX]
VARCHAR(20) COLLATE SQL_Latin1_General_CP1_CI_AS;

INSERT INTO [TableC]
([ColumT] )
SELECT
 [TableB].[Account]
FROM [TableA], [TableB]
WHERE
 Left(TableA.[ColumnX],1)=TableB.[ColumnY];

If I have run the ALTER and INSERT SQL code independently, then the INSERT statement works. If I run them together in a stored procedure, then I get the error.

Why is the stored procedure not running the first ALTER SQL statement?

Body:
Either you change the table to have the proper collation by executing the alter statement outside the scope of a stored procedure (i.e. standalone). This only has to be done once.

Doing this in the stored procedure is not the right place. You would alter this table column each time the stored procedure is executed, which is not necessary. Also it can be problematic if you later decide this column has to change in another way; you would have to remember and change the stored procedure as well. That is not desirable.

Or, you specify the collation that is needed in the SQL statement

INSERT INTO [TableC]
    ([ColumT] )
SELECT
    [TableB].[Account]
FROM
    [TableA]
    INNER JOIN [TableB] ON
        LEFT(TableA.[ColumnX],1) COLLATE SQL_Latin1_General_CP1_CI_AS = TableB.[ColumnY];


问:
Unable to get the xml attributes as column names with the XSLT
This is my sample xml file,

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<FIXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.fixprotocol.org/FIXML-5-0-SP2" xsi:schemaLocation="http://www.fixprotocol.org/FIXML-5-0-SP2 fixml-main-5-0-SP2_.xsd" s="2012-04-23" v="FIX.5.0SP2">
  <Batch ID="RPTTA111PUBLI20170518">
<MktDef MktID="XEEE" MktSegID="19478" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B1" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160PX2" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="1.195">
  <Instrmt ID="483878" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-06" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41222169" AltIDSrc="M"/>
    <AID AltID="XF00000407B3" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-06"/>
  </Instrmt>
  <MktSegGrp MktSegID="19478">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="491139" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-05" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41222170" AltIDSrc="M"/>
    <AID AltID="XF0000046RY9" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-05"/>
  </Instrmt>
  <MktSegGrp MktSegID="19478">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19479" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B2" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160PY0" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="0.587">
  <Instrmt ID="483879" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-13" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41287705" AltIDSrc="M"/>
    <AID AltID="XF00000407C1" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-13"/>
  </Instrmt>
  <MktSegGrp MktSegID="19479">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="493745" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-12" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41287706" AltIDSrc="M"/>
    <AID AltID="XF0000049F05" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-12"/>
  </Instrmt>
  <MktSegGrp MktSegID="19479">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19480" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B3" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160PZ7" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="0.777">
  <Instrmt ID="483880" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-21" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41353241" AltIDSrc="M"/>
    <AID AltID="XF00000407D9" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-21"/>
  </Instrmt>
  <MktSegGrp MktSegID="19480">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="495690" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-19" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41353242" AltIDSrc="M"/>
    <AID AltID="XF000004B602" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-19"/>
  </Instrmt>
  <MktSegGrp MktSegID="19480">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19481" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B4" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160P05" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="1.11">
  <Instrmt ID="478944" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-05-23" MMY="201705" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41418776" AltIDSrc="M"/>
    <AID AltID="XF000003VLD7" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-05-23"/>
  </Instrmt>
  <MktSegGrp MktSegID="19481">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="488484" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-28" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41418777" AltIDSrc="M"/>
    <AID AltID="XF0000044BK7" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-28"/>
  </Instrmt>
  <MktSegGrp MktSegID="19481">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19482" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B5" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160P13" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="483881" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-29" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41484313" AltIDSrc="M"/>
    <AID AltID="XF00000407E7" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-29"/>
  </Instrmt>
  <MktSegGrp MktSegID="19482">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="491783" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-06" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41484314" AltIDSrc="M"/>
    <AID AltID="XF0000047E32" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-06"/>
  </Instrmt>
  <MktSegGrp MktSegID="19482">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
  </Batch>
</FIXML>
</code>```

And this is my XSLT code,

```<code><xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                          xmlns:x="http://www.fixprotocol.org/FIXML-5-0-SP2"
                          xsi:schemaLocation="http://www.fixprotocol.org/FIXML-5-0-SP2 fixml-main-5-0-SP2_.xsd"
                          xmlns:math="http://www.w3.org/2005/xpath-functions/math"
                          exclude-result-prefixes="xs math">

  <xsl:mode streamable="yes"/>
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'"'" />
  <xsl:param name="break" select="'\n'" />

  <xsl:template match="x:PxRngRules">

<xsl:value-of select="concat($quote, normalize-space(@PxRngRuleID), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@PxRngProdCmplx), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@StartPxRng), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@EndPxRng), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@PxRngValu), $quote)" /><xsl:value-of select="$delim" />
</code>```

Problem 1: I am trying to add below code to get the attribute names as column names

```<code> <xsl:template match="/">
   <xsl:text>PxRngRuleID,PxRngProdCmplx,StartPxRng,EndPxRng,PxRngValu</xsl:text>
<xsl:text>\n</xsl:text>
  </xsl:template>
</code>```

But what I am getting is all the column names but not the values.

This is the sample output what I am getting after adding the above code before xsl:template.

```<code>   PxRngRuleID  PxRngProdCmplx  StartPxRng  EndPxRng    PxRngValu
   PxRngRuleID  PxRngProdCmplx  StartPxRng  EndPxRng    PxRngValu
   PxRngRuleID  PxRngProdCmplx  StartPxRng  EndPxRng    PxRngValu
</code>```

Problem 2: If I want to add some more columns of the parent tag attributes, then what are all the changes I have to do ?
for example if I want to add the another column with "QtSideInd" in  parent tag and "MktSegID" in  tag.

I have tried with below, but not able to get the values,

```<code> <xsl:value-of select="concat($quote, normalize-space(../@QtSideInd), $quote)" /><xsl:value-of select="$delim" />
 <xsl:value-of select="concat($quote, normalize-space(../../@MktSegID), $quote)" /><xsl:value-of select="$delim" />
</code>```

This is my java code...

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

  public class ChunkXSLT {

public static int transform(InputStream is, OutputStream os, Transformer transformer, QName name) throws XMLStreamException, TransformerException {
    long time1 = System.nanoTime();
    // Open input & output files
    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    XMLStreamReader reader = factory.createXMLStreamReader(is);
    // In case you want to check which implementation is used.
    // Woodstox is a bit faster, but not worth adding extra dependency.

    Result result = new StreamResult(os);

    int count = 0;
    while (reader.hasNext()) {
        if (reader.getEventType() == XMLStreamReader.START_ELEMENT && name.equals(reader.getName())) {
            // System.out.println("FOUND " + count);
            count++;
            transformer.transform(new StAXSource(reader), result);
            if (count % 1000 == 0) {
                long time2 = System.nanoTime();
                double ms = (time2 - time1) / 1000000.0;
                System.out.format("Time=%.2fms Rows=%d%n", ms, count);
            }
        } else if (reader.getEventType() == XMLStreamReader.START_ELEMENT) {
//                    System.out.println("Start "+reader.getName()+" != "+name);
        }
        reader.next();
    }
    long time2 = System.nanoTime();
    double ms = (time2 - time1) / 1000000.0;
    System.out.format("Total Time=%.2fms Total rows=%d%n", ms, count);
    return count;
}

public static void main(String arg[]) throws Exception {
    // Parse command line options
    File xsltFile;
    File inputFile;
    File outputFile;
    String tagName;
    String namespace;
    try {
        String xsltFileName = parse("-x", arg, "XSLT sheet", true);
        String inputFileName = parse("-f", arg, "Input file", true);
        String outputFileName = parse("-o", arg, "Output file", true);
        tagName = parse("-t", arg, "Tag name", true);
        namespace = parse("-n", arg, "Tag Namespace URL", false);
        xsltFile = new File(xsltFileName);
        inputFile = new File(inputFileName);
        outputFile = new File(outputFileName);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.println("Syntax: ChunkXSLT -f <input file> -o <output file> -x <XSLT stylesheet> -t <Tag name> [-n <namespace URL>]");
        System.err.println("Will split given file on given tag with given namespace.");
        System.err.println("Will process contents of each tag using given XSLT.");
        System.exit(1);
        return;
    }
    if (!xsltFile.exists()) {
        System.err.println("File not found " + xsltFile.getAbsolutePath());
        System.exit(1);
    }
    if (!inputFile.exists()) {
        System.err.println("File not found " + inputFile.getAbsolutePath());
        System.exit(1);
    }

    // Open XSLT stylesheet
    StreamSource stylesource = new StreamSource(xsltFile);
    Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);

    // Create XML tag name which is used to break up XML into rows
    final QName name;
    if (namespace != null) {
        name = new QName(namespace, tagName);
    } else {
        name = new QName(tagName);
    }
    System.out.println("Will look for tag " + name + " in namespace " + namespace);

    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
        // Open input & output files
        fis = new FileInputStream(inputFile);
        fos = new FileOutputStream(outputFile);
        transform(fis, fos, transformer, name);
    } finally {
        if (fos != null) {
            fos.close();
        }
        if (fis != null) {
            fis.close();
        }
    }
}

// Teo - inefficient, but who cares
private static String parse(String option, String[] arg, String desc, boolean required) throws ParseException {
    for (int i = 0; i < arg.length; i++) {
        if (option.equals(arg[i])) {
            if (i + 1 < arg.length) {
                String value = arg[i + 1].trim();
                return value;
            } else {
                throw new ParseException(option + " must be followed by an argument", i);
            }
        }
    }
    if (required) {
        throw new ParseException(desc + " is required", 0);
    } else {
        return null;
    }
}
}
</code>```

答:
Change

```<code> <xsl:template match="/">
   <xsl:text>PxRngRuleID,PxRngProdCmplx,StartPxRng,EndPxRng,PxRngValu</xsl:text>
<xsl:text>\n</xsl:text>
  </xsl:template>
</code>```

to

```<code> <xsl:template match="/">
   <xsl:text>PxRngRuleID,PxRngProdCmplx,StartPxRng,EndPxRng,PxRngValu</xsl:text>
   <xsl:text>\n</xsl:text>
   <xsl:apply-templates select="descendant::x:PxRngRules"/>
  </xsl:template>
</code>```

to make sure your those elements are processed by the template you have written.

Body:
This is my sample xml file,

<?xml version="1.0" encoding="ISO-8859-1"?>
<FIXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.fixprotocol.org/FIXML-5-0-SP2" xsi:schemaLocation="http://www.fixprotocol.org/FIXML-5-0-SP2 fixml-main-5-0-SP2_.xsd" s="2012-04-23" v="FIX.5.0SP2">
  <Batch ID="RPTTA111PUBLI20170518">
<MktDef MktID="XEEE" MktSegID="19478" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B1" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160PX2" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="1.195">
  <Instrmt ID="483878" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-06" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41222169" AltIDSrc="M"/>
    <AID AltID="XF00000407B3" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-06"/>
  </Instrmt>
  <MktSegGrp MktSegID="19478">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="491139" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-05" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41222170" AltIDSrc="M"/>
    <AID AltID="XF0000046RY9" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-05"/>
  </Instrmt>
  <MktSegGrp MktSegID="19478">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19479" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B2" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160PY0" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="0.587">
  <Instrmt ID="483879" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-13" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41287705" AltIDSrc="M"/>
    <AID AltID="XF00000407C1" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-13"/>
  </Instrmt>
  <MktSegGrp MktSegID="19479">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="493745" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-12" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41287706" AltIDSrc="M"/>
    <AID AltID="XF0000049F05" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-12"/>
  </Instrmt>
  <MktSegGrp MktSegID="19479">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19480" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B3" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160PZ7" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="0.777">
  <Instrmt ID="483880" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-21" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41353241" AltIDSrc="M"/>
    <AID AltID="XF00000407D9" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-21"/>
  </Instrmt>
  <MktSegGrp MktSegID="19480">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="495690" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-19" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41353242" AltIDSrc="M"/>
    <AID AltID="XF000004B602" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-19"/>
  </Instrmt>
  <MktSegGrp MktSegID="19480">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19481" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B4" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160P05" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="1.11">
  <Instrmt ID="478944" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-05-23" MMY="201705" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41418776" AltIDSrc="M"/>
    <AID AltID="XF000003VLD7" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-05-23"/>
  </Instrmt>
  <MktSegGrp MktSegID="19481">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="488484" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-28" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41418777" AltIDSrc="M"/>
    <AID AltID="XF0000044BK7" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-28"/>
  </Instrmt>
  <MktSegGrp MktSegID="19481">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<MktDef MktID="XEEE" MktSegID="19482" EfctvBizDt="2017-05-22" NxtEfctvBizDt="2017-05-23" MktSeg="C1B5" MarketSegmentDesc="GERMAN INTRADAY CAP FUTURE" Sym="DE000A160P13" ParentMktSegmID="FENE" Ccy="EUR" MktSegStat="1" USFirmFlag="Y" PartID="10">
  <MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT"/>
  <BaseTrdgRules QtSideInd="1" FastMktPctg="0">
    <TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.001"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0"/>
    <QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1"/>
    <PxRngRules PxRngRuleID="178" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.5"/>
  </BaseTrdgRules>
  <MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.82" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.210" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.106" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.234" SvcLctnSubID2="59500"/>
  <MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.107" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.235" SvcLctnSubID2="59501"/>
</MktDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="483881" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-06-29" MMY="201706" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41484313" AltIDSrc="M"/>
    <AID AltID="XF00000407E7" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-06-29"/>
  </Instrmt>
  <MktSegGrp MktSegID="19482">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
<SecDef PriSetPx="0.001">
  <Instrmt ID="491783" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMCSX" MatDt="2017-07-06" MMY="201707" Mult="168" ValMeth="FUT" SettlMeth="C" PxPrcsn="3" MinPxIncr="0.001" MinPxIncrAmt="0.001">
    <AID AltID="41484314" AltIDSrc="M"/>
    <AID AltID="XF0000047E32" AltIDSrc="4"/>
    <Evnt EventTyp="7" Dt="2017-07-06"/>
  </Instrmt>
  <MktSegGrp MktSegID="19482">
    <SecTrdgRules>
      <BaseTrdgRules>
        <PxRngRules PxRngRuleID="178"/>
      </BaseTrdgRules>
    </SecTrdgRules>
  </MktSegGrp>
</SecDef>
  </Batch>
</FIXML>

And this is my XSLT code,

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                          xmlns:x="http://www.fixprotocol.org/FIXML-5-0-SP2"
                          xsi:schemaLocation="http://www.fixprotocol.org/FIXML-5-0-SP2 fixml-main-5-0-SP2_.xsd"
                          xmlns:math="http://www.w3.org/2005/xpath-functions/math"
                          exclude-result-prefixes="xs math">

  <xsl:mode streamable="yes"/>
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'"'" />
  <xsl:param name="break" select="'
'" />

  <xsl:template match="x:PxRngRules">

<xsl:value-of select="concat($quote, normalize-space(@PxRngRuleID), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@PxRngProdCmplx), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@StartPxRng), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@EndPxRng), $quote)" /><xsl:value-of select="$delim" />
<xsl:value-of select="concat($quote, normalize-space(@PxRngValu), $quote)" /><xsl:value-of select="$delim" />

Problem 1: I am trying to add below code to get the attribute names as column names

 <xsl:template match="/">
   <xsl:text>PxRngRuleID,PxRngProdCmplx,StartPxRng,EndPxRng,PxRngValu</xsl:text>
<xsl:text>
</xsl:text>
  </xsl:template>

But what I am getting is all the column names but not the values.

This is the sample output what I am getting after adding the above code before xsl:template.

   PxRngRuleID  PxRngProdCmplx  StartPxRng  EndPxRng    PxRngValu
   PxRngRuleID  PxRngProdCmplx  StartPxRng  EndPxRng    PxRngValu
   PxRngRuleID  PxRngProdCmplx  StartPxRng  EndPxRng    PxRngValu

Problem 2: If I want to add some more columns of the parent tag attributes, then what are all the changes I have to do ?
for example if I want to add the another column with "QtSideInd" in  parent tag and "MktSegID" in  tag.

I have tried with below, but not able to get the values,

 <xsl:value-of select="concat($quote, normalize-space(../@QtSideInd), $quote)" /><xsl:value-of select="$delim" />
 <xsl:value-of select="concat($quote, normalize-space(../../@MktSegID), $quote)" /><xsl:value-of select="$delim" />

This is my java code...

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

  public class ChunkXSLT {

public static int transform(InputStream is, OutputStream os, Transformer transformer, QName name) throws XMLStreamException, TransformerException {
    long time1 = System.nanoTime();
    // Open input & output files
    XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    XMLStreamReader reader = factory.createXMLStreamReader(is);
    // In case you want to check which implementation is used.
    // Woodstox is a bit faster, but not worth adding extra dependency.

    Result result = new StreamResult(os);

    int count = 0;
    while (reader.hasNext()) {
        if (reader.getEventType() == XMLStreamReader.START_ELEMENT && name.equals(reader.getName())) {
            // System.out.println("FOUND " + count);
            count++;
            transformer.transform(new StAXSource(reader), result);
            if (count % 1000 == 0) {
                long time2 = System.nanoTime();
                double ms = (time2 - time1) / 1000000.0;
                System.out.format("Time=%.2fms Rows=%d%n", ms, count);
            }
        } else if (reader.getEventType() == XMLStreamReader.START_ELEMENT) {
//                    System.out.println("Start "+reader.getName()+" != "+name);
        }
        reader.next();
    }
    long time2 = System.nanoTime();
    double ms = (time2 - time1) / 1000000.0;
    System.out.format("Total Time=%.2fms Total rows=%d%n", ms, count);
    return count;
}

public static void main(String arg[]) throws Exception {
    // Parse command line options
    File xsltFile;
    File inputFile;
    File outputFile;
    String tagName;
    String namespace;
    try {
        String xsltFileName = parse("-x", arg, "XSLT sheet", true);
        String inputFileName = parse("-f", arg, "Input file", true);
        String outputFileName = parse("-o", arg, "Output file", true);
        tagName = parse("-t", arg, "Tag name", true);
        namespace = parse("-n", arg, "Tag Namespace URL", false);
        xsltFile = new File(xsltFileName);
        inputFile = new File(inputFileName);
        outputFile = new File(outputFileName);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.println("Syntax: ChunkXSLT -f <input file> -o <output file> -x <XSLT stylesheet> -t <Tag name> [-n <namespace URL>]");
        System.err.println("Will split given file on given tag with given namespace.");
        System.err.println("Will process contents of each tag using given XSLT.");
        System.exit(1);
        return;
    }
    if (!xsltFile.exists()) {
        System.err.println("File not found " + xsltFile.getAbsolutePath());
        System.exit(1);
    }
    if (!inputFile.exists()) {
        System.err.println("File not found " + inputFile.getAbsolutePath());
        System.exit(1);
    }

    // Open XSLT stylesheet
    StreamSource stylesource = new StreamSource(xsltFile);
    Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);

    // Create XML tag name which is used to break up XML into rows
    final QName name;
    if (namespace != null) {
        name = new QName(namespace, tagName);
    } else {
        name = new QName(tagName);
    }
    System.out.println("Will look for tag " + name + " in namespace " + namespace);

    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
        // Open input & output files
        fis = new FileInputStream(inputFile);
        fos = new FileOutputStream(outputFile);
        transform(fis, fos, transformer, name);
    } finally {
        if (fos != null) {
            fos.close();
        }
        if (fis != null) {
            fis.close();
        }
    }
}

// Teo - inefficient, but who cares
private static String parse(String option, String[] arg, String desc, boolean required) throws ParseException {
    for (int i = 0; i < arg.length; i++) {
        if (option.equals(arg[i])) {
            if (i + 1 < arg.length) {
                String value = arg[i + 1].trim();
                return value;
            } else {
                throw new ParseException(option + " must be followed by an argument", i);
            }
        }
    }
    if (required) {
        throw new ParseException(desc + " is required", 0);
    } else {
        return null;
    }
}
}

Body:
Change

 <xsl:template match="/">
   <xsl:text>PxRngRuleID,PxRngProdCmplx,StartPxRng,EndPxRng,PxRngValu</xsl:text>
<xsl:text>&#xA;</xsl:text>
  </xsl:template>

to

 <xsl:template match="/">
   <xsl:text>PxRngRuleID,PxRngProdCmplx,StartPxRng,EndPxRng,PxRngValu</xsl:text>
   <xsl:text>&#xA;</xsl:text>
   <xsl:apply-templates select="descendant::x:PxRngRules"/>
  </xsl:template>

to make sure your those elements are processed by the template you have written.


问:
How to lowercase field name in pdi (pentaho)?
I'm actually new to PDI and i need to do some extract from csv however sometimes field name are in lowercase or uppercase.
I know how to modify it for rows but don't know how to do it for fields names.

Does exist a step to do it?

I tried ${fieldName}.lower(), lower(${fieldName}) in select value and javascript script  but without succes

thanks in advance

答:
The quick fix is to right-click the list of column provided by the CSV file input to copy/paste it back and forth into Excel (or whatever).

If you also have 150 input files, the step which changes dynamically the column names (and other metadata like type) is called Metadata Injection, Kettle doc. The Official doc gives details and examples.

Your specific case is covered in BizCubed. Download the sample near the end of the web page, unzip, load the ktr in PDI. You'll need to adapt the Fields step in the MetaDataInjection transformation. It is currently a DataGrid that you may change by a Javascript lowercase (or better a String operation), after having kept the first line only of your CSV (read with header NOT present, include the rownumber and Filter rownumber=1).


问:
Google Speech API streaming
I'm trying to connect my PBX IVR to Google Speech API using syncrecognize method, but since I need to record voice, send it to API, wait for response and process it back, is impossible to have a normal conversation or attempt to have a normal conversation/process voice using it for real time services.
Is there any other API is recommended? or is there a way to setup VoIP/Streaming to Google. Similar like Alexa/Google Home. I didnt find anything for RecognitionAudio object:

答:
Google Cloud Speech API service supports two different functions:

Non Streaming Recognition, assuming you provide the full audio to Google platform and after it is processed you receive the result

Streaming Recognition, allowing you to feed audio interactively (in real time) and to get notified about results (partial, interim, results and final results) while audio chunks are processed

Both the above operations can be:

Syncronous, execute the command and wait for result (suitable for standard recognition with short files)

Asyncronous, issue commands and wait to be notified/check for the specific command result (usually on a different thread or in a multhreading environment, mandatory mode for audio longer than one minute)

Streaming Recognition API is recomended for your application scenario, consider it is accessible only with Cloud Speech RPC API (google RPC), while Non Streaming Recognition API is available both with both Cloud Speech REST and RPC API.

We used AsyncStreamingRecognize in a similar application environment via gRPC API, the project was in C++, environment setup was quite long and complex (you need to download and build grpc, protoc and Google Speech API stubs/libraries for your environment). For the application we used as reference the examples available on Google Speech API Site, once the environment was ready it was quite simple to adapt the sample application logic to our specific scenario.

With streaming API you have limitations on audio encoding (not all encoding are supported) and the length of the audio processed (in streaming you can process up to 1 minute of speech), moreover, you can access the API only with a Service Account that must be enabled to use Speech API.

Title: Google Speech API streaming


问:
Unable to compatible Organize imports between eclipse and intellij Idea for inner classes
As below, eclipse and intellij idea working differently for inner class DBInputSplit

Eclipse:

```<code>import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat.DBInputSplit;
import org.apache.hadoop.mapreduce.lib.db.DBRecordReader;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;
</code>```

Intelliji Idea:

```<code>import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBRecordReader;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat.DBInputSplit;
</code>```

Here the order for DBInputSplit import differs.
Any suggestion? Can we make intelliji orderding as same as Eclipse ordering.

For eclipse, we are using natural ordering (i.e. com, java, javax, org)

答: You can setup import ordering in IDEA: Settings-> Editor-> Code Style-> Java-> Look at bottom section "Import Layout".</p>

Body:
As below, eclipse and intellij idea working differently for inner class DBInputSplit

Eclipse:

import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat.DBInputSplit;
import org.apache.hadoop.mapreduce.lib.db.DBRecordReader;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;

Intelliji Idea:

import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBRecordReader;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat.DBInputSplit;

Here the order for DBInputSplit import differs.
Any suggestion? Can we make intelliji orderding as same as Eclipse ordering.

For eclipse, we are using natural ordering (i.e. com, java, javax, org)


问:
Generating JSON from SQLAlchemy base class including subclases from relationship
I'm trying to generate the JSON of my SQLAlchemy classes, I followed this example:
https://blogs.gnome.org/danni/2013/03/07/generating-json-from-sqlalchemy-objects/

It’s working very fine, but now I want to include all the data of the subclasses generated by the relationship of SQLAchemy. I've tried several things, the last one is trying to iterate over the subclases but I don't know why the method subclasses doesn't return anything. This is the function tojson modified:

```<code>def tojson(self):
    res=self.columnitems
    for cls in self.__class__.__subclasses__():
        res[cls.__name__]=cls.tojson()
    return res
</code>```

Do you know any way to do it?

Thanks in advance

答:
I can't comment yet but based on the information provided I'm assuming you are trying to generate a json from your (related) sqlalchemy classes. You can use the marshmallow (https://marshmallow.readthedocs.io/en/latest/) for this.

The (quick) example below shows how you can generate a json using marshmallow of two related tables.

```<code>from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()

# Creating dummy classes...
class Owner(Base):
    __tablename__ = 'owner'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(250))
    interested_in_cars = Column('interest', Boolean)
    car = relationship('Car', uselist=False, back_populates="owner")

    def __init__(self, name, interested_in_cars, id):
        self.id = id
        self.name = name
        self.interested_in_cars = interested_in_cars

    def __repr__(self):
        return '< (id={id}) Owner: {name} - interested: {interested_in_cars} >'.format(id=self.id,
                                                                                name=self.name,
                                                                                interested_in_cars=self.interested_in_cars)

class Car(Base):
    __tablename__ = 'car'
    id = Column('id', Integer, primary_key=True)
    brand = Column(String(250))
    owner_id = Column(Integer, ForeignKey('owner.id'))
    owner = relationship('Owner', back_populates='car')

    def __init__(self, owner_id, brand):
        self.owner_id = owner_id
        self.brand = brand

    def __repr__(self):
        return '< Owner: {owner_id} - Car: {brand} >'.format(owner_id=self.owner_id, brand=self.brand)

engine = create_engine('sqlite:///')
session = sessionmaker()
session.configure(bind=engine)
ex_ses = session()
Base.metadata.create_all(engine)

owner_1 = Owner(interested_in_cars=True, name='Owner a', id=1)
owner_2 = Owner(interested_in_cars=False, name='Owner b', id=2)
ex_ses.add(owner_1)
ex_ses.add(owner_2)

# ID's - quick example
car_1 = Car(owner_id=1, brand='Car a')
car_2 = Car(owner_id=2, brand='Car b')
ex_ses.add(car_1)
ex_ses.add(car_2)

ex_ses.commit()

# Using marshmallow to generate the json
from marshmallow import Schema, fields, pprint

class OwnerShema(Schema):
    id = fields.Int()
    name = fields.String()
    interested_in_cars = fields.Boolean()
    car = fields.Nested('CarShema')

class CarShema(Schema):
    id = fields.Int()
    brand = fields.String()

# Example Owners and cars
owners_cars = ex_ses.query(Owner).all()
print('Owners and cars: ', owners_cars)
owners_cars_shema = OwnerShema()
pprint(owners_cars_shema.dump(owners_cars, many=True).data)
</code>```

For more information see the marshmallow documentation (link provided above).

Body:
I'm trying to generate the JSON of my SQLAlchemy classes, I followed this example:
https://blogs.gnome.org/danni/2013/03/07/generating-json-from-sqlalchemy-objects/

It’s working very fine, but now I want to include all the data of the subclasses generated by the relationship of SQLAchemy. I've tried several things, the last one is trying to iterate over the subclases but I don't know why the method subclasses doesn't return anything. This is the function tojson modified:

def tojson(self):
    res=self.columnitems
    for cls in self.__class__.__subclasses__():
        res[cls.__name__]=cls.tojson()
    return res

Do you know any way to do it?

Thanks in advance

Body:
I can't comment yet but based on the information provided I'm assuming you are trying to generate a json from your (related) sqlalchemy classes. You can use the marshmallow (https://marshmallow.readthedocs.io/en/latest/) for this.

The (quick) example below shows how you can generate a json using marshmallow of two related tables.

from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()

# Creating dummy classes...
class Owner(Base):
    __tablename__ = 'owner'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String(250))
    interested_in_cars = Column('interest', Boolean)
    car = relationship('Car', uselist=False, back_populates="owner")

    def __init__(self, name, interested_in_cars, id):
        self.id = id
        self.name = name
        self.interested_in_cars = interested_in_cars

    def __repr__(self):
        return '< (id={id}) Owner: {name} - interested: {interested_in_cars} >'.format(id=self.id,
                                                                                name=self.name,
                                                                                interested_in_cars=self.interested_in_cars)

class Car(Base):
    __tablename__ = 'car'
    id = Column('id', Integer, primary_key=True)
    brand = Column(String(250))
    owner_id = Column(Integer, ForeignKey('owner.id'))
    owner = relationship('Owner', back_populates='car')

    def __init__(self, owner_id, brand):
        self.owner_id = owner_id
        self.brand = brand

    def __repr__(self):
        return '< Owner: {owner_id} - Car: {brand} >'.format(owner_id=self.owner_id, brand=self.brand)

engine = create_engine('sqlite:///')
session = sessionmaker()
session.configure(bind=engine)
ex_ses = session()
Base.metadata.create_all(engine)

owner_1 = Owner(interested_in_cars=True, name='Owner a', id=1)
owner_2 = Owner(interested_in_cars=False, name='Owner b', id=2)
ex_ses.add(owner_1)
ex_ses.add(owner_2)

# ID's - quick example
car_1 = Car(owner_id=1, brand='Car a')
car_2 = Car(owner_id=2, brand='Car b')
ex_ses.add(car_1)
ex_ses.add(car_2)

ex_ses.commit()

# Using marshmallow to generate the json
from marshmallow import Schema, fields, pprint

class OwnerShema(Schema):
    id = fields.Int()
    name = fields.String()
    interested_in_cars = fields.Boolean()
    car = fields.Nested('CarShema')

class CarShema(Schema):
    id = fields.Int()
    brand = fields.String()

# Example Owners and cars
owners_cars = ex_ses.query(Owner).all()
print('Owners and cars: ', owners_cars)
owners_cars_shema = OwnerShema()
pprint(owners_cars_shema.dump(owners_cars, many=True).data)

For more information see the marshmallow documentation (link provided above).