问:
SELECT data from two table get NULL
I am trying to write SELECT statement (JOIN) of two table.
First one is KPOL table second one is SIFRAD and I  want display all employee which release policy in 2013.
When I type query like this notthing happened

```<code>SELECT P.SIFRA_RAD, S.IME, P.DAT_IZD
FROM AUTO.SIFRAD S, AUTO.KPOL P
WHERE S.IME = P.SIFRA_RAD AND EXTRACT(YEAR FROM P.DAT_IZD)= '2013'
</code>```

But when I select DAT_IZD I get the bunch of data

```<code>SELECT DAT_IZD
FROM AUTO.KPOL
WHERE EXTRACT(YEAR FROM DAT_IZD)='2013' ORDER BY DAT_IZD ASC
</code>```

I have no idea where I make mistake. Query look like alright but It doesnt return anything.
Any suggestion and comment where I made mistake ?

UPDATE

I want to display which Employee release policy in 2013 year.
The first table is KPOL which contain DAT_IZD (date of release)
Second one is AUTO.SIFRAD which is Employee table which contain SIFRA_R and IME
And SIFRA_R is key in table AUTO.KPOL which contain SIFRA_RAD
in picure belove you can see all details

```<code>"SIFRA_RAD"  "IME"      "DAT_IZD"

"00456"     "Test"      "1.3.2013"
"00465      "Test123"   "1.3.2013"
"00469"     "Test111"   "1.3.2013"
</code>```

答:
The empty first result set indicates that there is no record in the AUTO.SIFRAD table which matches to any record in the AUTO.KPOL table which also has a DAT_IZD date in 2013.  You could mitigate this problem by rephrasing your query as a left join, and by moving the WHERE logic to the ON clause:

```<code>SELECT P.SIFRA_RAD, S.IME, P.DAT_IZD
FROM AUTO.SIFRAD S
LEFT JOIN AUTO.KPOL P
    ON S.IME = P.SIFRA_RAD AND EXTRACT(YEAR FROM P.DAT_IZD) = 2013;
</code>```

This should still show no data for the DAT_IZD column, but it would at least return all records from the AUTO.SIFRAD table.

Title: SELECT data from two table get NULL

Body:
I am trying to write SELECT statement (JOIN) of two table.
First one is KPOL table second one is SIFRAD and I  want display all employee which release policy in 2013.
When I type query like this notthing happened

SELECT P.SIFRA_RAD, S.IME, P.DAT_IZD
FROM AUTO.SIFRAD S, AUTO.KPOL P
WHERE S.IME = P.SIFRA_RAD AND EXTRACT(YEAR FROM P.DAT_IZD)= '2013'

But when I select DAT_IZD I get the bunch of data

SELECT DAT_IZD
FROM AUTO.KPOL
WHERE EXTRACT(YEAR FROM DAT_IZD)='2013' ORDER BY DAT_IZD ASC

I have no idea where I make mistake. Query look like alright but It doesnt return anything.
Any suggestion and comment where I made mistake ?

UPDATE

I want to display which Employee release policy in 2013 year.
The first table is KPOL which contain DAT_IZD (date of release)
Second one is AUTO.SIFRAD which is Employee table which contain SIFRA_R and IME
And SIFRA_R is key in table AUTO.KPOL which contain SIFRA_RAD
in picure belove you can see all details

"SIFRA_RAD"  "IME"      "DAT_IZD"

"00456"     "Test"      "1.3.2013"
"00465      "Test123"   "1.3.2013"
"00469"     "Test111"   "1.3.2013"

Body:
The empty first result set indicates that there is no record in the AUTO.SIFRAD table which matches to any record in the AUTO.KPOL table which also has a DAT_IZD date in 2013.  You could mitigate this problem by rephrasing your query as a left join, and by moving the WHERE logic to the ON clause:

SELECT P.SIFRA_RAD, S.IME, P.DAT_IZD
FROM AUTO.SIFRAD S
LEFT JOIN AUTO.KPOL P
    ON S.IME = P.SIFRA_RAD AND EXTRACT(YEAR FROM P.DAT_IZD) = 2013;

This should still show no data for the DAT_IZD column, but it would at least return all records from the AUTO.SIFRAD table.


来源: stackexchange

问:
Get key value from string using Powershell
I am trying to get key value using Regex in powershell.

```<code>$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name
</code>```

I want output like this :

```<code>$key1 = "value1"
$key2 = "value2"
$key3 = "value3"
</code>```

Output i am getting :

```<code>Name : :value1,key2:value2,
</code>```

答:
You get that match because  there is no match before the : and [^/]+ will also match : and ,.

So your pattern will first match :, then it will match not a / and then backtracks until it can match a ,

You could use 2 times a negated character class matching not a comma or colon and assert what is on the right is a comma or the end of the string:

```<code>[^:,]+:[^:,]+(?=,|$)
</code>```

Regex demo

If you also don't want to match a / you could add it to the character class:

```<code>[^:,/]+:[^:,/]+(?=,|$)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get key value using Regex in powershell.

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name

I want output like this :

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"

Output i am getting :

Name : :value1,key2:value2,

Body:
You get that match because  there is no match before the : and [^/]+ will also match : and ,.

So your pattern will first match :, then it will match not a / and then backtracks until it can match a ,

You could use 2 times a negated character class matching not a comma or colon and assert what is on the right is a comma or the end of the string:

[^:,]+:[^:,]+(?=,|$)

Regex demo

If you also don't want to match a / you could add it to the character class:

[^:,/]+:[^:,/]+(?=,|$)


问:
How to store command output into array in Ansible?
Essentially, I want to be able to handle "wildcard filenames" in Linux using ansible.  In essence, this means using the ls command with part of a filename followed by an "*" so that it will list ONLY certain files.

However, I cannot store the output properly in a variable as there will likely be more than one filename returned.  Thus, I want to be able to store these results no matter how many there might be in an array during one task.  I then want to be able to retrieve all of the results from the array in a later task.  Furthermore, since I don't know how many files might be returned, I cannot do a task for each filename, and an array makes more sense.

The reason behind this is that there are files in a random storage location that are changed often, but they always have the same first half.  It's their second half of their names that are random, and I don't want to have to hard code that into ansible at all.

I'm not certain at all how to properly implement/manipulate an array in ansible, so the following code is an example of what I'm "trying" to accomplish.  Obviously it won't function as intended if more than one filename is returned, which is why I was asking for assistance on this topic:

```<code>- hosts: <randomservername>
  remote_user: remoteguy
  become: yes
  become_method: sudo
  vars:
    aaaa: b
  tasks:

 - name: Copy over all random file contents from directory on control node to target clients.  This is to show how to manipulate wildcard filenames.
    copy:
      src: /opt/home/remoteguy/copyable-files/testdir/
      dest: /tmp/
      owner: remoteguy
      mode: u=rwx,g=r,o=r
    ignore_errors: yes

  - name: Determine the current filenames and store in variable for later use, obviously for this exercise we know part of the filenames.
    shell: "ls {{item}}"
    changed_when: false
    register: annoying
    with_items: [/tmp/this-name-is-annoying*, /tmp/this-name-is-also*]

  - name: Run command to cat each file and then capture that output.
    shell: cat {{ annoying }}
    register: annoying_words

  - debug: msg=Here is the output of the two files.  {{annoying_words.stdout_lines }}

  - name: Now, remove the wildcard files from each server to clean up.
    file:
      path: '{{ item }}'
      state: absent
    with_items:
    - "{{ annoying.stdout }}"
</code>```

I understand the YAML format got a little mussed up, but if it's fixed, this "would" run normally, it just won't give me the output I'm looking for.  Thus if there were 50 files, I'd want ansible to be able to manipulate them all, and/or be able to delete them all.. etc etc etc.

If anyone here could let me know how to properly utilize an array in the above test code fragment that would be fantastic!

答:
Can you try as below. </p>

```<code>- name: Run command to cat each file and then capture that output.
   shell: cat {{ item.stdout_lines }}
   register: annoying_words
   with_items:
    - "{{ annoying.results }}"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Essentially, I want to be able to handle "wildcard filenames" in Linux using ansible.  In essence, this means using the ls command with part of a filename followed by an "*" so that it will list ONLY certain files.

