问:
Flipping the order of a row
I'm trying to create An Array function that will reverse the order of a row of selected data.

```<code>Function Flip(R)

    Dim n as variant
    Dim i as long
    ReDim A(1, n)
    n = R.Rows.Columns.Count

    For i = 1 To n
        A(1, n - 1) = R.Cells(1, n)
    Next i
    Flip= A
End Function
</code>```

The goal of this is to be able to reverse the order of a row of cells. For example: if the cells were ordered 20, 30, 40, 120, then using this array function should return the values 120, 40, 30, 20.

I know I'm having problems on how to call the n value to rearrange the array order. I've also tried making it "A(n, 1)" but this doesn't work either.

答:
You were using n before you'd assigned it a value. Also, the array pointers weren't quite right. This should do it:

```<code>Function Flip(R As Range)

Dim n As Variant
Dim i As Long

n = R.Cells.Count
ReDim A(1 To 1, 1 To n)

For i = 1 To n
    A(1, 1 + n - i) = R.Cells(1, i).Value
Next i

Flip = A

End Function
</code>```

Title: Flipping the order of a row

Body:
I'm trying to create An Array function that will reverse the order of a row of selected data.

Function Flip(R)

    Dim n as variant
    Dim i as long
    ReDim A(1, n)
    n = R.Rows.Columns.Count

    For i = 1 To n
        A(1, n - 1) = R.Cells(1, n)
    Next i
    Flip= A
End Function

The goal of this is to be able to reverse the order of a row of cells. For example: if the cells were ordered 20, 30, 40, 120, then using this array function should return the values 120, 40, 30, 20.

I know I'm having problems on how to call the n value to rearrange the array order. I've also tried making it "A(n, 1)" but this doesn't work either.

Body:
You were using n before you'd assigned it a value. Also, the array pointers weren't quite right. This should do it:

Function Flip(R As Range)

Dim n As Variant
Dim i As Long

n = R.Cells.Count
ReDim A(1 To 1, 1 To n)

For i = 1 To n
    A(1, 1 + n - i) = R.Cells(1, i).Value
Next i

Flip = A

End Function


来源: stackexchange

问:
Hive json data explode option not exploding array
I am inserting Json data into Hive. this is the format -

```<code>A1 Array <
struct <
        product array <
                     struct <
                             dim1 array < struct <> >
                             dim2 array < struct <> >
                            >
                      >
       >>
</code>```

In the from table clause i am using explode as :

```<code>Lateral view outer explode(A1.product) t1 as prod Lateral view outer explode(prod.dim1) t2 as prod_d1 Lateral view outer explode(prod.dim2) t3 as prod_d2
</code>```

Sample data :

```<code>A1["product":[{"productsku":"p_dmf_qs:click: page load","v2productname":"Quality Score - click: page load","v2productcategory":"DMF","productvariant":"(not set)","productbrand":"xxxx","productrevenue":"1000","localproductrevenue":null,"productprice":"100","productquantity":"1","productrefundamount":null,"productlistname":"(not set)","dim1":[],"dim2":[]}]]
</code>```

when i call t2 and t3 in the select statement as prod_d1 and prod_d2, i am getting a struct in the result, not array.
Please help me. It is a nested struct. If i did not have the first product array, i could have referred this easily as A1.dim1 and A1.dim2 as two explode functions. Kindly help me out.

答:
```<code>select  t2.dim1,t2.dim2
...
Lateral view outer inline  (A1)         t1
Lateral view outer inline  (t1.product) t2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am inserting Json data into Hive. this is the format -

A1 Array <
struct <
        product array <
                     struct <
                             dim1 array < struct <> >
                             dim2 array < struct <> >
                            >
                      >
       >>

In the from table clause i am using explode as :

Lateral view outer explode(A1.product) t1 as prod Lateral view outer explode(prod.dim1) t2 as prod_d1 Lateral view outer explode(prod.dim2) t3 as prod_d2

Sample data :

A1["product":[{"productsku":"p_dmf_qs:click: page load","v2productname":"Quality Score - click: page load","v2productcategory":"DMF","productvariant":"(not set)","productbrand":"xxxx","productrevenue":"1000","localproductrevenue":null,"productprice":"100","productquantity":"1","productrefundamount":null,"productlistname":"(not set)","dim1":[],"dim2":[]}]]

when i call t2 and t3 in the select statement as prod_d1 and prod_d2, i am getting a struct in the result, not array.
Please help me. It is a nested struct. If i did not have the first product array, i could have referred this easily as A1.dim1 and A1.dim2 as two explode functions. Kindly help me out.


问:
Django Admin: add inlines dynamically
```<code>class MyTemplateAdmin(admin.ModelAdmin):
list_display = ('name')
search_fields = ['name']
inlines = [
    Template1Inline,
    Template2Inline,
    Template3Inline,
]
</code>```

This works fine. But what I need is to make it dynamic. Whenever the admin adds a new Template to the MyTemplate Model, that needs to be added to the inlines.

Is there a way to do this? Please comment if I am not clear enough on my question.
Thanks in advance!

答:
I'm not completely sure this is what you are looking for. You want inlines that are different instances of the same model?
One way of creating the inlines dynamically is with type() and adding them in get_inline_instances()</p>

```<code>class MyTemplateAdmin(admin.ModelAdmin):
    list_display = ('name')
    search_fields = ['name']
    inlines = [some_other_inline]

    def get_inline_instances(self, request, obj=None):
        new_inlines = []
        for inline in (Template, Template2,Template3, ...): # I don't know how you want to get these.
            attrs = {
                'model': MyTemplate,
                # 'extra': 1, Add extra attributes
            }
            # Create a new uninstanciated inline class
            new_inlines.append(type('{}Inline'.format(inline),
                                      (admin.TabularInline, ), attrs))

        # Add the dynamically created inlines along with the ordinary.
        self.inlines = self.inlines + new_inlines
        return super(CommunityAdmin, self).get_inline_instances(request, obj)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Django Admin: add inlines dynamically

Body:
class MyTemplateAdmin(admin.ModelAdmin):
list_display = ('name')
search_fields = ['name']
inlines = [
    Template1Inline,
    Template2Inline,
    Template3Inline,
]

This works fine. But what I need is to make it dynamic. Whenever the admin adds a new Template to the MyTemplate Model, that needs to be added to the inlines.

Is there a way to do this? Please comment if I am not clear enough on my question.
Thanks in advance!

Body:
I'm not completely sure this is what you are looking for. You want inlines that are different instances of the same model?
One way of creating the inlines dynamically is with type() and adding them in get_inline_instances()

class MyTemplateAdmin(admin.ModelAdmin):
    list_display = ('name')
    search_fields = ['name']
    inlines = [some_other_inline]

    def get_inline_instances(self, request, obj=None):
        new_inlines = []
        for inline in (Template, Template2,Template3, ...): # I don't know how you want to get these.
            attrs = {
                'model': MyTemplate,
                # 'extra': 1, Add extra attributes
            }
            # Create a new uninstanciated inline class
            new_inlines.append(type('{}Inline'.format(inline),
                                      (admin.TabularInline, ), attrs))

        # Add the dynamically created inlines along with the ordinary.
        self.inlines = self.inlines + new_inlines
        return super(CommunityAdmin, self).get_inline_instances(request, obj)


问:
Structs and Multidimensional Array Global Declaration in C
My intention is to create a multidimensional array of structs. However, the problem is that it needs to be a global variable, but I don't know the size at compile time (it is user input).

Lets say I have a Struct like so:

```<code>typedef struct abc abc;
struct abc {
  int test;
  char* color;
};
</code>```

I need to declare a global multidimensional array for this.

```<code>abc** board;
</code>```

Within a function later in the code, I then want to initialise the size and fill it with values:

```<code>board[height][width];

for(int i = 0; i < height; i++) {
    for(int x = 0; x <width; x++) {
        board[i][x].test = 0;
    }
}
</code>```

Where am I going wrong? It seem's this part is the issue: board[height][width] ?

答:
Answered by @xing

malloc could be used to allocate memory to board and it could be accessed using board[x][y] notation

board = malloc ( height * sizeof ( *board)); then in a loop allocate memory as board[i] = malloc ( width * sizeof ( **board));. the structure also has a char * that will need to be allocated

Body:
My intention is to create a multidimensional array of structs. However, the problem is that it needs to be a global variable, but I don't know the size at compile time (it is user input).

Lets say I have a Struct like so:

typedef struct abc abc;
struct abc {
  int test;
  char* color;
};

I need to declare a global multidimensional array for this.

abc** board;

Within a function later in the code, I then want to initialise the size and fill it with values:

board[height][width];

for(int i = 0; i < height; i++) {
    for(int x = 0; x <width; x++) {
        board[i][x].test = 0;
    }
}

Where am I going wrong? It seem's this part is the issue: board[height][width] ?


问:
Microseconds to human readable output
I have a need to convert microseconds to a human readable format. While I would be able convert it to HH:MM:SS.MS, I'm not sure the best way to strip the 00:'s if present I would like work with these

```<code>input = [ 12040000, 60042000, 15582000000 ]
output = [ '12.04', '1:00.42', '4:19:27' ]

function formatMark(mu) {
    var timeList = []
    var ms = mu / 1000
    var time = new Date(ms)

    var ms = time.getMilliseconds()
    var ss = time.getSeconds()
    var mm = time.getMinutes()
    var hh = time.getHours()

    if (ms > 1) timeList.push(ms) //
    if (ss > 1) timeList.push(ss) //
    if (mm > 1) timeList.push(mm) //
    if (hh > 1) timeList.push(hh) //

    return { hh + ':' + mm + ':' + ss + '.' + ms }

 }
</code>```

Unfortunately the code above doesn't work, probably for multiple reasons in which I'd be better off knowing, but I really just need a conventional and readable output. Any tips / suggestions are appreciated!

答:
Unfortunately the code above doesn't work, probably for multiple
  reasons in which I'd be better off knowing,

Syntax of your return statement is wrong

Try replacing your return statement with

```<code>return { hh : hh, mm : mm, ss : ss, ms : ms }
</code>```

Finally, use the output of formatMark as

```<code>var output = formatMark(157442234333332221);
var finalOutput = Object.keys( output ).map( function( key ){ return key + ":" + output[key] } ).join(",");
</code>```

Title: Microseconds to human readable output

Body:
I have a need to convert microseconds to a human readable format. While I would be able convert it to HH:MM:SS.MS, I'm not sure the best way to strip the 00:'s if present I would like work with these

input = [ 12040000, 60042000, 15582000000 ]
output = [ '12.04', '1:00.42', '4:19:27' ]

function formatMark(mu) {
    var timeList = []
    var ms = mu / 1000
    var time = new Date(ms)

    var ms = time.getMilliseconds()
    var ss = time.getSeconds()
    var mm = time.getMinutes()
    var hh = time.getHours()

    if (ms > 1) timeList.push(ms) //
    if (ss > 1) timeList.push(ss) //
    if (mm > 1) timeList.push(mm) //
    if (hh > 1) timeList.push(hh) //

    return { hh + ':' + mm + ':' + ss + '.' + ms }

 }

Unfortunately the code above doesn't work, probably for multiple reasons in which I'd be better off knowing, but I really just need a conventional and readable output. Any tips / suggestions are appreciated!

Body:
Unfortunately the code above doesn't work, probably for multiple
  reasons in which I'd be better off knowing,

Syntax of your return statement is wrong

Try replacing your return statement with

return { hh : hh, mm : mm, ss : ss, ms : ms }

Finally, use the output of formatMark as

var output = formatMark(157442234333332221);
var finalOutput = Object.keys( output ).map( function( key ){ return key + ":" + output[key] } ).join(",");


问:
Get and Set methods for Maps in Erlang
I have started to learn Erlang, so I'm a noob in functional programming.

I think that I can't have "global variables" that I could use in different processes of the same module. Therefore, I have thought that I could use maps to store data (counters, status,...) and manage/update it.