However, I cannot store the output properly in a variable as there will likely be more than one filename returned.  Thus, I want to be able to store these results no matter how many there might be in an array during one task.  I then want to be able to retrieve all of the results from the array in a later task.  Furthermore, since I don't know how many files might be returned, I cannot do a task for each filename, and an array makes more sense.

The reason behind this is that there are files in a random storage location that are changed often, but they always have the same first half.  It's their second half of their names that are random, and I don't want to have to hard code that into ansible at all.

I'm not certain at all how to properly implement/manipulate an array in ansible, so the following code is an example of what I'm "trying" to accomplish.  Obviously it won't function as intended if more than one filename is returned, which is why I was asking for assistance on this topic:

- hosts: <randomservername>
  remote_user: remoteguy
  become: yes
  become_method: sudo
  vars:
    aaaa: b
  tasks:

 - name: Copy over all random file contents from directory on control node to target clients.  This is to show how to manipulate wildcard filenames.
    copy:
      src: /opt/home/remoteguy/copyable-files/testdir/
      dest: /tmp/
      owner: remoteguy
      mode: u=rwx,g=r,o=r
    ignore_errors: yes

  - name: Determine the current filenames and store in variable for later use, obviously for this exercise we know part of the filenames.
    shell: "ls {{item}}"
    changed_when: false
    register: annoying
    with_items: [/tmp/this-name-is-annoying*, /tmp/this-name-is-also*]

  - name: Run command to cat each file and then capture that output.
    shell: cat {{ annoying }}
    register: annoying_words

  - debug: msg=Here is the output of the two files.  {{annoying_words.stdout_lines }}

  - name: Now, remove the wildcard files from each server to clean up.
    file:
      path: '{{ item }}'
      state: absent
    with_items:
    - "{{ annoying.stdout }}"

I understand the YAML format got a little mussed up, but if it's fixed, this "would" run normally, it just won't give me the output I'm looking for.  Thus if there were 50 files, I'd want ansible to be able to manipulate them all, and/or be able to delete them all.. etc etc etc.

If anyone here could let me know how to properly utilize an array in the above test code fragment that would be fantastic!

Body:
Can you try as below.

- name: Run command to cat each file and then capture that output.
   shell: cat {{ item.stdout_lines }}
   register: annoying_words
   with_items:
    - "{{ annoying.results }}"


问:
VBA - Copy-Paste to another workbook
I am trying to copy specific cells from one workbook to another at the end of the table.
I assume the problem is with using 'ActiveWorkbook' a lot.
I get the error "Object doesnt support this property or method" and it seems that macro copies cells from CurrentBook and not uploader.

How can I fix my code?

```<code>
Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With

CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub
</code>```

答:
In VBA you must not use Ative.

So replace all the Active and you have to use PasteSpecial, it's better than Paste

```<code>Sub test()

Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ThisWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Set uploader = Workbooks.Open(uploadfile)

Application.CutCopyMode = False
uploader.Worksheets(1).Range("A1:J100").Copy

lastRow = CurrentBook.Worksheets(1).Cells(CurrentBook.Worksheets(1).Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & (lastRow + 100)).PasteSpecial xlPasteValues

uploader.Close

End Sub
</code>```

This code works for me,

Your welcome :)

Title: VBA - Copy-Paste to another workbook

Body:
I am trying to copy specific cells from one workbook to another at the end of the table.
I assume the problem is with using 'ActiveWorkbook' a lot.
I get the error "Object doesnt support this property or method" and it seems that macro copies cells from CurrentBook and not uploader.

How can I fix my code?

Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With

CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub

Body:
In VBA you must not use Ative.

So replace all the Active and you have to use PasteSpecial, it's better than Paste

Sub test()

Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ThisWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Set uploader = Workbooks.Open(uploadfile)

Application.CutCopyMode = False
uploader.Worksheets(1).Range("A1:J100").Copy

lastRow = CurrentBook.Worksheets(1).Cells(CurrentBook.Worksheets(1).Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & (lastRow + 100)).PasteSpecial xlPasteValues

uploader.Close

End Sub

This code works for me,

Your welcome :)


问:
Threading in C, cross platform
I am dealing with an existing project (in C) that is currently running on a single thread, and we would like to run on multiple platforms AND have multiple threads. Hopefully, there is a library for this, because, IMHO, the Win32 API is like poking yourself in the eye repeatedly. I know about Boost.Thread for C++, but, this must be C (and compilable on MinGW and gcc). Cygwin is not an option, sorry.</p>

答:
Windows threading has sufficiently different functionality when compared to that of Linux such that perhaps you should consider two different implementations, at least if application performance could be an issue. On the other hand, simply implementing multi-threading may well make your app slower than it was before. Lets assume that performance is an issue and that multi-threading is the best option.

With Windows threads I'm specifically thinking of I/O Completion Ports (IOCPs) which allow implementing I/O-event driven threads that make the most efficient use of the hardware.

Many "classic" applications are constructed along one thread/one socket (/one user or similar) concept where the number of simultaneous sessions will be limited by the scheduler's ability to handle large numbers of threads (>1000). The IOCP concept allows limiting the number of threads to the number of cores in your system which means that the scheduler will have very little to do. The threads will only execute when the IOCP releases them after an I/O event has occurred. The thread services the IOC, (typically) initiates a new I/O and returns to wait at the IOCP for the next completion. Before releasing a thread the IOCP will also provide the context of the completion such that the thread will "know" what processing context the IOC belongs to.

The IOCP concept completely does away with polling which is a great resource waster although "wait on multiple object" polling is somewhat of an improvement. The last time I looked Linux had nothing remotely like IOCPs so a Linux multi-threaded application would be constructed quite differently compared to a Windows app with IOCPs.

In really efficient IOCP apps there is a risk that so many IOs (or rather Outputs) are queued to the IO resource involved that the system runs out of non-paged memory to store them. Conversely, in really inefficient IOCP apps there is a risk that so many Inputs are queued (waiting to be serviced) that the non-paged memory is exhausted when trying to temporarily buffer them.

Title: Threading in C, cross platform


问:
Get count of array objects belonging to a partical ID in JavaScript/Node js
I have an array of arrays like this:

```<code>var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]
</code>```

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

```<code>[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]
</code>```

Note that the output is in the ascending order of the Count.

This is what I tried :

```<code>var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)
</code>```

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

答:
You can get the intended result with the below piece of code as well.</p>

```<code>var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

var arrMap = {}

array.map(item => {
    if(arrMap[item[0]]){
     arrMap[item[0]]++
    }else{
     arrMap[item[0]] = 1
    }
})

var resultArr = []

for(var keys of Object.keys(arrMap)){
 resultArr.push({"ID":keys,"Count":arrMap[keys]})
}
</code>```

Body:
I have an array of arrays like this:

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]

Note that the output is in the ascending order of the Count.

This is what I tried :

var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

Body:
You can get the intended result with the below piece of code as well.

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

var arrMap = {}

array.map(item => {
    if(arrMap[item[0]]){
     arrMap[item[0]]++
    }else{
     arrMap[item[0]] = 1
    }
})

var resultArr = []

for(var keys of Object.keys(arrMap)){
 resultArr.push({"ID":keys,"Count":arrMap[keys]})
}


问:
Dubbuging C++ with VS. Track down varrible change
I have a huge program (VS project) which contains global variable. It modifies from hundreds places. Actually it standard STL container (std::vector) and question is how can I track down this particular variable modifications?
In my work I use VS debugger (Prof 2017 15.9.5)</p>

答:
There are a few solutions which come to my mind:

Create another class which will encapsulte this vector.
Then allow users to use this vector by adding getter returning
reference to it.
Then you can put a breakpoint in getter.

Put a memory breakpoint on one of vector's members but it is plantform specific solution which may not work in all scenarios.

Replace std::vector with your custom type with interface identical to std::vector's which would use original std::vector in its internals.
With this solution you can monitor accesses more precisely.