My question is: Is there any way to do get/set methods (similar to the methods that we can find in Java, C#,...) to access to maps data without writing them in files? Or is there another way to have these data globally.

Thank you!

答:
Just forget OOP.

In this approach, other functional programmers can't understand your code and maintenance is so hard.

If you want to keep data in one process, the best way is learning implementation of the Generic Server and use your data instead of state of your gen_server.

If you want to keep some data and share them to some processes:

In one Erlang node use ETS (Erlang Term Storage) or DETS (Disk Erlang Term Storage).

In cluster of nodes use Mnesia DB.

Title: Get and Set methods for Maps in Erlang


问:
VB.NET - Insert Date Into Mysql Database Error
i'm trying to insert date(only) from dateTimePicker to mysql database, but error happen

the format i use

```<code>DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")
</code>```

in my mysql database, i use DATE data type

when i try to display date in vb it show

the date format displaying correctly, yyyy/MM/dd but still, i can't insert it to my database.

EDIT:
my code to insert into database

```<code> Dim namaBarang, satuan, sql As String
        Dim idtoko = formStok.pIdToko
        Dim tglTransaksi = DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")
        Dim qty, idBarang As Integer
        Dim noTrans = Label2.Text
        strcon.Open()
        For x As Integer = 0 To dataListTransaksi.Rows.Count - 1 Step 1
            namaBarang = dataListTransaksi.Rows(x).Cells(2).Value.ToString
            idBarang = dataListTransaksi.Rows(x).Cells(1).Value.ToString
            satuan = dataListTransaksi.Rows(x).Cells(3).Value.ToString
            qty = dataListTransaksi.Rows(x).Cells(4).Value.ToString

            sql = "BEGIN;
                    INSERT
            INTO
                    `tbl_transaksi`(
                    `tbl_transaksi`.`no_transaksi`,
                    `tbl_transaksi`.`tgl_transaksi`,
                    `tbl_transaksi`.`id_toko`
                    )
                VALUES(" & noTrans & ", " & tglTransaksi & ", " & idtoko & ");
                INSERT
            INTO
                    `tbl_transaksi_detail`(
                    `tbl_transaksi_detail`.`no_transaksi`,
                    `tbl_transaksi_detail`.`id_barang`,
                    `tbl_transaksi_detail`.`qty`,
                    `tbl_transaksi_detail`.`unit`
                    )
                VALUES(" & noTrans & ", " & idBarang & ", " & qty & ", '" & satuan & "');
                COMMIT;"

            Try

                'HOLDS THE DATA TO BE EXECUTED
                With cmd
                    .Connection = strcon
                    .CommandText = sql
                    'EXECUTE THE DATA
                    result = cmd.ExecuteNonQuery
                    'CHECKING IF THE DATA HAS EXECUTED OR NOT AND THEN THE POP UP MESSAGE WILL APPEAR
                    If result = 0 Then
                        MsgBox("FAILED TO SAVE THE DATA", MsgBoxStyle.Information)
                    Else
                        MsgBox("DATA HAS BEEN SAVE IN THE DATABASE")
                    End If
                End With
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

        Next
        strcon.Close()
</code>```

答:
i forgot to add single quote's around date value

```<code>sql = "BEGIN;
                    INSERT
            INTO
                    `tbl_transaksi`(
                    `tbl_transaksi`.`no_transaksi`,
                    `tbl_transaksi`.`tgl_transaksi`,
                    `tbl_transaksi`.`id_toko`
                    )
                VALUES(" & noTrans & ", " & tglTransaksi & "<<==THE PROBLEM IS HERE, " & idtoko & ");
                INSERT
            INTO
                    `tbl_transaksi_detail`(
                    `tbl_transaksi_detail`.`no_transaksi`,
                    `tbl_transaksi_detail`.`id_barang`,
                    `tbl_transaksi_detail`.`qty`,
                    `tbl_transaksi_detail`.`unit`
                    )
                VALUES(" & noTrans & ", " & idBarang & ", " & qty & ", '" & satuan & "');
                COMMIT;"
</code>```

so i change it

VALUES(" & noTrans & ", '" & tglTransaksi & "', " & idtoko & ");

solved!

Body:
i'm trying to insert date(only) from dateTimePicker to mysql database, but error happen

the format i use

DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")

in my mysql database, i use DATE data type

when i try to display date in vb it show

the date format displaying correctly, yyyy/MM/dd but still, i can't insert it to my database.

EDIT:
my code to insert into database

 Dim namaBarang, satuan, sql As String
        Dim idtoko = formStok.pIdToko
        Dim tglTransaksi = DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")
        Dim qty, idBarang As Integer
        Dim noTrans = Label2.Text
        strcon.Open()
        For x As Integer = 0 To dataListTransaksi.Rows.Count - 1 Step 1
            namaBarang = dataListTransaksi.Rows(x).Cells(2).Value.ToString
            idBarang = dataListTransaksi.Rows(x).Cells(1).Value.ToString
            satuan = dataListTransaksi.Rows(x).Cells(3).Value.ToString
            qty = dataListTransaksi.Rows(x).Cells(4).Value.ToString

            sql = "BEGIN;
                    INSERT
            INTO
                    `tbl_transaksi`(
                    `tbl_transaksi`.`no_transaksi`,
                    `tbl_transaksi`.`tgl_transaksi`,
                    `tbl_transaksi`.`id_toko`
                    )
                VALUES(" & noTrans & ", " & tglTransaksi & ", " & idtoko & ");
                INSERT
            INTO
                    `tbl_transaksi_detail`(
                    `tbl_transaksi_detail`.`no_transaksi`,
                    `tbl_transaksi_detail`.`id_barang`,
                    `tbl_transaksi_detail`.`qty`,
                    `tbl_transaksi_detail`.`unit`
                    )
                VALUES(" & noTrans & ", " & idBarang & ", " & qty & ", '" & satuan & "');
                COMMIT;"

            Try

                'HOLDS THE DATA TO BE EXECUTED
                With cmd
                    .Connection = strcon
                    .CommandText = sql
                    'EXECUTE THE DATA
                    result = cmd.ExecuteNonQuery
                    'CHECKING IF THE DATA HAS EXECUTED OR NOT AND THEN THE POP UP MESSAGE WILL APPEAR
                    If result = 0 Then
                        MsgBox("FAILED TO SAVE THE DATA", MsgBoxStyle.Information)
                    Else
                        MsgBox("DATA HAS BEEN SAVE IN THE DATABASE")
                    End If
                End With
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

        Next
        strcon.Close()

Body:
i forgot to add single quote's around date value

sql = "BEGIN;
                    INSERT
            INTO
                    `tbl_transaksi`(
                    `tbl_transaksi`.`no_transaksi`,
                    `tbl_transaksi`.`tgl_transaksi`,
                    `tbl_transaksi`.`id_toko`
                    )
                VALUES(" & noTrans & ", " & tglTransaksi & "<<==THE PROBLEM IS HERE, " & idtoko & ");
                INSERT
            INTO
                    `tbl_transaksi_detail`(
                    `tbl_transaksi_detail`.`no_transaksi`,
                    `tbl_transaksi_detail`.`id_barang`,
                    `tbl_transaksi_detail`.`qty`,
                    `tbl_transaksi_detail`.`unit`
                    )
                VALUES(" & noTrans & ", " & idBarang & ", " & qty & ", '" & satuan & "');
                COMMIT;"

so i change it

VALUES(" & noTrans & ", '" & tglTransaksi & "', " & idtoko & ");

solved!


问:
Laravel custom error page if authorization fails
I am trying to show a custom 403 file in laravel when authorization fails in my edit request.

I tried forbiddenResponse() but as it turns out it has been eliminated.

Then I tried failedauthorization() but this does not redirect as well and allows me to edit.

here is my request file

```<code>public function authorize()
{
  $job_posting_id = $this->route('id');

  $job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();

  if($job_posting){
    return true;
  }

  return false;
}

public function failedAuthorization()
{

  return redirect('errors.dashboard.parent.403');
}
</code>```

I have a folder called errors and inside there I have dashboard folder and parent where the error file is located.

How can I redirect to that page if authorization fails?

答:
```<code>public function authorize()
{
  $job_posting_id = $this->route('id');

  $job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();

  if($job_posting){
    return true;
  }

  return redirect('/error');
}

public function failedAuthorization()
{

  return view('errors.dashboard.parent.403');
}
</code>```

<p>In your route </p>

```<code>Route::get('error', 'YourController@failedAuthorization');
</code>```

Body:
I am trying to show a custom 403 file in laravel when authorization fails in my edit request.

I tried forbiddenResponse() but as it turns out it has been eliminated.

Then I tried failedauthorization() but this does not redirect as well and allows me to edit.

here is my request file

public function authorize()
{
  $job_posting_id = $this->route('id');

  $job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();

  if($job_posting){
    return true;
  }

  return false;
}

public function failedAuthorization()
{

  return redirect('errors.dashboard.parent.403');
}

I have a folder called errors and inside there I have dashboard folder and parent where the error file is located.

How can I redirect to that page if authorization fails?

Body:
public function authorize()
{
  $job_posting_id = $this->route('id');

  $job_posting = Job_postings::where('id', $job_posting_id)->where('user_id', user()->id)->exists();

  if($job_posting){
    return true;
  }

  return redirect('/error');
}

public function failedAuthorization()
{

  return view('errors.dashboard.parent.403');
}

In your route

Route::get('error', 'YourController@failedAuthorization');


问:
Ruby on rails rake db error
I have cloned a project and ran it locally on my machine. I'm getting an error when i run rake db:migrate.

Can anyone please explain this to me? I have attached an image showing the error I am receiving.

Error Received

答:
Try following command:</p>

```<code>rake db:scheme:load
</code>```

Title: Ruby on rails rake db error

Body:
Try following command:

rake db:scheme:load


问:
python regex to match both english and telugu/devanagari words
I need some help in getting words from a mix of language it contains english and telugu language, here is my code so far

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
sentence="hello world యూనియన్ యూనియన్"
sentence=sentence.decode('utf-8')
for m in re.finditer(ur'(\w|\’\w|\'\w)+', sentence, re.UNICODE):
    start, end = m.span()
    word = m.group().encode('utf-8')
    print start, end, word
</code>```

the result i'm expecting is

```<code>0 5 hello
6 11 world
11 17 యూనియన్
17 23 యూనియన్
</code>```

but the result i get is

```<code>0 5 hello
6 11 world
12 13 య
14 15 న
16 18 యన
20 21 య
22 23 న
24 26 యన
</code>```

the code split every character of the langauge and give independent start and end lengths. is there any way that i can get the result in the above format as words instead of characters

ContentLicense: CC BY-SA 4.0

Body:
I need some help in getting words from a mix of language it contains english and telugu language, here is my code so far

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
sentence="hello world యూనియన్ యూనియన్"
sentence=sentence.decode('utf-8')
for m in re.finditer(ur'(\w|\’\w|\'\w)+', sentence, re.UNICODE):
    start, end = m.span()
    word = m.group().encode('utf-8')
    print start, end, word

the result i'm expecting is

0 5 hello
6 11 world
11 17 యూనియన్
17 23 యూనియన్

but the result i get is

0 5 hello
6 11 world
12 13 య
14 15 న
16 18 యన
20 21 య
22 23 న
24 26 యన

the code split every character of the langauge and give independent start and end lengths. is there any way that i can get the result in the above format as words instead of characters

Body:
The point is that \w does not match diacritic symbols.

You may either use PyPi regex library and include \p{M} into your pattern, or define the cmobining marks Unicode ranges the way it is done in XRegExp package for JavaScript:

import re
combining_marks_bmp = u'\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F'
combining_marks_astral = u'\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDEAB-\uDEB7\uDF1D-\uDF2B]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDCA-\uDDCC\uDE2C-\uDE37\uDEDF-\uDEEA\uDF00-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD82F[\uDC9D\uDC9E]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]'
pat = ur'(\w|’\w|\'\w|[{}]|{})+'.format(combining_marks_bmp, combining_marks_astral)
sentence="hello world యూనియన్ యూనియన్"
sentence=sentence.decode('utf-8')
for m in re.finditer(pat, sentence, re.UNICODE):
    start, end = m.span()
    word = m.group().encode('utf-8')
    print start, end, word

See the Python demo


问:
DynamicReports crosstab report column grouping breaks after calling setDataPreSorted(true)
I'm using crosstab report and after applying row and column sorting, it breaks column grouping.
I call setDataPreSorted(true) on crosstab and SortBuilder for row and column:

```<code>SortBuilder rowSortBuilder = asc(field("rowOrder", Integer.class));
SortBuilder columnSortBuilder = asc(field("colOrder", Integer.class));
report.sortBy(rowSortBuilder, columnSortBuilder)
</code>```

Here's how it supposed to look:

But the column grouping breaks and it looks like this:

Here's my full code:

```<code>import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import static net.sf.dynamicreports.report.builder.DynamicReports.asc;
import static net.sf.dynamicreports.report.builder.DynamicReports.cmp;
import static net.sf.dynamicreports.report.builder.DynamicReports.ctab;
import static net.sf.dynamicreports.report.builder.DynamicReports.field;
import static net.sf.dynamicreports.report.builder.DynamicReports.report;
import static net.sf.dynamicreports.report.builder.DynamicReports.stl;
import net.sf.dynamicreports.report.builder.SortBuilder;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabColumnGroupBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabMeasureBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabRowGroupBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.Calculation;
import net.sf.dynamicreports.report.constant.HorizontalTextAlignment;
import net.sf.dynamicreports.report.constant.PageOrientation;
import net.sf.dynamicreports.report.constant.PageType;
import net.sf.dynamicreports.report.constant.VerticalTextAlignment;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class CrosstabGroupTest {

    public JasperReportBuilder build() throws DRException {

        JasperReportBuilder report = report();

        // styles
        String reportFont = "Roboto";
        int cellPadding = 3;

        StyleBuilder headerStyleCenter = stl.style().setFontName(reportFont).setFontSize(10).setBold(true)
            .setBorder(stl.pen1Point()).setPadding(cellPadding)
            .setHorizontalTextAlignment(HorizontalTextAlignment.CENTER)
            .setVerticalTextAlignment(VerticalTextAlignment.MIDDLE);

        StyleBuilder rowStyleData = stl.style().setFontName(reportFont).setFontSize(10)
                .setBorder(stl.pen1Point()).setPadding(cellPadding)
                .setHorizontalTextAlignment(HorizontalTextAlignment.CENTER)
                .setVerticalTextAlignment(VerticalTextAlignment.MIDDLE);

        // row groups
        CrosstabRowGroupBuilder<String> rowGroupItem = ctab.rowGroup("product", String.class).setShowTotal(false)
                .setHeaderStyle(rowStyleData).setHeaderWidth(120);
        CrosstabRowGroupBuilder<String> rowGroupUnit = ctab.rowGroup("unit", String.class).setShowTotal(false)
                .setHeaderStyle(rowStyleData).setHeaderWidth(50);
        CrosstabRowGroupBuilder<String> rowGroupDate = ctab.rowGroup("date", String.class).setShowTotal(false)
                .setHeaderStyle(rowStyleData).setHeaderWidth(50);

        // column groups
        CrosstabColumnGroupBuilder col_type = ctab.columnGroup("branch", String.class).setTotalHeader("Total quantity")
                .setShowTotal(true).setHeaderStyle(rowStyleData);

        // measure
        CrosstabMeasureBuilder quantityMeasure = ctab.measure("", "amount", Double.class, Calculation.NOTHING).setTitleStyle(stl.style().setFontSize(0));

        CrosstabBuilder crosstab = ctab.crosstab()
                .setCellWidth(220)
                .addHeaderCell(cmp.horizontalList(
                        cmp.text("Product").setStyle(headerStyleCenter).setFixedWidth(120),
                        cmp.text("Unit").setStyle(headerStyleCenter).setFixedWidth(50),
                        cmp.text("Year").setStyle(headerStyleCenter).setFixedWidth(50)).
                        setHeight(13))
                .setCellStyle(rowStyleData).setCellWidth(60)
                .rowGroups(rowGroupItem, rowGroupUnit, rowGroupDate)
                .columnGroups(col_type)
                .measures(quantityMeasure)
                .setDataPreSorted(true);

        // data
        List<ProductQuantityData> dataList = new ArrayList<>();
        int rowOrder = 1;
        int colOrder = 1;
        dataList.add(new ProductQuantityData("Water", "litre", "2016.02", "Branch 1", 50d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "2017.02", "Branch 1", 150d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "diff", "Branch 1", 100d, rowOrder, colOrder));

        colOrder = 2;
        dataList.add(new ProductQuantityData("Water", "litre", "2016.02", "Branch 2", 150d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "2017.02", "Branch 2", 140d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "diff", "Branch 2", -10d, rowOrder, colOrder));

        rowOrder = 2;
        colOrder = 1;
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2016.02", "Branch 1", 80d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2017.02", "Branch 1", 75d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "diff", "Branch 1", -5d, rowOrder, colOrder));

        colOrder = 2;
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2016.02", "Branch 2", 77d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2017.02", "Branch 2", 77d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "diff", "Branch 2", 0d, rowOrder, colOrder));

        // sort
        SortBuilder rowSortBuilder = asc(field("rowOrder", Integer.class));
        SortBuilder columnSortBuilder = asc(field("colOrder", Integer.class));

        report
                .sortBy(rowSortBuilder, columnSortBuilder)
                .setPageFormat(PageType.A4, PageOrientation.LANDSCAPE)
                .setTemplate(Templates.reportTemplate)
                .title(Components.text("Product quantity by branch"))
                .summary(crosstab)
                .pageFooter(Components.pageXslashY())
                .setDataSource(new JRBeanCollectionDataSource(dataList));

        return report;
    }

    public static void main(String[] args) {
        CrosstabGroupTest design = new CrosstabGroupTest();
        try {
            JasperReportBuilder report = design.build();
            report.show();
        } catch (DRException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Here's my java bean code:

```<code>public class ProductQuantityData {

    private String product;
    private String unit;
    private String date;

    private String branch;
    private Double amount;

    private int rowOrder;
    private int colOrder;

    public ProductQuantityData(String product, String unit, String date, String branch, Double amount, int rowOrder, int colOrder) {
        this.product = product;
        this.date = date;
        this.unit = unit;
        this.branch = branch;
        this.amount = amount;
        this.rowOrder = rowOrder;
        this.colOrder = colOrder;
    }

    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getUnit() {
        return unit;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public int getRowOrder() {
        return rowOrder;
    }

    public void setRowOrder(int rowOrder) {
        this.rowOrder = rowOrder;
    }

    public int getColOrder() {
        return colOrder;
    }

    public void setColOrder(int colOrder) {
        this.colOrder = colOrder;
    }
}
</code>```

答:
Luckily found one helpful forum post.

Add the following 2 classes.

```<code>    public class CTOValueFormatter extends AbstractValueFormatter<String, String>{
        @Override
        public String format(String value, ReportParameters reportParameters) {
           return value.split("-")[1];
        }
    }

    public class CTOrderExpression extends AbstractComplexExpression<String> {

        public CTOrderExpression(String sortField, String showField) {
            addExpression(field(sortField, Integer.class));
            addExpression(field(showField, String.class));
        }

        @Override
        public String evaluate(List<?> list, ReportParameters rp) {
            return list.get(0) + "-" + list.get(1);
        }
    }
</code>```

And do not use .sortBy(rowSortBuilder, columnSortBuilder) and .setDataPreSorted(true).

Instead create a row-group-item with the following code.

```<code>CrosstabRowGroupBuilder<String> rowGroupItem = ctab.rowGroup(new CTOrderExpression("rowOrder", "product")).setShowTotal(false)
    .setHeaderStyle(rowStyleData)
    .setHeaderWidth(120)
    .setHeaderValueFormatter(new CTOValueFormatter());
</code>```

Also you can do same for the column-groups.

```<code>CrosstabColumnGroupBuilder col_type = ctab.columnGroup(new CTOrderExpression("colOrder", "branch")).setTotalHeader("Total quantity")
            .setShowTotal(true).setHeaderStyle(rowStyleData);
</code>```

Grab the full source code here.

Body:
I'm using crosstab report and after applying row and column sorting, it breaks column grouping.
I call setDataPreSorted(true) on crosstab and SortBuilder for row and column:

SortBuilder rowSortBuilder = asc(field("rowOrder", Integer.class));
SortBuilder columnSortBuilder = asc(field("colOrder", Integer.class));
report.sortBy(rowSortBuilder, columnSortBuilder)

Here's how it supposed to look:

But the column grouping breaks and it looks like this:

Here's my full code:

import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import static net.sf.dynamicreports.report.builder.DynamicReports.asc;
import static net.sf.dynamicreports.report.builder.DynamicReports.cmp;
import static net.sf.dynamicreports.report.builder.DynamicReports.ctab;
import static net.sf.dynamicreports.report.builder.DynamicReports.field;
import static net.sf.dynamicreports.report.builder.DynamicReports.report;
import static net.sf.dynamicreports.report.builder.DynamicReports.stl;
import net.sf.dynamicreports.report.builder.SortBuilder;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabColumnGroupBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabMeasureBuilder;
import net.sf.dynamicreports.report.builder.crosstab.CrosstabRowGroupBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.Calculation;
import net.sf.dynamicreports.report.constant.HorizontalTextAlignment;
import net.sf.dynamicreports.report.constant.PageOrientation;
import net.sf.dynamicreports.report.constant.PageType;
import net.sf.dynamicreports.report.constant.VerticalTextAlignment;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class CrosstabGroupTest {

    public JasperReportBuilder build() throws DRException {

        JasperReportBuilder report = report();

        // styles
        String reportFont = "Roboto";
        int cellPadding = 3;

        StyleBuilder headerStyleCenter = stl.style().setFontName(reportFont).setFontSize(10).setBold(true)
            .setBorder(stl.pen1Point()).setPadding(cellPadding)
            .setHorizontalTextAlignment(HorizontalTextAlignment.CENTER)
            .setVerticalTextAlignment(VerticalTextAlignment.MIDDLE);

        StyleBuilder rowStyleData = stl.style().setFontName(reportFont).setFontSize(10)
                .setBorder(stl.pen1Point()).setPadding(cellPadding)
                .setHorizontalTextAlignment(HorizontalTextAlignment.CENTER)
                .setVerticalTextAlignment(VerticalTextAlignment.MIDDLE);

        // row groups
        CrosstabRowGroupBuilder<String> rowGroupItem = ctab.rowGroup("product", String.class).setShowTotal(false)
                .setHeaderStyle(rowStyleData).setHeaderWidth(120);
        CrosstabRowGroupBuilder<String> rowGroupUnit = ctab.rowGroup("unit", String.class).setShowTotal(false)
                .setHeaderStyle(rowStyleData).setHeaderWidth(50);
        CrosstabRowGroupBuilder<String> rowGroupDate = ctab.rowGroup("date", String.class).setShowTotal(false)
                .setHeaderStyle(rowStyleData).setHeaderWidth(50);

        // column groups
        CrosstabColumnGroupBuilder col_type = ctab.columnGroup("branch", String.class).setTotalHeader("Total quantity")
                .setShowTotal(true).setHeaderStyle(rowStyleData);

        // measure
        CrosstabMeasureBuilder quantityMeasure = ctab.measure("", "amount", Double.class, Calculation.NOTHING).setTitleStyle(stl.style().setFontSize(0));

        CrosstabBuilder crosstab = ctab.crosstab()
                .setCellWidth(220)
                .addHeaderCell(cmp.horizontalList(
                        cmp.text("Product").setStyle(headerStyleCenter).setFixedWidth(120),
                        cmp.text("Unit").setStyle(headerStyleCenter).setFixedWidth(50),
                        cmp.text("Year").setStyle(headerStyleCenter).setFixedWidth(50)).
                        setHeight(13))
                .setCellStyle(rowStyleData).setCellWidth(60)
                .rowGroups(rowGroupItem, rowGroupUnit, rowGroupDate)
                .columnGroups(col_type)
                .measures(quantityMeasure)
                .setDataPreSorted(true);

        // data
        List<ProductQuantityData> dataList = new ArrayList<>();
        int rowOrder = 1;
        int colOrder = 1;
        dataList.add(new ProductQuantityData("Water", "litre", "2016.02", "Branch 1", 50d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "2017.02", "Branch 1", 150d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "diff", "Branch 1", 100d, rowOrder, colOrder));

        colOrder = 2;
        dataList.add(new ProductQuantityData("Water", "litre", "2016.02", "Branch 2", 150d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "2017.02", "Branch 2", 140d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Water", "litre", "diff", "Branch 2", -10d, rowOrder, colOrder));

        rowOrder = 2;
        colOrder = 1;
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2016.02", "Branch 1", 80d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2017.02", "Branch 1", 75d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "diff", "Branch 1", -5d, rowOrder, colOrder));

        colOrder = 2;
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2016.02", "Branch 2", 77d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "2017.02", "Branch 2", 77d, rowOrder, colOrder));
        dataList.add(new ProductQuantityData("Coffee bean", "kg", "diff", "Branch 2", 0d, rowOrder, colOrder));

        // sort
        SortBuilder rowSortBuilder = asc(field("rowOrder", Integer.class));
        SortBuilder columnSortBuilder = asc(field("colOrder", Integer.class));

        report
                .sortBy(rowSortBuilder, columnSortBuilder)
                .setPageFormat(PageType.A4, PageOrientation.LANDSCAPE)
                .setTemplate(Templates.reportTemplate)
                .title(Components.text("Product quantity by branch"))
                .summary(crosstab)
                .pageFooter(Components.pageXslashY())
                .setDataSource(new JRBeanCollectionDataSource(dataList));

        return report;
    }

    public static void main(String[] args) {
        CrosstabGroupTest design = new CrosstabGroupTest();
        try {
            JasperReportBuilder report = design.build();
            report.show();
        } catch (DRException e) {
            e.printStackTrace();
        }
    }
}

Here's my java bean code:

public class ProductQuantityData {

    private String product;
    private String unit;
    private String date;

    private String branch;
    private Double amount;

    private int rowOrder;
    private int colOrder;

    public ProductQuantityData(String product, String unit, String date, String branch, Double amount, int rowOrder, int colOrder) {
        this.product = product;
        this.date = date;
        this.unit = unit;
        this.branch = branch;
        this.amount = amount;
        this.rowOrder = rowOrder;
        this.colOrder = colOrder;
    }

    public String getProduct() {
        return product;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getUnit() {
        return unit;
    }

    public void setUnit(String unit) {
        this.unit = unit;
    }

    public String getBranch() {
        return branch;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public int getRowOrder() {
        return rowOrder;
    }

    public void setRowOrder(int rowOrder) {
        this.rowOrder = rowOrder;
    }

    public int getColOrder() {
        return colOrder;
    }

    public void setColOrder(int colOrder) {
        this.colOrder = colOrder;
    }
}

Body:
Luckily found one helpful forum post.

Add the following 2 classes.

    public class CTOValueFormatter extends AbstractValueFormatter<String, String>{
        @Override
        public String format(String value, ReportParameters reportParameters) {
           return value.split("-")[1];
        }
    }

    public class CTOrderExpression extends AbstractComplexExpression<String> {

        public CTOrderExpression(String sortField, String showField) {
            addExpression(field(sortField, Integer.class));
            addExpression(field(showField, String.class));
        }

        @Override
        public String evaluate(List<?> list, ReportParameters rp) {
            return list.get(0) + "-" + list.get(1);
        }
    }

And do not use .sortBy(rowSortBuilder, columnSortBuilder) and .setDataPreSorted(true).

Instead create a row-group-item with the following code.

CrosstabRowGroupBuilder<String> rowGroupItem = ctab.rowGroup(new CTOrderExpression("rowOrder", "product")).setShowTotal(false)
    .setHeaderStyle(rowStyleData)
    .setHeaderWidth(120)
    .setHeaderValueFormatter(new CTOValueFormatter());

Also you can do same for the column-groups.

CrosstabColumnGroupBuilder col_type = ctab.columnGroup(new CTOrderExpression("colOrder", "branch")).setTotalHeader("Total quantity")
            .setShowTotal(true).setHeaderStyle(rowStyleData);

Grab the full source code here.


答:
```<code>return abort('403')
</code>```

Laravel documentation:
https://laravel.com/docs/5.4/errors#http-exceptions

if you make everything like in docs, you'll achieve:

url will stay the same.

template resources/views/errors/403.blade.php will be shown.

aslo response will have Status Code:403 Forbidden

do you want change url into http://www.examlpe.com/error403 ?

return abort('403') doesn't make redirect. It just shows a client that error has occured.

In your case it is easier to show different content in single script, than different scripts. Try to leave single error script as an "entry point". And in that script change output for different users. Imagine that 403.blade.php is a layout for a number of 403 error pages.

Title: Laravel custom error page if authorization fails

Body:
return abort('403')

Laravel documentation:
https://laravel.com/docs/5.4/errors#http-exceptions

if you make everything like in docs, you'll achieve:

url will stay the same.

template resources/views/errors/403.blade.php will be shown.

aslo response will have Status Code:403 Forbidden

do you want change url into http://www.examlpe.com/error403 ?

return abort('403') doesn't make redirect. It just shows a client that error has occured.

In your case it is easier to show different content in single script, than different scripts. Try to leave single error script as an "entry point". And in that script change output for different users. Imagine that 403.blade.php is a layout for a number of 403 error pages.


问:
Primefaces Calendar with Converter doesn't update correctly upon ajax "valueChange" event
I want my p:calendar to work both by clicking on a date in the calendar popup, as well as by editing the date directly in the text input field.

This works fine:

```<code>        <p:calendar value="#{myBackingBean.date}">
            <p:ajax event="valueChange" listener="#{myBackingBean.updateDate()}" />
            <p:ajax event="dateSelect" listener="#{myBackingBean.selectDate()}" />
        </p:calendar>
</code>```

However, as soon as I add a converter (see below), the new date is no longer set for "valueChange" events (when the date is edited by keyboard in the text field), even though the new date is converted correctly, but the date that is set in the backing bean is the old value, not the new one I edited in the text field:

```<code>        <p:calendar value="#{myBackingBean.date}">
            <f:converter converterId="myLocalDateConverter"/>
            <p:ajax event="valueChange" listener="#{myBackingBean.updateDate()}" />
            <p:ajax event="dateSelect" listener="#{myBackingBean.selectDate()}" />
        </p:calendar>
</code>```

How can I get this to work together?

答: I found the cause of the problem: The converter was receiving text from the input field that it wasn't able to correctly convert. Apparently this leads to an interruption of the standard JSF lifecycle and the old value is set instead of the new one. With properly formatted input the whole thing works as expected.</p>

Body:
I want my p:calendar to work both by clicking on a date in the calendar popup, as well as by editing the date directly in the text input field.

This works fine:

However, as soon as I add a converter (see below), the new date is no longer set for "valueChange" events (when the date is edited by keyboard in the text field), even though the new date is converted correctly, but the date that is set in the backing bean is the old value, not the new one I edited in the text field:

            <f:converter converterId="myLocalDateConverter"/>

How can I get this to work together?


问:
Objective C Header with Implementation
So someone gave me their code to work on, and I noticed that their header files (specifically ViewController.h) have not only declared fields, but have initialized them. Take a look:

The funny thing is, this is all in my header (.h) file, but it's still compiling! Isn't this not allowed?

My implementation file (ViewController.m) imports this header file, so I know that it's getting compiled. Why is the compiler not saying this is wrong?

答: What you are doing here is a structure declaration and its syntax is correct as you posted abouve so there is nothing wrong here.</p>

Title: Objective C Header with Implementation


问:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'table_Name'
i've checked again and again , but couldn't find any error  </p>

```<code>private void Btn_Save_Click(object sender, EventArgs e)
    {

        SqlConnection c = new SqlConnection(conn);

                c.Open();
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    query = @"INSERT INTO '" + tbpg.Text + "' VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";

                }
        SqlCommand cmd = new SqlCommand(query,c);
        cmd.ExecuteNonQuery();
</code>```

答:
Try Below Code</p>

```<code>query = @"INSERT INTO " + tbpg.Text + "  VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";
</code>```

Body:
i've checked again and again , but couldn't find any error

private void Btn_Save_Click(object sender, EventArgs e)
    {

        SqlConnection c = new SqlConnection(conn);

                c.Open();
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    query = @"INSERT INTO '" + tbpg.Text + "' VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";

                }
        SqlCommand cmd = new SqlCommand(query,c);
        cmd.ExecuteNonQuery();

Body:
Try Below Code

query = @"INSERT INTO " + tbpg.Text + "  VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";


问:
c# and SMO - Get Message output such as "Table already exists" for logging
I am using SQL Management objects to connect to SQL server. At the moment they contain simple "create table" commands for my example.

I run this code twice on purpose to cause an error for "table already exists".

However my events below are not getting triggered.

Anyone got any ideas, how I can get hold of this message in my code other then changing the ExecutionType to stop on errors causing exceptions ( which I dont want to do, I want to continue)

My Code:

```<code>public void executeSomeSQL() {
    FileInfo file = new FileInfo(@"\c:\sqlcommands.sql");
    string script = file.OpenText().ReadToEnd();
    SqlConnection conn = new SqlConnection(sqlConnectionString);
    conn.InfoMessage +=new SqlInfoMessageEventHandler(conn_InfoMessage);
    Server server = new Server(new ServerConnection(conn));
    server.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(ConnectionContext_InfoMessage);
    server.ConnectionContext.ExecuteNonQuery(script,ExecutionTypes.ContinueOnError);
    MessageBox.Show("All Done");
}
</code>```

Events:-

```<code>public void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e) {
    textBox3.Text += "1:"+DateTime.Now.ToString();
}

public void ConnectionContext_InfoMessage(object sender, SqlInfoMessageEventArgs e) {
    textBox3.Text += "2:" + DateTime.Now.ToString();
}
</code>```

答:
I'm not programmer (DBA), therefore I'm not sure.
I assume following cam be helpfull

conn.FireInfoMessageEventOnUserErrors = true;

Body:
I am using SQL Management objects to connect to SQL server. At the moment they contain simple "create table" commands for my example.

I run this code twice on purpose to cause an error for "table already exists".

However my events below are not getting triggered.

Anyone got any ideas, how I can get hold of this message in my code other then changing the ExecutionType to stop on errors causing exceptions ( which I dont want to do, I want to continue)

My Code:

public void executeSomeSQL() {
    FileInfo file = new FileInfo(@"\c:\sqlcommands.sql");
    string script = file.OpenText().ReadToEnd();
    SqlConnection conn = new SqlConnection(sqlConnectionString);
    conn.InfoMessage +=new SqlInfoMessageEventHandler(conn_InfoMessage);
    Server server = new Server(new ServerConnection(conn));
    server.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(ConnectionContext_InfoMessage);
    server.ConnectionContext.ExecuteNonQuery(script,ExecutionTypes.ContinueOnError);
    MessageBox.Show("All Done");
}

Events:-

public void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e) {
    textBox3.Text += "1:"+DateTime.Now.ToString();
}

public void ConnectionContext_InfoMessage(object sender, SqlInfoMessageEventArgs e) {
    textBox3.Text += "2:" + DateTime.Now.ToString();
}


问:
Getting around file access protection in Windows to view an active logfile read-only
A customer asked for quick and dirty log viewer for an ASP.NET app, for which I'm using log4net, and I thought somehow we could simply add a controller to read the tail of the active file and spit it back.

If I use the standard .NET API (File.OpenText, etc.) I get access violation (file open by another process), which is what I expect, but I know it is possible to read the file because Ultraedit opens it for viewing read-only. Can I do the same from the .NET API?

```<code>using(StreamReader infile =
         System.IO.File.OpenText(Request.PhysicalApplicationPath + @"\log\my.log"))
{
}
</code>```

答:
Did you try:</p>

```<code>        using (FileStream fs = File.OpenRead("C:\\1.txt"))
        {
            //read here
        }
</code>```

Body:
A customer asked for quick and dirty log viewer for an ASP.NET app, for which I'm using log4net, and I thought somehow we could simply add a controller to read the tail of the active file and spit it back.

If I use the standard .NET API (File.OpenText, etc.) I get access violation (file open by another process), which is what I expect, but I know it is possible to read the file because Ultraedit opens it for viewing read-only. Can I do the same from the .NET API?

using(StreamReader infile =
         System.IO.File.OpenText(Request.PhysicalApplicationPath + @"\log\my.log"))
{
}

Body:
Did you try:

        using (FileStream fs = File.OpenRead("C:\\1.txt"))
        {
            //read here
        }


问:
When I add the second input, it shows undefined for both in alert box
Not sure if the mistake is in the viewData() function.

```<code>  var list = {
  firstName: [],
  lastName: [],
  maximumHeartRate: [],
  restingHeartRate: [],
  age: [],
  gender: []
}

alert("Welcome to the VO2 Max Categorisation App.");

function validate(string) {
  var stringToVal = prompt(string);
  var range = new RegExp("^[a-zA-Z]{2,}$");
  while (range.test(stringToVal) == false || stringToVal == "" || stringToVal == null ) {
    stringToVal = prompt(string);
  }
  return stringToVal
}

function validateNumber(numToVal, min, max){
  var askUser = Number(prompt(numToVal))
  while (isNaN(askUser) || askUser < min || askUser > max || askUser == '' || askUser == null) {
      askUser = Number(prompt("Please enter a number between " + min + " & " + max + "." ));
  }
  return askUser
}

function addData(list) {
   var userFirstName = validate("First name of user?");
   var userLastName = validate("Last name of user?");
   var userGender = validate("Gender of user?");
   var userAge = validateNumber("Please enter an age between 20 - 39!",20,39);
   var MHR = validateNumber("Enter maximum heart rate of user",30,200);
   var RHR = validateNumber("Enter resting heart rate of user",30,200 );

   list.firstName.push(userFirstName);
   list.lastName.push(userLastName);
   list.gender.push(userGender);
   list.age.push(userAge);
   list.maximumHeartRate.push(MHR);
   list.restingHeartRate.push(RHR);

}
</code>```

This function asks the user and pushes everything into the list

```<code>function calculateVO2Max(list) {
  var VO2Max = 15.3 * (list.maximumHeartRate / list.restingHeartRate);
  return VO2Max;
}
</code>```

This calculates VO2Max

```<code>function VO2MaxCategorisation(Gender,Age,VO2Max) {
  if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max < 31) {
    return("Low");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 31 && VO2Max <=34) ) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 35 && VO2Max <= 37)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 38 && VO2Max <= 41)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max > 41) {
    return("High");
  }

  if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max < 29) {
    return("Low");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 29 && VO2Max <= 32)) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 33 && VO2Max <= 35)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 36 && VO2Max <= 39)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max > 39) {
    return("High");
  }

  if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max < 37) {
    return("Low");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 37 && VO2Max <= 41)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 42 && VO2Max <= 44)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 45 && VO2Max <= 48)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max > 48) {
    return("High");
  }

  if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max < 35) {
    return("Low");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 35 && VO2Max <= 39)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 40 && VO2Max <= 42)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 43 && VO2Max <= 47)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max > 47) {
    return("High");
  }

}
</code>```

This function categorize

```<code>function viewData(list) {
  var string = ""
  for(var i = 0; i < list.firstName.length; i++) {
    string += (list.firstName[i] + " " + list.lastName[i] + ": " + VO2MaxCategorisation(list.gender[i],list.age[i],calculateVO2Max(list)) + "\n")
  }
  alert(string)
}
</code>```

It shows undefined when 2 inputs are displayed in the alert box,but it shows the category of the user when only 1 put is displayed

```<code>function optionMenu(list) {
  while(true) {
  var optionChoice = Number(prompt("What do you want to do: \n 1)Enter data \n 2)View data \n 3)Exit"));
    if (optionChoice == 1) {
      addData(list);
    } else if (optionChoice == 2) {
      viewData(list);
    } else if (optionChoice == 3) {
      break;
    } else {
      alert("Sorry,choose from the options.");
    }
  }
}
</code>```

This is the menu to choose

```<code>optionMenu(list);
</code>```

答:
You are initializing string to '' in every call to viewData.

place string outside of viewData context and make it global.

https://jsbin.com/sukuyeguzu/edit?html,js,output

```<code> var list = {
  firstName: [],
  lastName: [],
  maximumHeartRate: [],
  restingHeartRate: [],
  age: [],
  gender: []
}
 var string = "";

alert("Welcome to the VO2 Max Categorisation App.");

function validate(string) {
  var stringToVal = prompt(string);
  var range = new RegExp("^[a-zA-Z]{2,}$");
  while (range.test(stringToVal) == false || stringToVal == "" || stringToVal == null ) {
    stringToVal = prompt(string);
  }
  return stringToVal
}

function validateNumber(numToVal, min, max){
  var askUser = Number(prompt(numToVal))
  while (isNaN(askUser) || askUser < min || askUser > max || askUser == '' || askUser == null) {
      askUser = Number(prompt("Please enter a number between " + min + " & " + max + "." ));
  }
  return askUser
}

function addData(list) {
   var userFirstName = validate("First name of user?");
   var userLastName = validate("Last name of user?");
   var userGender = validate("Gender of user?");
   var userAge = validateNumber("Please enter an age between 20 - 39!",20,39);
   var MHR = validateNumber("Enter maximum heart rate of user",30,200);
   var RHR = validateNumber("Enter resting heart rate of user",30,200 );

   list.firstName.push(userFirstName);
   list.lastName.push(userLastName);
   list.gender.push(userGender);
   list.age.push(userAge);
   list.maximumHeartRate.push(MHR);
   list.restingHeartRate.push(RHR);

}

function calculateVO2Max(list) {
  var VO2Max = 15.3 * (list.maximumHeartRate / list.restingHeartRate);
  return VO2Max;
}

function VO2MaxCategorisation(Gender,Age,VO2Max) {
  if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max < 31) {
    return("Low");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 31 && VO2Max <=34) ) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 35 && VO2Max <= 37)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 38 && VO2Max <= 41)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max > 41) {
    return("High");
  }

  if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max < 29) {
    return("Low");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 29 && VO2Max <= 32)) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 33 && VO2Max <= 35)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 36 && VO2Max <= 39)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max > 39) {
    return("High");
  }

  if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max < 37) {
    return("Low");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 37 && VO2Max <= 41)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 42 && VO2Max <= 44)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 45 && VO2Max <= 48)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max > 48) {
    return("High");
  }

  if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max < 35) {
    return("Low");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 35 && VO2Max <= 39)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 40 && VO2Max <= 42)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 43 && VO2Max <= 47)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max > 47) {
    return("High");
  }

}

function viewData(list) {
  for(var i = 0; i < list.firstName.length; i++) {
    string += (list.firstName[i] + " " + list.lastName[i] + ": " + VO2MaxCategorisation(list.gender[i],list.age[i],calculateVO2Max(list)) + "\n")
  }
  alert(string)
}

function optionMenu(list) {
  while(true) {
  var optionChoice = Number(prompt("What do you want to do: \n 1)Enter data \n 2)View data \n 3)Exit"));
    if (optionChoice == 1) {
      addData(list);
      viewData(list);
    } else if (optionChoice == 2) {
      viewData(list);
    } else if (optionChoice == 3) {
      break;
    } else {
      alert("Sorry,choose from the options.");
    }
  }
}

optionMenu(list);
</code>```

Body:
Not sure if the mistake is in the viewData() function.

  var list = {
  firstName: [],
  lastName: [],
  maximumHeartRate: [],
  restingHeartRate: [],
  age: [],
  gender: []
}

alert("Welcome to the VO2 Max Categorisation App.");

function validate(string) {
  var stringToVal = prompt(string);
  var range = new RegExp("^[a-zA-Z]{2,}$");
  while (range.test(stringToVal) == false || stringToVal == "" || stringToVal == null ) {
    stringToVal = prompt(string);
  }
  return stringToVal
}

function validateNumber(numToVal, min, max){
  var askUser = Number(prompt(numToVal))
  while (isNaN(askUser) || askUser < min || askUser > max || askUser == '' || askUser == null) {
      askUser = Number(prompt("Please enter a number between " + min + " & " + max + "." ));
  }
  return askUser
}

function addData(list) {
   var userFirstName = validate("First name of user?");
   var userLastName = validate("Last name of user?");
   var userGender = validate("Gender of user?");
   var userAge = validateNumber("Please enter an age between 20 - 39!",20,39);
   var MHR = validateNumber("Enter maximum heart rate of user",30,200);
   var RHR = validateNumber("Enter resting heart rate of user",30,200 );

   list.firstName.push(userFirstName);
   list.lastName.push(userLastName);
   list.gender.push(userGender);
   list.age.push(userAge);
   list.maximumHeartRate.push(MHR);
   list.restingHeartRate.push(RHR);

}

This function asks the user and pushes everything into the list

function calculateVO2Max(list) {
  var VO2Max = 15.3 * (list.maximumHeartRate / list.restingHeartRate);
  return VO2Max;
}

This calculates VO2Max

function VO2MaxCategorisation(Gender,Age,VO2Max) {
  if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max < 31) {
    return("Low");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 31 && VO2Max <=34) ) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 35 && VO2Max <= 37)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 38 && VO2Max <= 41)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max > 41) {
    return("High");
  }

  if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max < 29) {
    return("Low");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 29 && VO2Max <= 32)) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 33 && VO2Max <= 35)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 36 && VO2Max <= 39)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max > 39) {
    return("High");
  }

  if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max < 37) {
    return("Low");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 37 && VO2Max <= 41)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 42 && VO2Max <= 44)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 45 && VO2Max <= 48)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max > 48) {
    return("High");
  }

  if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max < 35) {
    return("Low");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 35 && VO2Max <= 39)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 40 && VO2Max <= 42)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 43 && VO2Max <= 47)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max > 47) {
    return("High");
  }

}