P.S. remove this global ASAP.


问:
Different between in operator and for loop?
i was wondering if the "in" operator work as a for loop and if the time complexity are equivalent?

for n in range(10):
    if n == 5:
        return True
return False

5 in range(10)
```

答:
The 2nd approach...

```<code>5 in range(10)
</code>```

...is much faster. Python’s range is lazy iterator. When you check whether a value is in the range of numbers, it can easily be calculated rather than looping over the range. This means there is an O(1) time complexity.

The 1st approach however has, at worst, an O(n) time complexity as you may have to loop over the whole range.

Body:
The 2nd approach...

5 in range(10)

...is much faster. Python’s range is lazy iterator. When you check whether a value is in the range of numbers, it can easily be calculated rather than looping over the range. This means there is an O(1) time complexity.

The 1st approach however has, at worst, an O(n) time complexity as you may have to loop over the whole range.


问:
how to merge two json_arrays in postgresql
I need to MERGE two JSONB_ARRAYS

i have in my table column jsonb of items which looks like this:

```<code>[
   {"fav": 1, "is_active": true, "date": "1999-00-00 11:07:05.710000"},
   {"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"}
]
</code>```

where fav's value is unique number.

And i have incoming data, where could be the same items which also exists in my table and also new items and after merging the result must be that way where new items just need to add but existing items i need to update

so after merging the result must look like this:

```<code>merge:
[
   {"fav": 1, "is_active": true, "date": "1999-00-00 11:07:05.710000"},
   {"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"}
]::jsonb ||

[
   {"fav": 3, "is_active": true, "date": "2019-00-00 11:07:05.710000"},
   {"fav": 1, "is_active": false, "date": "2020-00-00 11:07:05.710000"}
]::jsonb

------------------------------------------------------------------------
result:

[
   {"fav": 1, "is_active": false, "date": "2020-00-00 11:07:05.710000"},
   {"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"},
   {"fav": 3, "is_active": true, "date": "2019-00-00 11:07:05.710000"}
]
</code>```

as expected the "fav": 1 -> was updated and "fav": 3 -> was added
maybe i need some refactroring structure of my json maybe something else?
and maybe it would be better if i retrieve json to Collection and work with objects and after all manipulations just save it back?

Update 1

i try write custom function:

```<code>CREATE OR REPLACE FUNCTION public.json_array_merge(data1 jsonb, merge_data jsonb)
    RETURNS jsonb
    IMMUTABLE
    LANGUAGE sql
AS $$
SELECT jsonb_agg(expression)::jsonb
FROM (
         WITH to_merge AS (
             SELECT * FROM jsonb_each(jsonb_array_elements(merge_data))
         )
         SELECT *
         FROM json_each(jsonb_array_elements(data1))
         WHERE value NOT IN (SELECT value FROM to_merge)
         UNION ALL
         SELECT * FROM to_merge
     ) expression;
$$;
</code>```

but now it doesnt work (

答:
You probably will want to write a custom function to handle this. The default behaviour is to append each value because it has no way of knowing that you want fav to be unique.

If your data used fav as a key e.g.

```<code>{
    "fav1": {"date": "2020-00-00 11:07:05.710000", "is_active": false},
    "fav2": {"date": "1998-00-00 11:07:05.710000", "is_active": true},
    "fav3": {"date": "2019-00-00 11:07:05.710000", "is_active": true}
}
</code>```

this would be simple to manage, but since you are using an array you would need to make a custom function that iterates and check each value.

Edit you would need to run a few loops with plpgsql, this could be achieved more efficiently using plv8

```<code>CREATE OR REPLACE FUNCTION public.json_array_merge(
    data_new jsonb,
    data_old jsonb,
    key_val text
)
    RETURNS jsonb
AS $$
DECLARE
    ret jsonb := '[]'::jsonb;
    cur text;
    add boolean := true;

    i integer := 0;
    ic integer := jsonb_array_length(data_old);
    j integer := 0;
    jc integer := jsonb_array_length(data_new);
BEGIN
    IF ic > 0 AND jc > 0 THEN

        -- populate or replace the records that are already there
        WHILE i < ic LOOP
            cur := null;
            j   := 0;

            -- loop new array
            WHILE j < jc LOOP
                IF data_old->i->>key_val = data_new->j->>key_val THEN
                    cur := data_new->>j;
                    add := false;
                END IF;
                j := j + 1;
            END LOOP;

            -- add or replace
            IF add THEN
                ret := ret || format('[%s]', data_old->>i)::jsonb;
            ELSE
                ret := ret || format('[%s]', cur)::jsonb;
            END IF;

            add := true;
            i   := i + 1;
        END LOOP;

        -- loop through the new data again and add any values not in ret
        ic := jsonb_array_length(ret);
        j  := 0;
        WHILE j < jc LOOP
            i   := 0;
            add := true;

            WHILE i < ic LOOP
                IF ret->i->>key_val = data_new->j->>key_val THEN
                    add := false;
                END IF;

                i := i + 1;
            END LOOP;

            IF add THEN
                ret := ret || format('[%s]', data_new->>j)::jsonb;
            END IF;

            j := j + 1;
        END LOOP;
    ELSE
        ret := data_new;
    END IF;

    RETURN ret;
END
$$
LANGUAGE plpgsql IMMUTABLE;
</code>```

Running this should give you the desired result

```<code>SELECT json_array_merge(
    '[{"fav": 3, "is_active": true, "date": "2019-00-00 11:07:05.710000"},{"fav": 1, "is_active": false, "date": "2020-00-00 11:07:05.710000"}]',
    '[{"fav": 1, "is_active": true, "date": "1999-00-00 11:07:05.710000"},{"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"}]',
    'fav'
)
</code>```

Body:
I need to MERGE two JSONB_ARRAYS

i have in my table column jsonb of items which looks like this:

[
   {"fav": 1, "is_active": true, "date": "1999-00-00 11:07:05.710000"},
   {"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"}
]

where fav's value is unique number.

And i have incoming data, where could be the same items which also exists in my table and also new items and after merging the result must be that way where new items just need to add but existing items i need to update

so after merging the result must look like this:

merge:
[
   {"fav": 1, "is_active": true, "date": "1999-00-00 11:07:05.710000"},
   {"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"}
]::jsonb ||

[
   {"fav": 3, "is_active": true, "date": "2019-00-00 11:07:05.710000"},
   {"fav": 1, "is_active": false, "date": "2020-00-00 11:07:05.710000"}
]::jsonb

------------------------------------------------------------------------
result:

[
   {"fav": 1, "is_active": false, "date": "2020-00-00 11:07:05.710000"},
   {"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"},
   {"fav": 3, "is_active": true, "date": "2019-00-00 11:07:05.710000"}
]

as expected the "fav": 1 -> was updated and "fav": 3 -> was added
maybe i need some refactroring structure of my json maybe something else?
and maybe it would be better if i retrieve json to Collection and work with objects and after all manipulations just save it back?

Update 1

i try write custom function:

CREATE OR REPLACE FUNCTION public.json_array_merge(data1 jsonb, merge_data jsonb)
    RETURNS jsonb
    IMMUTABLE
    LANGUAGE sql
AS $$
SELECT jsonb_agg(expression)::jsonb
FROM (
         WITH to_merge AS (
             SELECT * FROM jsonb_each(jsonb_array_elements(merge_data))
         )
         SELECT *
         FROM json_each(jsonb_array_elements(data1))
         WHERE value NOT IN (SELECT value FROM to_merge)
         UNION ALL
         SELECT * FROM to_merge
     ) expression;
$$;

but now it doesnt work (

Body:
You probably will want to write a custom function to handle this. The default behaviour is to append each value because it has no way of knowing that you want fav to be unique.

If your data used fav as a key e.g.

{
    "fav1": {"date": "2020-00-00 11:07:05.710000", "is_active": false},
    "fav2": {"date": "1998-00-00 11:07:05.710000", "is_active": true},
    "fav3": {"date": "2019-00-00 11:07:05.710000", "is_active": true}
}

this would be simple to manage, but since you are using an array you would need to make a custom function that iterates and check each value.

Edit you would need to run a few loops with plpgsql, this could be achieved more efficiently using plv8

CREATE OR REPLACE FUNCTION public.json_array_merge(
    data_new jsonb,
    data_old jsonb,
    key_val text
)
    RETURNS jsonb
AS $$
DECLARE
    ret jsonb := '[]'::jsonb;
    cur text;
    add boolean := true;

    i integer := 0;
    ic integer := jsonb_array_length(data_old);
    j integer := 0;
    jc integer := jsonb_array_length(data_new);
BEGIN
    IF ic > 0 AND jc > 0 THEN

        -- populate or replace the records that are already there
        WHILE i < ic LOOP
            cur := null;
            j   := 0;

            -- loop new array
            WHILE j < jc LOOP
                IF data_old->i->>key_val = data_new->j->>key_val THEN
                    cur := data_new->>j;
                    add := false;
                END IF;
                j := j + 1;
            END LOOP;

            -- add or replace
            IF add THEN
                ret := ret || format('[%s]', data_old->>i)::jsonb;
            ELSE
                ret := ret || format('[%s]', cur)::jsonb;
            END IF;

            add := true;
            i   := i + 1;
        END LOOP;

        -- loop through the new data again and add any values not in ret
        ic := jsonb_array_length(ret);
        j  := 0;
        WHILE j < jc LOOP
            i   := 0;
            add := true;

            WHILE i < ic LOOP
                IF ret->i->>key_val = data_new->j->>key_val THEN
                    add := false;
                END IF;

                i := i + 1;
            END LOOP;

            IF add THEN
                ret := ret || format('[%s]', data_new->>j)::jsonb;
            END IF;

            j := j + 1;
        END LOOP;
    ELSE
        ret := data_new;
    END IF;

    RETURN ret;
END
$$
LANGUAGE plpgsql IMMUTABLE;

Running this should give you the desired result

SELECT json_array_merge(
    '[{"fav": 3, "is_active": true, "date": "2019-00-00 11:07:05.710000"},{"fav": 1, "is_active": false, "date": "2020-00-00 11:07:05.710000"}]',
    '[{"fav": 1, "is_active": true, "date": "1999-00-00 11:07:05.710000"},{"fav": 2, "is_active": true, "date": "1998-00-00 11:07:05.710000"}]',
    'fav'
)


问:
Check if an object exist in an array in Angular 6
I have an array of categories: this.categories

```<code>[ { "id": 6, "name": "categories.ladies_team" }, { "id": 2, "name": "categories.junior_team" }, { "id": 7, "name": "categories.master" }, { "id": 5, "name": "categories.ladies_single" }, { "id": 1, "name": "categories.junior" }, { "id": 3, "name": "categories.men_single" }, { "id": 4, "name": "categories.men_team" } ]
</code>```

Now I have a new element:

```<code>const newCategory = {
    id: category.id,
    name: category.name
};
</code>```

I would like to insert it if not present.

I tried:

```<code>if (!this.categories.includes(newCategory)) {
    this.categories.push(newCategory);
  }
</code>```

but it is not working...

What am I doing wrong ?

答:
The solution given by user184994 didn't worked for me, It was only fetching the first element. I tried like this which worked for me.</p>

```<code>let data = this.categories.find(ob => ob.id === newCategory.id);
if(data === null){
 this.categories.push(newCategory);
}
</code>```

Body:
I have an array of categories: this.categories

[ { "id": 6, "name": "categories.ladies_team" }, { "id": 2, "name": "categories.junior_team" }, { "id": 7, "name": "categories.master" }, { "id": 5, "name": "categories.ladies_single" }, { "id": 1, "name": "categories.junior" }, { "id": 3, "name": "categories.men_single" }, { "id": 4, "name": "categories.men_team" } ]

Now I have a new element:

const newCategory = {
    id: category.id,
    name: category.name
};

I would like to insert it if not present.

I tried:

if (!this.categories.includes(newCategory)) {
    this.categories.push(newCategory);
  }

but it is not working...

What am I doing wrong ?

Body:
The solution given by user184994 didn't worked for me, It was only fetching the first element. I tried like this which worked for me.

let data = this.categories.find(ob => ob.id === newCategory.id);
if(data === null){
 this.categories.push(newCategory);
}


问:
How to get the browser page URL without the domain name in the component's jsp/html aem6.3?
Let's say my page url is www.test.com/myproject/en/test.html. Now I need to get '/myproject/en/test.html' in my component's jsp/html file. We are using sightly.

I am trying to use the below code to achieve it-

```<code><script>
    var x = window.location.pathname;
alert(x);
</script>
</code>```

I am getting the value /myproject/en/test.html in variable x, but not able to use the value in the meta tag as below-

```<code><link rel="icon" href="https://mywebsite.com ${x}">
</code>```

How can I pass x's value here in the meta tag? Or, is there any other way to achieve it?

答:
You can directly use the request object (Java-backed Objects) provided by Sightly.

For complete URL:

```<code>${request.requestURL.toString}
</code>```

For current page path:

```<code>${currentPage.path} // returns only the path without domain name
</code>```

For specific parts of a URL:

```<code>${request.scheme} // returns https or http
${request.serverName} // returns server name eg: stackoverflow.com
${request.serverPort} // returns server port eg: 4502 for AEM
${request.requestURI} // returns URI eg: /content/test.html
</code>```

Concatenate the specific parts to create your desired url in Sighlty:

```<code><sly data-sly-test.scheme="${request.scheme}"/>
<sly data-sly-test.servername="${request.serverName}"/>
<sly data-sly-test.serverport="${request.serverPort}"/>
<sly data-sly-test.uri="${request.requestURI}"/>

<link rel="icon" href="${scheme}://${servername}:${serverport}${uri}">
</code>```

Methods available under request object: https://sling.apache.org/apidocs/sling7/org/apache/sling/api/SlingHttpServletRequest.html

Other helpful HTL Global Objects:
https://docs.adobe.com/content/help/en/experience-manager-htl/using/htl/global-objects.html

Body:
Let's say my page url is www.test.com/myproject/en/test.html. Now I need to get '/myproject/en/test.html' in my component's jsp/html file. We are using sightly.

I am trying to use the below code to achieve it-

I am getting the value /myproject/en/test.html in variable x, but not able to use the value in the meta tag as below-

<link rel="icon" href="https://mywebsite.com ${x}">

How can I pass x's value here in the meta tag? Or, is there any other way to achieve it?

Body:
You can directly use the request object (Java-backed Objects) provided by Sightly.

For complete URL:

${request.requestURL.toString}

For current page path:

${currentPage.path} // returns only the path without domain name

For specific parts of a URL:

${request.scheme} // returns https or http
${request.serverName} // returns server name eg: stackoverflow.com
${request.serverPort} // returns server port eg: 4502 for AEM
${request.requestURI} // returns URI eg: /content/test.html

Concatenate the specific parts to create your desired url in Sighlty:

<sly data-sly-test.scheme="${request.scheme}"/>
<sly data-sly-test.servername="${request.serverName}"/>
<sly data-sly-test.serverport="${request.serverPort}"/>
<sly data-sly-test.uri="${request.requestURI}"/>

<link rel="icon" href="${scheme}://${servername}:${serverport}${uri}">

Methods available under request object: https://sling.apache.org/apidocs/sling7/org/apache/sling/api/SlingHttpServletRequest.html

Other helpful HTL Global Objects:
https://docs.adobe.com/content/help/en/experience-manager-htl/using/htl/global-objects.html


问:
Java ClassNotFound Exception
My application tries to execute the following line of code

```
<code>
JMFSecurity jmfSecurity = JMFSecurityManager.getJMFSecurity();
</code>
```

That line throws the following exception. Here is a stack trace:

```
<code>
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/media/JMFSecurityManager
        at com.compunetix.vsd.stix.main.JMFUtilities.Registry.(Registry.java:71)
        at com.compunetix.vsd.stix.main.JMFUtilities.JMFRunner.getJMFPropertiesFileLocation(JMFRunner.java:129)
        at com.compunetix.vsd.stix.main.Main.setUpJMF(Main.java:274)
        at com.compunetix.vsd.stix.main.Main.main(Main.java:166)