This function categorize

function viewData(list) {
  var string = ""
  for(var i = 0; i < list.firstName.length; i++) {
    string += (list.firstName[i] + " " + list.lastName[i] + ": " + VO2MaxCategorisation(list.gender[i],list.age[i],calculateVO2Max(list)) + "\n")
  }
  alert(string)
}

It shows undefined when 2 inputs are displayed in the alert box,but it shows the category of the user when only 1 put is displayed

function optionMenu(list) {
  while(true) {
  var optionChoice = Number(prompt("What do you want to do: \n 1)Enter data \n 2)View data \n 3)Exit"));
    if (optionChoice == 1) {
      addData(list);
    } else if (optionChoice == 2) {
      viewData(list);
    } else if (optionChoice == 3) {
      break;
    } else {
      alert("Sorry,choose from the options.");
    }
  }
}

This is the menu to choose

optionMenu(list);

Body:
You are initializing string to '' in every call to viewData.

place string outside of viewData context and make it global.

https://jsbin.com/sukuyeguzu/edit?html,js,output

 var list = {
  firstName: [],
  lastName: [],
  maximumHeartRate: [],
  restingHeartRate: [],
  age: [],
  gender: []
}
 var string = "";

alert("Welcome to the VO2 Max Categorisation App.");

function validate(string) {
  var stringToVal = prompt(string);
  var range = new RegExp("^[a-zA-Z]{2,}$");
  while (range.test(stringToVal) == false || stringToVal == "" || stringToVal == null ) {
    stringToVal = prompt(string);
  }
  return stringToVal
}

function validateNumber(numToVal, min, max){
  var askUser = Number(prompt(numToVal))
  while (isNaN(askUser) || askUser < min || askUser > max || askUser == '' || askUser == null) {
      askUser = Number(prompt("Please enter a number between " + min + " & " + max + "." ));
  }
  return askUser
}

function addData(list) {
   var userFirstName = validate("First name of user?");
   var userLastName = validate("Last name of user?");
   var userGender = validate("Gender of user?");
   var userAge = validateNumber("Please enter an age between 20 - 39!",20,39);
   var MHR = validateNumber("Enter maximum heart rate of user",30,200);
   var RHR = validateNumber("Enter resting heart rate of user",30,200 );

   list.firstName.push(userFirstName);
   list.lastName.push(userLastName);
   list.gender.push(userGender);
   list.age.push(userAge);
   list.maximumHeartRate.push(MHR);
   list.restingHeartRate.push(RHR);

}

function calculateVO2Max(list) {
  var VO2Max = 15.3 * (list.maximumHeartRate / list.restingHeartRate);
  return VO2Max;
}

function VO2MaxCategorisation(Gender,Age,VO2Max) {
  if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max < 31) {
    return("Low");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 31 && VO2Max <=34) ) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 35 && VO2Max <= 37)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && (VO2Max >= 38 && VO2Max <= 41)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 20 && Age <= 29 && VO2Max > 41) {
    return("High");
  }

  if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max < 29) {
    return("Low");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 29 && VO2Max <= 32)) {
    return("Fair");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 33 && VO2Max <= 35)) {
    return("Average");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && (VO2Max >= 36 && VO2Max <= 39)) {
    return("Good");
  } else if (Gender == "Female" && Age >= 30 && Age <= 39 && VO2Max > 39) {
    return("High");
  }

  if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max < 37) {
    return("Low");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 37 && VO2Max <= 41)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 42 && VO2Max <= 44)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && (VO2Max >= 45 && VO2Max <= 48)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 20 && Age <= 29 && VO2Max > 48) {
    return("High");
  }

  if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max < 35) {
    return("Low");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 35 && VO2Max <= 39)) {
    return("Fair");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 40 && VO2Max <= 42)) {
    return("Average");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && (VO2Max >= 43 && VO2Max <= 47)) {
    return("Good");
  } else if (Gender == "Male" && Age >= 30 && Age <= 39 && VO2Max > 47) {
    return("High");
  }

}