Caused by: java.lang.ClassNotFoundException: com.sun.media.JMFSecurityManager
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        ... 4 more
</code>
```

Any ideas why this might be throwing an exception. This used to work fine. I didn't make any changes to this file. Any ideas?

答:
ClassNotFoundException means the class isn't on your classpath.

You're using a class from the com.sun package. Those classes are implementation details, not public APIs. You might have switched to a version of the JVM that implements things differently. Generally, depending on com.sun classes is a bad idea.

Title: Java ClassNotFound Exception

Body:
My application tries to execute the following line of code

JMFSecurity jmfSecurity = JMFSecurityManager.getJMFSecurity();

That line throws the following exception. Here is a stack trace:

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/media/JMFSecurityManager
        at com.compunetix.vsd.stix.main.JMFUtilities.Registry.(Registry.java:71)
        at com.compunetix.vsd.stix.main.JMFUtilities.JMFRunner.getJMFPropertiesFileLocation(JMFRunner.java:129)
        at com.compunetix.vsd.stix.main.Main.setUpJMF(Main.java:274)
        at com.compunetix.vsd.stix.main.Main.main(Main.java:166)
Caused by: java.lang.ClassNotFoundException: com.sun.media.JMFSecurityManager
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        ... 4 more

Any ideas why this might be throwing an exception. This used to work fine. I didn't make any changes to this file. Any ideas?


问:
What is `"dev" true` in package-lock.json for?
What does "dev" true means in package-lock.json file?

In my case it is automatically updated when I perform npm operations.

How can we remove it?

答:
I think this paragraph tries to illustrate how the package dependency's dev: true is assigned.

Directly development dependency -> dev: true

With only indirect development dependency -> dev: true

Directly development dependency however
it also has indirect non-develop dependency -> no dev: true

In other words, once a develop dependency package is indirectly dependent by a non-development package, it shall be dev: false and thus it will be included in the build process. The purpose of this rule is to make sure that packages needed by the non-develop package will not have "dev: true".

Besides, if I install via npm install -D <name>, then the package will be installed as the develop package thus no dev: true changes may occur. However, if install via npm install <name>, this may remove many existing dependencies' "dev: true" attribute.

For example, I run npm install -D bestzip in my project and the result is:

53 dependencies with "dev": true added

Run npm install bestzip and the result is:

53 dependencies without "dev": true added

43 existing dependencies' "dev": true attribute are removed


问:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'
This is the Warning im getting in console, Im confused with this warning:</p>
```<code>Loading class `com.mysql.jdbc.Driver'.
This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
The driver is automatically registered via the SPI and manual loading
of the driver class is generally unnecessary.
</code>```

答:
There important changes to the Connector/J API going from version 5.1 to 8.0. You might need to adjust your API calls accordingly if the version you are using falls above 5.1.

please visit MySQL on the following link for more information https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-api-changes.html

Body:
This is the Warning im getting in console, Im confused with this warning:

Loading class `com.mysql.jdbc.Driver'.
This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
The driver is automatically registered via the SPI and manual loading
of the driver class is generally unnecessary.


问:
Select top * from 2 table orderb by some field
I have 2 table like this

[Info]

[Score]

I want to select top3 * orderby score in May DESC
the result should be look like this.

答:
The following will be helpfull.</p>

```<code>SELECT TOP 3 S.User_Id, SUM(S.Score) Score, U.Name, U.Age
FROM Info U
INNER JOIN Score S ON U.User_Id = S.User_Id
WHERE MONTH(S.Date) = 5 --Only May Month.
GROUP BY S.User_Id, U.Name, U.Age
ORDER BY 2 DESC
</code>```

Body:
The following will be helpfull.

SELECT TOP 3 S.User_Id, SUM(S.Score) Score, U.Name, U.Age
FROM Info U
INNER JOIN Score S ON U.User_Id = S.User_Id
WHERE MONTH(S.Date) = 5 --Only May Month.
GROUP BY S.User_Id, U.Name, U.Age
ORDER BY 2 DESC


问:
Unable to display my CreateForm in Django
I have created a form and a view in Django and I'm trying to display it in the HTML but it isn't loading anything and I don't know why.

alumno2.html

```<code>{% block header %}
    <header class="masthead bg-white text-dark text-uppercase">
        <div class="container">
            <h3 class="text-center">Añadir alumno</h3>
            <form method="post">
                {% csrf_token %}
                    {{ form.as_p }}
                <button class="btn btn-secondary" type="submit">Guardar</button>
            </form>
        </div>
    </header>
{% endblock %}
</code>```

form.py

```<code>class AlumnoForm2(forms.ModelForm):
    class Meta:
        model = Alumno
        #fields = ['dni', 'nombre', 'apellido1', 'apellido2','email','repetidor']
        fields = ['dni', 'nombre', 'apellido1', 'apellido2','email','repetidor','curs']

        labels = {
            'dni': 'dni',
            'nombre': 'nombre',
            'apellido1': 'Primer Apellido',
            'apellido2': 'Segundo Apellido',
            'email': 'Email',
            'repetidor': 'repetidor',
            'curs': 'curs'
        }

        widgets = {
            'dni': forms.TextInput(attrs={'class': 'form-control'}),
            'nombre': forms.TextInput(attrs={'class': 'form-control'}),
            'apellido1': forms.TextInput(attrs={'class': 'form-control'}),
            'apellido2': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.TextInput(attrs={'class': 'form-control'}),
            'repetidor': forms.CheckboxInput(attrs={'class':'form-control-checkbox','id': 'repetidor'}),
            'curs':forms.Select(attrs={'class': 'form-control'}),
        }
</code>```

view.py

```<code>class crea_alumno(CreateView):
    model = Alumno
    form_class = AlumnoForm2
    template_name = '/alumno2.html'
    success_url = reverse_lazy('mostrar_alumnos')
</code>```

url.py

```<code>url(r'^alumno2/$', crea_alumno.as_view(),name='alumno2'),
</code>```

models.py

```<code>class Alumno(models.Model):
    dni = models.CharField(max_length=9,primary_key=True)
    nombre = models.CharField(max_length=100)
    apellido1 = models.CharField('Primer apellido',max_length=50)
    apellido2 = models.CharField('Segundo apellido',max_length=50)
    email = models.EmailField("Correo electronico",null=True)
    repetidor = models.BooleanField()
    curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos")
    Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel'))
    Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica'))
    Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso'))

    def __str__(self):
        return self.dni