function viewData(list) {
  for(var i = 0; i < list.firstName.length; i++) {
    string += (list.firstName[i] + " " + list.lastName[i] + ": " + VO2MaxCategorisation(list.gender[i],list.age[i],calculateVO2Max(list)) + "\n")
  }
  alert(string)
}

function optionMenu(list) {
  while(true) {
  var optionChoice = Number(prompt("What do you want to do: \n 1)Enter data \n 2)View data \n 3)Exit"));
    if (optionChoice == 1) {
      addData(list);
      viewData(list);
    } else if (optionChoice == 2) {
      viewData(list);
    } else if (optionChoice == 3) {
      break;
    } else {
      alert("Sorry,choose from the options.");
    }
  }
}

optionMenu(list);


问:
Adding a complete row to a table from a DAO.Recordset
I have an access table containing product information with 100 Columns (it is a bought system so not of my creation). I want to be able to copy a row and insert it as a new row with 3 fields updated. I am using VBA on an access DB.

I am selecting the row I want to copy (Select Product.* FROM .....) and putting it into a DAO.Recordset. This works fine. I then want to insert this data back into the table as a new row with all the same data apart from the Product ID (key) and the Product short description.

As there is 100 columns I am trying to avoid typing in all the column names and assigning the values individually. Is there a way to insert from a DAO.Recordset so I can avoid typing in all the columns?  if not is there another way to avoid typing in all the columns and all the values? It would save me a very big insert statement!

Many thanks

Tony

答:
If you use a form where you select the record to copy, you can also use the RecordsetClone:

Copy selected record to new record


问:
How to install mod_proxy_hcheck module/extension for apache2
How to install mod_proxy check module/extension for apache2 ? I want to use all the latest mod_proxy ProxyPass parameters. Currently it is throwing compilation error saying</p>

```<code>AH00526: Syntax error on line 8 of /etc/apache2/conf-extra/httpd-proxy-balancer.conf:
BalancerMember unknown Worker parameter
Action 'configtest' failed.
The Apache error log may have more information.
</code>```

答:
I was able to do it by executing</p>

```<code>a2enmod proxy_hcheck
</code>```

Body:
How to install mod_proxy check module/extension for apache2 ? I want to use all the latest mod_proxy ProxyPass parameters. Currently it is throwing compilation error saying

AH00526: Syntax error on line 8 of /etc/apache2/conf-extra/httpd-proxy-balancer.conf:
BalancerMember unknown Worker parameter
Action 'configtest' failed.
The Apache error log may have more information.

Body:
I was able to do it by executing

a2enmod proxy_hcheck


问:
Debugging Typescript with IntelliJ and Chrome
Is there a way to find the corresponding line in a Typescript file to the (compiled) Javascript one that is causing an error?

I am using IntelliJ and Google Chrome.

答:
You need to compile with the source map support. Is will create a .js.map file that matches the JavaScript files with the TypeScript source. Chrome (and all other browsers as well) will be able to use that to show .ts files while debugging.

For the command line compiler you can add the --sourceMap option (docs) to enable this.

To configure the built-in compiler, follow the instructions from jetbrains.com documentation:

Choose the Set options manually to configure compilation manually:

Select the Generate source maps check box to generate source maps that set correspondence between lines in your TypeScript code and in the generated JavaScript code, otherwise your breakpoints will not be recognised and processed correctly.


问:
Check python function determine isogram from codewars
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

```<code>is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
</code>```

Here is my code:

```<code>def is_isogram(string):
    string = string.lower()
    for char in string:
        if string.count(char) > 1:
            return False
        else:
            return True
</code>```

And when I tried to run the test code Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) It failed, but I thought I did convert everything into lowercase. Can someone help?

答:
let us define an isogram well:
according to wikipedia  An Isogram is a word in which no letter occurs more than once.
check here for more about an isogram

just remind letter
I write this code and it works for me :

```<code>def is_isogram(argument):
   print(len(argument))
   if isinstance(argument,str):
      valeur=argument.lower()
      if not argument:
         return False
      else:
         for char in valeur:
            if valeur.count(char)>1 or not char.isalpha():
               return False
         return True
   else:
      raise TypeError("need a string ")
</code>```

NB: the hidden test is the fact that you must check if the char in the string is a alpha character a-z, when i add this it pass all the hiddens tests
up vote if this help

Body:
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case

Here is my code:

def is_isogram(string):
    string = string.lower()
    for char in string:
        if string.count(char) > 1:
            return False
        else:
            return True

And when I tried to run the test code Test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" ) It failed, but I thought I did convert everything into lowercase. Can someone help?

Body:
let us define an isogram well:
according to wikipedia  An Isogram is a word in which no letter occurs more than once.
check here for more about an isogram

just remind letter
I write this code and it works for me :

def is_isogram(argument):
   print(len(argument))
   if isinstance(argument,str):
      valeur=argument.lower()
      if not argument:
         return False
      else:
         for char in valeur:
            if valeur.count(char)>1 or not char.isalpha():
               return False
         return True
   else:
      raise TypeError("need a string ")

NB: the hidden test is the fact that you must check if the char in the string is a alpha character a-z, when i add this it pass all the hiddens tests
up vote if this help


问:
Are there any free parser generators that generate C++ code and handle Unicode correctly?
After asking this question, I'm now sold on trying to use a parser generator, where before I was going to write things manually.

However, I can't seem to find any such parser that generates C++ code, nor can I find a parser that correctly handles Unicode. (note that my input is in UCS-2 -- I don't care about supporting bits outside of the Basic Multilingual Plane if that makes building the parser more difficult)

There are some parsers which can generate C, but such parsers all seem to throw exception safety out the window, which would prevent me from using C++ inside any semantic actions.

Does a parser generator exist which meets these two tenets, or am I stuck doing everything by hand?

EDIT: Oh, and my project is BSL licensed, so there can't be many restrictions on use of the output of the parser generator itself.

答: if you're in the mood to experiment, this one supports wide chars but is obscure: http://wiki.winprog.org/wiki/LibCC_Parse</p>


问:
Define comma operator like javascript
Javascript's comma operator is useful for inserting commands within code without it breaking the workflow. The preceding expression is executed but otherwise ignored (e.g. if embedded in a function that is expecting a different object):