</code>```

the html only display the save button, is not loading the create form. The html is inside the template folders thats why I have this urls.

EDIT:
I have removed the template I had also

```<code>url(r'^alumno2/$', TemplateView.as_view(template_name='alumno2.html'),name='alumno2'),
</code>```

and I'm not sure if i need to put this in the url.py so now I only have the view and is unable to find my template withouth that

答:
Remove the line

```<code>url(r'^alumno2/$', TemplateView.as_view(template_name='alumno2.html'),name='alumno2'),
</code>```

from your urls.py and only keep this one:

```<code>url(r'^alumno2/$', crea_alumno.as_view(),name='alumno2'),
</code>```

And inside your view, remove the / in the template name: instead of

```<code>template_name = '/alumno2.html'
</code>```

Use

```<code>template_name = 'alumno2.html'
</code>```

And replace CreateView with FormView as per the documentation

Body:
I have created a form and a view in Django and I'm trying to display it in the HTML but it isn't loading anything and I don't know why.

alumno2.html

{% block header %}

Añadir alumno

            <form method="post">
                {% csrf_token %}
                    {{ form.as_p }}
                <button class="btn btn-secondary" type="submit">Guardar</button>
            </form>

{% endblock %}

form.py

class AlumnoForm2(forms.ModelForm):
    class Meta:
        model = Alumno
        #fields = ['dni', 'nombre', 'apellido1', 'apellido2','email','repetidor']
        fields = ['dni', 'nombre', 'apellido1', 'apellido2','email','repetidor','curs']

        labels = {
            'dni': 'dni',
            'nombre': 'nombre',
            'apellido1': 'Primer Apellido',
            'apellido2': 'Segundo Apellido',
            'email': 'Email',
            'repetidor': 'repetidor',
            'curs': 'curs'
        }

        widgets = {
            'dni': forms.TextInput(attrs={'class': 'form-control'}),
            'nombre': forms.TextInput(attrs={'class': 'form-control'}),
            'apellido1': forms.TextInput(attrs={'class': 'form-control'}),
            'apellido2': forms.TextInput(attrs={'class': 'form-control'}),
            'email': forms.TextInput(attrs={'class': 'form-control'}),
            'repetidor': forms.CheckboxInput(attrs={'class':'form-control-checkbox','id': 'repetidor'}),
            'curs':forms.Select(attrs={'class': 'form-control'}),
        }

view.py

class crea_alumno(CreateView):
    model = Alumno
    form_class = AlumnoForm2
    template_name = '/alumno2.html'
    success_url = reverse_lazy('mostrar_alumnos')

url.py

url(r'^alumno2/$', crea_alumno.as_view(),name='alumno2'),

models.py

class Alumno(models.Model):
    dni = models.CharField(max_length=9,primary_key=True)
    nombre = models.CharField(max_length=100)
    apellido1 = models.CharField('Primer apellido',max_length=50)
    apellido2 = models.CharField('Segundo apellido',max_length=50)
    email = models.EmailField("Correo electronico",null=True)
    repetidor = models.BooleanField()
    curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos")
    Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel'))
    Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica'))
    Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso'))

    def __str__(self):
        return self.dni

the html only display the save button, is not loading the create form. The html is inside the template folders thats why I have this urls.

EDIT:
I have removed the template I had also

url(r'^alumno2/$', TemplateView.as_view(template_name='alumno2.html'),name='alumno2'),

and I'm not sure if i need to put this in the url.py so now I only have the view and is unable to find my template withouth that

Body:
Remove the line

url(r'^alumno2/$', TemplateView.as_view(template_name='alumno2.html'),name='alumno2'),

from your urls.py and only keep this one:

url(r'^alumno2/$', crea_alumno.as_view(),name='alumno2'),

And inside your view, remove the / in the template name: instead of

template_name = '/alumno2.html'

Use

template_name = 'alumno2.html'

And replace CreateView with FormView as per the documentation


问:
What is wrong with my code in Python Jupyter Notebook?
When I run the code and input "1" or "2" it gives me the response

Sorry, we didn't understand your selection.

How do I fix this so that it gives me the correct answer?

I've Tried making "1" and "2" a string.

```<code>def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if response == "1":
        return new_customer()
    elif response == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()
</code>```

No error messages, It won't give me the answer I am looking for which is either one of these functions: new_customer() or existing_customer()

答:
Try by converting response in to string and then compare.

```<code>def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if str(response) == "1":
        return new_customer()
    elif str(response) == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()
</code>```

Body:
When I run the code and input "1" or "2" it gives me the response

Sorry, we didn't understand your selection.

How do I fix this so that it gives me the correct answer?

I've Tried making "1" and "2" a string.

def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if response == "1":
        return new_customer()
    elif response == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()

No error messages, It won't give me the answer I am looking for which is either one of these functions: new_customer() or existing_customer()

Body:
Try by converting response in to string and then compare.

def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if str(response) == "1":
        return new_customer()
    elif str(response) == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()


问:
Create Bar Chart in Excel with Apache POI
I'm trying to create a Bar Chart in an XLSX Spreadsheet using Apache POI, but Excel keeps saying that there's a problem with the content and deleting the chart when I try to open the file. Here's the full code of what I'm trying to do:

```<code>public static void createBarChart() {

        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet2");
        Row row;
        Cell cell;

        row = sheet.createRow(0);
        row.createCell(0);
        row.createCell(1).setCellValue("HEADER 1");
        row.createCell(2).setCellValue("HEADER 2");
        row.createCell(3).setCellValue("HEADER 3");

        for (int r = 1; r < 5; r++) {
            row = sheet.createRow(r);
            cell = row.createCell(0);
            cell.setCellValue("Serie " + r);
            cell = row.createCell(1);
            cell.setCellValue(123);
            cell = row.createCell(2);
            cell.setCellValue(456);
            cell = row.createCell(3);
            cell.setCellValue(789);
        }

        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 5, 20);

        Chart chart = drawing.createChart(anchor);

        CTChart ctChart = ((XSSFChart) chart).getCTChart();

        ctChart.addNewTitle();

        CTPlotArea ctPlotArea = ctChart.getPlotArea();
        CTBarChart ctBarChart = ctPlotArea.addNewBarChart();

        ctBarChart.addNewBarDir().setVal(STBarDir.COL);
        ctBarChart.addNewGrouping().setVal(STBarGrouping.CLUSTERED);
        ctBarChart.addNewVaryColors().setVal(false);

        // First series
        CTBarSer ctBarSer = ctBarChart.addNewSer();

        ctBarSer.addNewIdx().setVal(0);
        ctBarSer.addNewOrder().setVal(0);

        // [01] Title
        CTSerTx ctSerTx = ctBarSer.addNewTx();
        CTStrRef ctSerTxStrRef = ctSerTx.addNewStrRef();
        ctSerTxStrRef.setF("Sheet2!$A$2");

        CTStrData strCache = ctSerTxStrRef.addNewStrCache();
        strCache.addNewPtCount().setVal(1);
        CTStrVal newPt = strCache.addNewPt();
        newPt.setV("Serie 1");
        newPt.setIdx(0);

        // [01] SpPr
        CTShapeProperties spPr = ctBarSer.addNewSpPr();
        CTSolidColorFillProperties solidFill = spPr.addNewSolidFill();
        solidFill.addNewSchemeClr().setVal(STSchemeColorValImpl.ACCENT_1);
        spPr.addNewLn().addNewNoFill();
        spPr.addNewEffectLst();

        // [01] Invert if negative
        ctBarSer.addNewInvertIfNegative().setVal(false);

        // [01] Series titles
        CTAxDataSource newCat = ctBarSer.addNewCat();
        CTStrRef addNewStrRef = newCat.addNewStrRef();
        addNewStrRef.setF("Sheet2!$B$1:$D$1");

        CTStrData addNewStrCache = addNewStrRef.addNewStrCache();
        addNewStrCache.addNewPtCount().setVal(3);

        CTStrVal pt1 = addNewStrCache.addNewPt();
        pt1.setIdx(0);
        pt1.setV(sheet.getRow(0).getCell(1).getStringCellValue());

        CTStrVal pt2 = addNewStrCache.addNewPt();
        pt2.setIdx(1);
        pt2.setV(sheet.getRow(0).getCell(2).getStringCellValue());

        CTStrVal pt3 = addNewStrCache.addNewPt();
        pt3.setIdx(2);
        pt3.setV(sheet.getRow(0).getCell(3).getStringCellValue());

        // [01] Series values
        CTNumDataSource newVal = ctBarSer.addNewVal();
        CTNumRef numRef = newVal.addNewNumRef();
        numRef.setF("Sheet2!$B$2:$D$2");
        CTNumData numCache = numRef.addNewNumCache();
        numCache.addNewPtCount().setVal(3);

        CTNumVal numpt1 = numCache.addNewPt();
        numpt1.setIdx(0);
        numpt1.setV(String.valueOf(sheet.getRow(1).getCell(1).getNumericCellValue()));

        CTNumVal numpt2 = numCache.addNewPt();
        numpt2.setIdx(1);
        numpt2.setV(String.valueOf(sheet.getRow(1).getCell(2).getNumericCellValue()));

        CTNumVal numpt3 = numCache.addNewPt();
        numpt3.setIdx(2);
        numpt3.setV(String.valueOf(sheet.getRow(1).getCell(3).getNumericCellValue()));

        // dLbls
        CTDLbls dLbls = ctBarChart.addNewDLbls();
        dLbls.addNewShowBubbleSize().setVal(false);
        dLbls.addNewShowLegendKey().setVal(false);
        dLbls.addNewShowCatName().setVal(false);
        dLbls.addNewShowSerName().setVal(false);
        dLbls.addNewShowPercent().setVal(false);
        dLbls.addNewShowVal().setVal(false);

        FileOutputStream fileOut = new FileOutputStream("barchart.xlsx");
        wb.write(fileOut);
        wb.close();
        fileOut.close();
    }
</code>```

Can anyone help me find (and, well, solve) the issue? Thanks in advance!

答:
This is the code for creating the bar chart (actually creating the column chart) in Excel using XSSF for Excel 2007 and above using the NPOI 2.4.1 nuget package.</p>

```<code>private XSSFWorkbook createBarchart()
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("WorkForceAnalytics");

        XSSFCellStyle styleHeader = (XSSFCellStyle)workbook.CreateCellStyle();
        styleHeader.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
        styleHeader.SetFont(getNewXSSFFont(workbook, styleHeader));

        XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
        style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;

        XSSFRow row1 = (XSSFRow)sheet.CreateRow(0);
        row1.CreateCell(0).SetCellValue("");

        List<string> lstdatase = new List<string>(4);
        lstdatase.Add("A1");
        lstdatase.Add("B1");
        lstdatase.Add("C1");
        lstdatase.Add("D1");
        lstdatase.Add("E1");

        for (int i = 1; i < 5; i++)
        {
            row1.CreateCell(i).SetCellValue(lstdatase[i - 1].ToString());
            row1.GetCell(i).CellStyle = styleHeader;
        }

        int rowvalue = 1;
        List<string> lstdata = new List<string>(8);
        lstdata.Add("A");
        lstdata.Add("B");
        lstdata.Add("C");
        lstdata.Add("D");
        lstdata.Add("E");
        lstdata.Add("F");
        lstdata.Add("G");
        lstdata.Add("H");

        int d = 10;

        XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
        XSSFClientAnchor anchor = (XSSFClientAnchor)drawing.CreateAnchor(0, 0, 0, 0, 6, 1, 15, 18);

        IChart chart = drawing.CreateChart(anchor);
        IChartLegend legend = chart.GetOrCreateLegend();
        legend.Position = (LegendPosition.TopRight);

        IBarChartData<string, double> data = chart.ChartDataFactory.CreateBarChartData<string, double>();

        IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
        IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
        leftAxis.Crosses = AxisCrosses.AutoZero;
        leftAxis.SetCrossBetween(AxisCrossBetween.Between);

        IChartDataSource<string> xs = DataSources.FromStringCellRange(sheet, new NPOI.SS.Util.CellRangeAddress(0, 0, 1, 5-1));

        for (int ii = 0; ii < 8; ii++)
        {
            XSSFRow rownew = (XSSFRow)sheet.CreateRow(rowvalue);
            rownew.CreateCell(0).SetCellValue(lstdata[ii].ToString());

            for (int i = 1; i < 5; i++)
            {
                rownew.CreateCell(i).SetCellValue(d);
                d++;
                rownew.GetCell(i).CellStyle = style;
            }
            rowvalue++;

            IChartDataSource<double> ys = DataSources.FromNumericCellRange(sheet, new NPOI.SS.Util.CellRangeAddress(ii + 1, ii + 1, 1, 5 - 1));
            data.AddSeries(xs, ys).SetTitle(lstdata[ii].ToString());
        }

        chart.Plot(data, bottomAxis, leftAxis);

        sheet.ForceFormulaRecalculation = true;

        string fileName = "WorkforceAnalyticsReport.xlsx";
        using (var exportData = new MemoryStream())
        {
            Response.Clear();
            workbook.Write(exportData);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
            Response.BinaryWrite(exportData.ToArray());
            Response.End();
        }
        return workbook;
    }