```<code>> x = 5, 4
< 4
> x
< 5
</code>```

Is there any way to implement this in R?  I've tried following

```<code>',' = function(x, y) { x; y }
</code>```

but R seems to have locked comma down:

```<code>> 4, 5
Error: unexpected ',' in "4,"
</code>```

Is there any workaround to this?

答:
(Un)fortunately , is one of the very few things in R that cannot be overloaded/redefined. It’s not an operator in the language, unlike e.g. `{` and `(`.

In a similar vein, while you can overload `=` and `(`, you cannot change their meaning indiscriminately; in a function call with parameters (e.g. f(a = 1, b = 2)), neither ( nor = can be made to change their meaning because, once again, they’re not operators in this context).

As noted in the comments, for your purpose, ; seems to be a very close equivalent, though.

Title: Define comma operator like javascript

Body:
Javascript's comma operator is useful for inserting commands within code without it breaking the workflow. The preceding expression is executed but otherwise ignored (e.g. if embedded in a function that is expecting a different object):

> x = 5, 4
< 4
> x
< 5

Is there any way to implement this in R?  I've tried following

',' = function(x, y) { x; y }

but R seems to have locked comma down:

> 4, 5
Error: unexpected ',' in "4,"

Is there any workaround to this?


问:
c++ initializer difference, with and without = operator
What is difference between initializing x1 and x2?

```<code>struct X {
    int i;
};

void func(){
    X x1 = {2};
    X x2 {2};

    cout << x1.i << ", " << x2.i << endl;
}
</code>```

答:
```<code>X x1 = {2};
</code>```

Is copy-list-initialization.

```<code>X x2 {2};
</code>```

Is direct-initialization.

Both syntaxes perform aggregate initialization, because X is an aggregate.

What is difference

Braces can not be elided with the direct-initialization form (until C++14).

In general, copy initialization only considers non-explicit constructors and conversion functions and direct initialization considers also explicit ones. However, this does not apply to aggregate initialization.

with and without = operator

The equals (=) character here isn't actually an operator. It is part of the syntax of copy initialization.

Body:
What is difference between initializing x1 and x2?

struct X {
    int i;
};

void func(){
    X x1 = {2};
    X x2 {2};

    cout << x1.i << ", " << x2.i << endl;
}

Body:
X x1 = {2};

Is copy-list-initialization.

X x2 {2};

Is direct-initialization.

Both syntaxes perform aggregate initialization, because X is an aggregate.

What is difference

Braces can not be elided with the direct-initialization form (until C++14).

In general, copy initialization only considers non-explicit constructors and conversion functions and direct initialization considers also explicit ones. However, this does not apply to aggregate initialization.

with and without = operator

The equals (=) character here isn't actually an operator. It is part of the syntax of copy initialization.


问:
Error in mongodb export in node,js
I was trying to connect mongodb using node.js. I stumbled on a problem.
I am getting   require(...).pure is not a function error . I tried to use the exact code from this site  "https://mongodb.github.io/node-mongodb-native/api-generated/collection.html"
My code is given below.

```<code>var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');

var uri = "mongodb://sa:psvitagamer5@cluster0-shard-00-00-
 tpfog.mongodb.net:27017,cluster0-shard-00-01-
  tpfog.mongodb.net:27017,cluster0-shard-00-02-
  tpfog.mongodb.net:27017/myNodeDb?ssl=true&replicaSet=Cluster0-shard-
  0&authSource=admin";

 MongoClient.connect(uri, function(err, db) {

   var collection = db.collection("userCollection");

    collection.insert({hello:'world_no_safe'});

   // Wait for a second before finishing up, to ensure we have written
     the item to disk
   setTimeout(function() {

  // Fetch the document
   collection.findOne({hello:'world_no_safe'}, function(err, item) {
      assert.equal(null, err);
      assert.equal('world_no_safe', item.hello);
      db.close();
   })
   }, 100);
  //db.close();
});
</code>```

Please let me know your suggestions.

答:
That documentation is not well written nor tested, pure() is in mongodb-core module

You should install mongodb-core and use:

```<code>BSON = require('mongodb-core').BSON;
</code>```

As I can see you (and that documentation) are not using BSON at all, you should remove that.

Title: Error in mongodb export in node,js

Body:
I was trying to connect mongodb using node.js. I stumbled on a problem.
I am getting   require(...).pure is not a function error . I tried to use the exact code from this site  "https://mongodb.github.io/node-mongodb-native/api-generated/collection.html"
My code is given below.

var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');

var uri = "mongodb://sa:psvitagamer5@cluster0-shard-00-00-
 tpfog.mongodb.net:27017,cluster0-shard-00-01-
  tpfog.mongodb.net:27017,cluster0-shard-00-02-
  tpfog.mongodb.net:27017/myNodeDb?ssl=true&replicaSet=Cluster0-shard-
  0&authSource=admin";

 MongoClient.connect(uri, function(err, db) {

   var collection = db.collection("userCollection");

    collection.insert({hello:'world_no_safe'});

   // Wait for a second before finishing up, to ensure we have written
     the item to disk
   setTimeout(function() {

  // Fetch the document
   collection.findOne({hello:'world_no_safe'}, function(err, item) {
      assert.equal(null, err);
      assert.equal('world_no_safe', item.hello);
      db.close();
   })
   }, 100);
  //db.close();
});

Please let me know your suggestions.

Body:
That documentation is not well written nor tested, pure() is in mongodb-core module

You should install mongodb-core and use:

BSON = require('mongodb-core').BSON;

As I can see you (and that documentation) are not using BSON at all, you should remove that.


问:
Form Dialogs in MS Bot Framework ignore the first item in all enums
I am using MS bot framework and building a dialog form. For the options available to the user, I am using enums and this code to build the form:

```<code>        return new FormBuilder<InsuranceDialogForm>()
            .Message("Sure, I will need to ask you a couple of questions first.")
            .Build();
</code>```

And my enums look like this:

```<code>public class InsuranceDialogForm
{
    //[Prompt("Are you our customer?")]
    //Disabled prompt because otherwise choice buttons won't appear
    public IsCurrentCustomer IsCurrentCustomer;

    //[Prompt("Which type of insurance do you need?")]
    public InsuranceType InsuranceType;

    //[Prompt("Which country are you travelling to?")]
    public string TravelDestination;

    //[Prompt("Please select one:")]
    public InsurancePackage InsurancePackage;
}

public enum IsCurrentCustomer
{
    Yes, No
}

public enum InsuranceType
{
    Travel, Vehicle, Life
}

public enum InsurancePackage
{
    Basic, Standard, Executive
}

public enum WhoIsTravelling
{
    Me, Family
}
</code>```

The issue is that the bot ignores the first option from each enum. It is not available for selection in the buttons output by the bot, and if you type it manually, it will say ".... is not an option". So I have to use a workaround like this:

```<code>public enum IsCurrentCustomer
{
    IGNORE, Yes, No
}
</code>```

Meanwhile, Microsoft's examples don't have this issue. What could I be doing wrong?

答:
+1 to kienct89

Sorry i cant add a comment to your question but just a FYI if you have not solved the Prompt issue out.

Currently you have the following:

```<code>//[Prompt("Are you our customer?")]
//Disabled prompt because otherwise choice buttons won't appear
public IsCurrentCustomer IsCurrentCustomer;
</code>```

Changing it to the following will now allow the prompt with the enum values:

```<code>[Prompt("Are you our customer?" {||})]
public IsCurrentCustomer IsCurrentCustomer;
</code>```

Basically just add {||} to the back of the enum prompt and the options will appear.

HTH

Body:
I am using MS bot framework and building a dialog form. For the options available to the user, I am using enums and this code to build the form:

        return new FormBuilder<InsuranceDialogForm>()
            .Message("Sure, I will need to ask you a couple of questions first.")
            .Build();

And my enums look like this:

public class InsuranceDialogForm
{
    //[Prompt("Are you our customer?")]
    //Disabled prompt because otherwise choice buttons won't appear
    public IsCurrentCustomer IsCurrentCustomer;

    //[Prompt("Which type of insurance do you need?")]
    public InsuranceType InsuranceType;

    //[Prompt("Which country are you travelling to?")]
    public string TravelDestination;

    //[Prompt("Please select one:")]
    public InsurancePackage InsurancePackage;
}

public enum IsCurrentCustomer
{
    Yes, No
}

public enum InsuranceType
{
    Travel, Vehicle, Life
}

public enum InsurancePackage
{
    Basic, Standard, Executive
}

public enum WhoIsTravelling
{
    Me, Family
}

The issue is that the bot ignores the first option from each enum. It is not available for selection in the buttons output by the bot, and if you type it manually, it will say ".... is not an option". So I have to use a workaround like this:

public enum IsCurrentCustomer
{
    IGNORE, Yes, No
}

Meanwhile, Microsoft's examples don't have this issue. What could I be doing wrong?

Body:
+1 to kienct89

Sorry i cant add a comment to your question but just a FYI if you have not solved the Prompt issue out.

Currently you have the following:

//[Prompt("Are you our customer?")]
//Disabled prompt because otherwise choice buttons won't appear
public IsCurrentCustomer IsCurrentCustomer;

Changing it to the following will now allow the prompt with the enum values:

[Prompt("Are you our customer?" {||})]
public IsCurrentCustomer IsCurrentCustomer;

Basically just add {||} to the back of the enum prompt and the options will appear.

HTH


问:
What is the difference between @Configuration and @Component in Spring?
@ComponentScan creates beans using both @Configuration and @Component. Both these annotations work fine when swapped. What is the difference then?

答:
Apart from the differences highlighted by reos.

The reason why @Configuration cannot be replaced by @Component is as below:

The difference is in how the inter bean dependency is handled.
Refer the link for a detailed explanation with example:
Difference between Configuration and Component