</code>```

Body:
I'm trying to create a Bar Chart in an XLSX Spreadsheet using Apache POI, but Excel keeps saying that there's a problem with the content and deleting the chart when I try to open the file. Here's the full code of what I'm trying to do:

public static void createBarChart() {

        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet2");
        Row row;
        Cell cell;

        row = sheet.createRow(0);
        row.createCell(0);
        row.createCell(1).setCellValue("HEADER 1");
        row.createCell(2).setCellValue("HEADER 2");
        row.createCell(3).setCellValue("HEADER 3");

        for (int r = 1; r < 5; r++) {
            row = sheet.createRow(r);
            cell = row.createCell(0);
            cell.setCellValue("Serie " + r);
            cell = row.createCell(1);
            cell.setCellValue(123);
            cell = row.createCell(2);
            cell.setCellValue(456);
            cell = row.createCell(3);
            cell.setCellValue(789);
        }

        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 5, 20);

        Chart chart = drawing.createChart(anchor);

        CTChart ctChart = ((XSSFChart) chart).getCTChart();

        ctChart.addNewTitle();

        CTPlotArea ctPlotArea = ctChart.getPlotArea();
        CTBarChart ctBarChart = ctPlotArea.addNewBarChart();

        ctBarChart.addNewBarDir().setVal(STBarDir.COL);
        ctBarChart.addNewGrouping().setVal(STBarGrouping.CLUSTERED);
        ctBarChart.addNewVaryColors().setVal(false);

        // First series
        CTBarSer ctBarSer = ctBarChart.addNewSer();

        ctBarSer.addNewIdx().setVal(0);
        ctBarSer.addNewOrder().setVal(0);

        // [01] Title
        CTSerTx ctSerTx = ctBarSer.addNewTx();
        CTStrRef ctSerTxStrRef = ctSerTx.addNewStrRef();
        ctSerTxStrRef.setF("Sheet2!$A$2");

        CTStrData strCache = ctSerTxStrRef.addNewStrCache();
        strCache.addNewPtCount().setVal(1);
        CTStrVal newPt = strCache.addNewPt();
        newPt.setV("Serie 1");
        newPt.setIdx(0);

        // [01] SpPr
        CTShapeProperties spPr = ctBarSer.addNewSpPr();
        CTSolidColorFillProperties solidFill = spPr.addNewSolidFill();
        solidFill.addNewSchemeClr().setVal(STSchemeColorValImpl.ACCENT_1);
        spPr.addNewLn().addNewNoFill();
        spPr.addNewEffectLst();

        // [01] Invert if negative
        ctBarSer.addNewInvertIfNegative().setVal(false);

        // [01] Series titles
        CTAxDataSource newCat = ctBarSer.addNewCat();
        CTStrRef addNewStrRef = newCat.addNewStrRef();
        addNewStrRef.setF("Sheet2!$B$1:$D$1");

        CTStrData addNewStrCache = addNewStrRef.addNewStrCache();
        addNewStrCache.addNewPtCount().setVal(3);

        CTStrVal pt1 = addNewStrCache.addNewPt();
        pt1.setIdx(0);
        pt1.setV(sheet.getRow(0).getCell(1).getStringCellValue());

        CTStrVal pt2 = addNewStrCache.addNewPt();
        pt2.setIdx(1);
        pt2.setV(sheet.getRow(0).getCell(2).getStringCellValue());

        CTStrVal pt3 = addNewStrCache.addNewPt();
        pt3.setIdx(2);
        pt3.setV(sheet.getRow(0).getCell(3).getStringCellValue());

        // [01] Series values
        CTNumDataSource newVal = ctBarSer.addNewVal();
        CTNumRef numRef = newVal.addNewNumRef();
        numRef.setF("Sheet2!$B$2:$D$2");
        CTNumData numCache = numRef.addNewNumCache();
        numCache.addNewPtCount().setVal(3);

        CTNumVal numpt1 = numCache.addNewPt();
        numpt1.setIdx(0);
        numpt1.setV(String.valueOf(sheet.getRow(1).getCell(1).getNumericCellValue()));

        CTNumVal numpt2 = numCache.addNewPt();
        numpt2.setIdx(1);
        numpt2.setV(String.valueOf(sheet.getRow(1).getCell(2).getNumericCellValue()));

        CTNumVal numpt3 = numCache.addNewPt();
        numpt3.setIdx(2);
        numpt3.setV(String.valueOf(sheet.getRow(1).getCell(3).getNumericCellValue()));

        // dLbls
        CTDLbls dLbls = ctBarChart.addNewDLbls();
        dLbls.addNewShowBubbleSize().setVal(false);
        dLbls.addNewShowLegendKey().setVal(false);
        dLbls.addNewShowCatName().setVal(false);
        dLbls.addNewShowSerName().setVal(false);
        dLbls.addNewShowPercent().setVal(false);
        dLbls.addNewShowVal().setVal(false);

        FileOutputStream fileOut = new FileOutputStream("barchart.xlsx");
        wb.write(fileOut);
        wb.close();
        fileOut.close();
    }

Can anyone help me find (and, well, solve) the issue? Thanks in advance!

Body:
This is the code for creating the bar chart (actually creating the column chart) in Excel using XSSF for Excel 2007 and above using the NPOI 2.4.1 nuget package.

private XSSFWorkbook createBarchart()
    {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("WorkForceAnalytics");

        XSSFCellStyle styleHeader = (XSSFCellStyle)workbook.CreateCellStyle();
        styleHeader.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
        styleHeader.SetFont(getNewXSSFFont(workbook, styleHeader));

        XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
        style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;

        XSSFRow row1 = (XSSFRow)sheet.CreateRow(0);
        row1.CreateCell(0).SetCellValue("");

        List<string> lstdatase = new List<string>(4);
        lstdatase.Add("A1");
        lstdatase.Add("B1");
        lstdatase.Add("C1");
        lstdatase.Add("D1");
        lstdatase.Add("E1");

        for (int i = 1; i < 5; i++)
        {
            row1.CreateCell(i).SetCellValue(lstdatase[i - 1].ToString());
            row1.GetCell(i).CellStyle = styleHeader;
        }

        int rowvalue = 1;
        List<string> lstdata = new List<string>(8);
        lstdata.Add("A");
        lstdata.Add("B");
        lstdata.Add("C");
        lstdata.Add("D");
        lstdata.Add("E");
        lstdata.Add("F");
        lstdata.Add("G");
        lstdata.Add("H");

        int d = 10;

        XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();
        XSSFClientAnchor anchor = (XSSFClientAnchor)drawing.CreateAnchor(0, 0, 0, 0, 6, 1, 15, 18);

        IChart chart = drawing.CreateChart(anchor);
        IChartLegend legend = chart.GetOrCreateLegend();
        legend.Position = (LegendPosition.TopRight);

        IBarChartData<string, double> data = chart.ChartDataFactory.CreateBarChartData<string, double>();

        IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);
        IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);
        leftAxis.Crosses = AxisCrosses.AutoZero;
        leftAxis.SetCrossBetween(AxisCrossBetween.Between);

        IChartDataSource<string> xs = DataSources.FromStringCellRange(sheet, new NPOI.SS.Util.CellRangeAddress(0, 0, 1, 5-1));

        for (int ii = 0; ii < 8; ii++)
        {
            XSSFRow rownew = (XSSFRow)sheet.CreateRow(rowvalue);
            rownew.CreateCell(0).SetCellValue(lstdata[ii].ToString());

            for (int i = 1; i < 5; i++)
            {
                rownew.CreateCell(i).SetCellValue(d);
                d++;
                rownew.GetCell(i).CellStyle = style;
            }
            rowvalue++;

            IChartDataSource<double> ys = DataSources.FromNumericCellRange(sheet, new NPOI.SS.Util.CellRangeAddress(ii + 1, ii + 1, 1, 5 - 1));
            data.AddSeries(xs, ys).SetTitle(lstdata[ii].ToString());
        }

        chart.Plot(data, bottomAxis, leftAxis);

        sheet.ForceFormulaRecalculation = true;

        string fileName = "WorkforceAnalyticsReport.xlsx";
        using (var exportData = new MemoryStream())
        {
            Response.Clear();
            workbook.Write(exportData);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
            Response.BinaryWrite(exportData.ToArray());
            Response.End();
        }
        return workbook;
    }


问:
Unit testing, statics, and factories
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

```<code>double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah
</code>```

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you

答: A problem with static factories is, that you are not able to replace the factories (and sometime the objects created by the factories) by mocks. - That is one reason why IOC Containers are so usefull.</p>

Title: Unit testing, statics, and factories

Body:
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you


问:
I have no experience with XML. How do i understand what is written in this XML file?
I have to start creating an android application. However, I have no experience with XML and understand the language. This XML file has data stored that I must use to create a Java program. I do not understand what I am looking at or how to read this language. I want to interpret the data so I can start coding it in Java. Please help.

I have tried to watch videos and learn XML but I cannot seem to apply the basics to interpret the information given to me in this file.

```<code><task name="neddle decompression" steps="8">

    <step
        description="Obtain a 14 gauge needle with catheter
        from your first aid kit.">
        <aid aid="needle.jpg">
        </aid>
        <aid aid="needle.avi">
        </aid>
    </step>

    <step description="Locate position on chest.">
        <aid aid="position.jpg">
        </aid>
    </step>

    <step description="Prepare chest area with antiseptic.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Insert the needle at a 90 degree angle.">
        <aid aid="insert.jpg">
        </aid>
    </step>

    <step
        description="Stop advancing the needle once a hiss of pop of air is heard. You should feel a 'pop' as the needle enters the chest cavity.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Hold the catheter in place and remove the needle.">
        <aid aid="catheter.jpg">
        </aid>
    </step>

    <step description="Leave the catheter and safely dispose of the needle.">
        <aid aid="dispose.jpg">
        </aid>
    </step>

    <step
        description="Tape the catheter in place and monitor the casualty until the medivac is available to insert a chest tube.">
        <aid image="tape.jpg">
        </aid>
    </step>

</task>

<task name="task2" steps="2">

    <step description="step1">
        <aid image="image1.png">
        </aid>
    </step>

    <step destription="step2">
        <aid aid="image.png">
        </aid>
        <aid aid="image3.avi">
        </aid>
    </step>

</task>
</code>```

I expect to get a guide of the classes and attributes I need to have in the Java program from this file.

答: Here is a great tutorial that is free in Udacity. It is also made by Google to help new android developers: https://classroom.udacity.com/courses/ud834</p>

Body:
I have to start creating an android application. However, I have no experience with XML and understand the language. This XML file has data stored that I must use to create a Java program. I do not understand what I am looking at or how to read this language. I want to interpret the data so I can start coding it in Java. Please help.

I have tried to watch videos and learn XML but I cannot seem to apply the basics to interpret the information given to me in this file.

<task name="neddle decompression" steps="8">

    <step
        description="Obtain a 14 gauge needle with catheter
        from your first aid kit.">
        <aid aid="needle.jpg">
        </aid>
        <aid aid="needle.avi">
        </aid>
    </step>

    <step description="Locate position on chest.">
        <aid aid="position.jpg">
        </aid>
    </step>

    <step description="Prepare chest area with antiseptic.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Insert the needle at a 90 degree angle.">
        <aid aid="insert.jpg">
        </aid>
    </step>

    <step
        description="Stop advancing the needle once a hiss of pop of air is heard. You should feel a 'pop' as the needle enters the chest cavity.">
        <aid aid="none">
        </aid>
    </step>

    <step description="Hold the catheter in place and remove the needle.">
        <aid aid="catheter.jpg">
        </aid>
    </step>

    <step description="Leave the catheter and safely dispose of the needle.">
        <aid aid="dispose.jpg">
        </aid>
    </step>

    <step
        description="Tape the catheter in place and monitor the casualty until the medivac is available to insert a chest tube.">
        <aid image="tape.jpg">
        </aid>
    </step>

</task>

<task name="task2" steps="2">

    <step description="step1">
        <aid image="image1.png">
        </aid>
    </step>

    <step destription="step2">
        <aid aid="image.png">
        </aid>
        <aid aid="image3.avi">
        </aid>
    </step>

</task>

I expect to get a guide of the classes and attributes I need to have in the Java program from this file.