问:
Concatenation and MD5 with awk
I would like to concatenate all columns in a CSV file and then apply an MD5 hash.

I would like to use awk.

With this code, I get the concatenation of the third column.

```<code>awk -F'#' '{  { printf "%s",$3 } }'
</code>```

and I can get the hash with this code

```<code>echo -n "HELLO WORLD" | md5sum
</code>```

Can anyone help me to integrate those two methods? First concat all columns, then apply the MD5 hash.

Sample CSV:

```<code>A#B#C#D
E#F#G#H
I#J#K#L
</code>```

The output will be:

```<code> md5(ABCD)
md5(EFGH)
md5(IJKL)
</code>```

答:
concatenating columns will mean removing the delimiter, here is a simpler approach

```<code>tr -d '#' <file | md5sum
</code>```

if you want to extract the third column only and concatenate rows into one big string (but why since you're losing information)

```<code>cut -d# -f3 file | tr -d '\n' | md5sum
</code>```

note that now these third columns

```<code>ab
c
</code>```

and

```<code>a
bc
</code>```

will end up with the same hash.  Better to preserve the distinctness of the fields by concatenating the values with the same delimiter

```<code>cut -d# -f3 file | paste -sd# | md5sum
</code>```

however, without concatenation you can assume the fields are separated with the newline delimiter and go with

```<code>cut -d# -f3 file | md5sum
</code>```

unless there is an unspecified reason.

UPDATE:  you want create md5 hash for each row! Which was the critical information missing in the question.

You can't pipe into md5sum the lines as in the other programs (you need a new invocation each time).  One way to address this is

```<code>tr -d '#' <file | while read line; do echo $line | md5sum; done

ed5d34c74e59d16bd6d5b3683db655c3  -
8ad37f51cbc6de792c885acf17ba7e40  -
fe672d984bef56cbfce488080f8055b7  -
</code>```

however, note that you're losing information if your fields are varying in length and overlapping in values.

For example, AB#C and A#BC will generate the same hash, which may or may not be desired but I guess you might have not considered.

Title: Concatenation and MD5 with awk

Body:
I would like to concatenate all columns in a CSV file and then apply an MD5 hash.

I would like to use awk.

With this code, I get the concatenation of the third column.

awk -F'#' '{  { printf "%s",$3 } }'

and I can get the hash with this code

echo -n "HELLO WORLD" | md5sum

Can anyone help me to integrate those two methods? First concat all columns, then apply the MD5 hash.

Sample CSV:

A#B#C#D
E#F#G#H
I#J#K#L

The output will be:

 md5(ABCD)
md5(EFGH)
md5(IJKL)

Body:
concatenating columns will mean removing the delimiter, here is a simpler approach

tr -d '#' <file | md5sum

if you want to extract the third column only and concatenate rows into one big string (but why since you're losing information)

cut -d# -f3 file | tr -d '\n' | md5sum

note that now these third columns

ab
c

and

a
bc

will end up with the same hash.  Better to preserve the distinctness of the fields by concatenating the values with the same delimiter

cut -d# -f3 file | paste -sd# | md5sum

however, without concatenation you can assume the fields are separated with the newline delimiter and go with

cut -d# -f3 file | md5sum

unless there is an unspecified reason.

UPDATE:  you want create md5 hash for each row! Which was the critical information missing in the question.

You can't pipe into md5sum the lines as in the other programs (you need a new invocation each time).  One way to address this is

tr -d '#' <file | while read line; do echo $line | md5sum; done

ed5d34c74e59d16bd6d5b3683db655c3  -
8ad37f51cbc6de792c885acf17ba7e40  -
fe672d984bef56cbfce488080f8055b7  -

however, note that you're losing information if your fields are varying in length and overlapping in values.

For example, AB#C and A#BC will generate the same hash, which may or may not be desired but I guess you might have not considered.


来源: stackexchange

问:
spaCy needs a file that is not there: strings.json
I am running pytextrank were in its second stage, I get this error from spaCy:

```<code>File "C:\Anaconda3\lib\pathlib.py", line 371, in wrapped return strfunc(str(pathobj), *args)

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Anaconda3\\lib\\site-packages\\spacy\\data\\en\\vocab\\strings.json'
</code>```

I looked for strings.json but there is no such thing.

The interesting thing is that similar error with pathlib.py existed when I installed spaCy with the following error code:

```<code>OSError: Symbolic link privilege not held
</code>```

Do you guys have any idea ?
Thanks

答:
Finallly, I can answer question in stackoverflow. I occurred same problem but solved it eventually. Here is my suggestion:

1. Download spaCy model from python -m spacy or github

both way are very convenient.

1). from python spacy:

```<code>python3 -m spacy download en
</code>```

assume you are using python3+, the can be done automatically and generate new packages of model, which you can import via import en or using spacy.load('en')

2). from github

transfer link, selet the newest version and download it.

2. (if you not using python -m way then you want manually link the model) Link your downloaded model

this is the most important part, you must unzip your downloaded tar or gzip file, and get a folder, however this is still not the link path you want.

```<code>.
├── en_core_web_md-1.2.1
│   ├── deps
│   │   ├── config.json
│   │   └── model
│   ├── meta.json
│   ├── ner
│   │   ├── config.json
│   │   └── model
│   ├── pos
│   │   ├── config.json
│   │   └── model
│   └── vocab
│       ├── gazetteer.json
│       ├── lexemes.bin
│       ├── oov_prob
│       ├── serializer.json
│       ├── strings.json
│       └── vec.bin
</code>```

you must link the folder with the structure. which spacy will link the folder via your link-shortcut name.

here is the link script you need:

```<code>base_path=`pwd`
sudo python3 -m spacy link ${base_path}/en_core_web_md-1.2.1 en_core_web --force
</code>```

you can create a .sh file just alongside that folder and run it.

that's it!

ContentLicense: CC BY-SA 3.0

Body:
I am running pytextrank were in its second stage, I get this error from spaCy:

File "C:\Anaconda3\lib\pathlib.py", line 371, in wrapped return strfunc(str(pathobj), *args)

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Anaconda3\\lib\\site-packages\\spacy\\data\\en\\vocab\\strings.json'

I looked for strings.json but there is no such thing.

The interesting thing is that similar error with pathlib.py existed when I installed spaCy with the following error code:

OSError: Symbolic link privilege not held

Do you guys have any idea ?
Thanks

Body:
Finallly, I can answer question in stackoverflow. I occurred same problem but solved it eventually. Here is my suggestion:

1. Download spaCy model from python -m spacy or github

both way are very convenient.

1). from python spacy:

python3 -m spacy download en

assume you are using python3+, the can be done automatically and generate new packages of model, which you can import via import en or using spacy.load('en')

2). from github

transfer link, selet the newest version and download it.

2. (if you not using python -m way then you want manually link the model) Link your downloaded model

this is the most important part, you must unzip your downloaded tar or gzip file, and get a folder, however this is still not the link path you want.

.
├── en_core_web_md-1.2.1
│   ├── deps
│   │   ├── config.json
│   │   └── model
│   ├── meta.json
│   ├── ner
│   │   ├── config.json
│   │   └── model
│   ├── pos
│   │   ├── config.json
│   │   └── model
│   └── vocab
│       ├── gazetteer.json
│       ├── lexemes.bin
│       ├── oov_prob
│       ├── serializer.json
│       ├── strings.json
│       └── vec.bin

you must link the folder with the structure. which spacy will link the folder via your link-shortcut name.

here is the link script you need:

base_path=`pwd`
sudo python3 -m spacy link ${base_path}/en_core_web_md-1.2.1 en_core_web --force

you can create a .sh file just alongside that folder and run it.

that's it!


问:
Tokens and wildcards in for loops
I am trying to create a txt file called "index" which contains a list of the names of a set of files. The files follow the same naming format: 01 - aaa; 02 - bbb; 03 - ccc etc where the letters represent whatever the name of the file is. I want to create a txt file with the names as follows:

aaa

bbb

ccc

i.e removing the numbers, hyphen and extension in a vertical list which I can then copy elsewhere.

This is the code I have written so far:

```<code>@echo off & setlocal EnableDelayedExpansion
for /f "tokens=3* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==index.bat (
        echo %%g >> index.txt
    )
)
endlocal
</code>```

This correctly loops through the files and ignores index.bat (which is the file I'm running) but it outputs the third token only and not all subsequent tokens. The * wildcard should mean it outputs the entire rest of the string but it doesn't seem to work?

Any other general improvements would be appreciated - only been learning batch for a week or so.

EDIT: Magoo and npocmaka's answers below solved it. %%h contains the wildcard information. "tokens=2* delims= " will assign the 2nd token to %%g and the 3rd + the rest to %%h.

The working code is as follows:

```<code>@echo off & setlocal EnableDelayedExpansion
for /f "tokens=2* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==%%~nx0 (
        set name=%%h
        echo !name:~0,-4! >> index.txt
    )
)
endlocal
</code>```

if not %%~nxg==%%~nx0 excludes the batch file from the loop, set name=%%h creates a new variable so that I can do a substring to remove the extension. echo !name:~0,-4! is the substring and it selects the entire string except the last 4 characters so as to exclude the file extension and then >> index.txt creates a new text file in the same directory with only the required characters.

答:
In your code, %%h would contain the remainder of the line.

You might consider changing to tokens=2* when %%h would contain the 3rd and later tokens.

You may want to add /a-d into the dir to ignore any directorynames encountered.

Title: Tokens and wildcards in for loops

Body:
I am trying to create a txt file called "index" which contains a list of the names of a set of files. The files follow the same naming format: 01 - aaa; 02 - bbb; 03 - ccc etc where the letters represent whatever the name of the file is. I want to create a txt file with the names as follows:

aaa

bbb

ccc

i.e removing the numbers, hyphen and extension in a vertical list which I can then copy elsewhere.

This is the code I have written so far:

@echo off & setlocal EnableDelayedExpansion
for /f "tokens=3* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==index.bat (
        echo %%g >> index.txt
    )
)
endlocal

This correctly loops through the files and ignores index.bat (which is the file I'm running) but it outputs the third token only and not all subsequent tokens. The * wildcard should mean it outputs the entire rest of the string but it doesn't seem to work?

Any other general improvements would be appreciated - only been learning batch for a week or so.

EDIT: Magoo and npocmaka's answers below solved it. %%h contains the wildcard information. "tokens=2* delims= " will assign the 2nd token to %%g and the 3rd + the rest to %%h.

The working code is as follows:

@echo off & setlocal EnableDelayedExpansion
for /f "tokens=2* delims= " %%g in ('dir /b /o:n') do (
    if not %%~nxg==%%~nx0 (
        set name=%%h
        echo !name:~0,-4! >> index.txt
    )
)
endlocal

if not %%~nxg==%%~nx0 excludes the batch file from the loop, set name=%%h creates a new variable so that I can do a substring to remove the extension. echo !name:~0,-4! is the substring and it selects the entire string except the last 4 characters so as to exclude the file extension and then >> index.txt creates a new text file in the same directory with only the required characters.


问:
JAXRS Asynchronous Services
Here's a sample code from Jersey docs for Asynchronous Services:

```<code>@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}
</code>```

Considering that container is already in charge of releasing the connection handling thread back to the pool and handing the request processing to a worker thread, I'm wondering why we still need to spawn a new thread programmatically? Shouldn't this be just a matter of container configuration (setting number of worker threads)?

答:
Shouldn't this be just a matter of container configuration (setting number of worker threads)?

Actually you can configure the number of container worker threads, but you are still bound by them. If you have 10 container threads then you can process 10 requests at the same time. If you have 100 threads, then you can have 100 simultaneous requests

Async web requests on the other hand decouple the request/response objects (and jax-rs uses servlets underneath in case of servlet-container deployment) from the worker thread. Thus you can have 10 threads, but 1000 requests for instance (keep reading).

I'm wondering why we still need to spawn a new thread programmatically?

It's meaningless to decouple the request from the thread if you are still going to process it in the same thread, because in that case there is absolutely no difference between async/sync requests.

Also you don need to spawn a new thread. Actually that's a horrible solution. Thread creation is expensive. Instead you should submit the runnables to a thread pool.

So what good are async requests then ? They are good for operations that take a lot of time to complete. Do the following experiment.

Configure tomcat (or your server of choice) to use a pool of 10 threads.

Make your resource to just sleep for 10 seconds.

Request it as many times as you can.

Make your resource asynchronous and instead of waiting in it, submit the runnables which just wait for 10seconds to a thread pool -> how many requests can you make now ?

Title: JAXRS Asynchronous Services

Body:
Here's a sample code from Jersey docs for Asynchronous Services:

@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}

Considering that container is already in charge of releasing the connection handling thread back to the pool and handing the request processing to a worker thread, I'm wondering why we still need to spawn a new thread programmatically? Shouldn't this be just a matter of container configuration (setting number of worker threads)?


问:
Glade treeview liststore data not visible, can't imagine why
I've got 99% 44/100 of everything working. I have a glade file, I use gtkbuilder to render it and voila it comes up. Everything except the data in my treeview liststore.
I notice by default the tree view is not visible, and setting that to true makes a box appear in the tree view area, but I can't get any of my liststore items to display in the treeview.
I have some default data in the list store defined in glade, and I programmatically add some too, but nothing ever displays. Is there some visible on/off option I'm missing?</p>

答: To add a cell renderer to your tree view in Glade, right click on the tree view and select "Edit". This brings up the tree view editor. If you click on the "Hierarchy" tab then you can add or remove columns. Add a column and then right click on it for a menu of cell renderers that you can add. This should do the trick.</p>

ContentLicense: CC BY-SA 2.5


答:
Assuming then liteNr and seqNr do not repeat themselfs, something like this should work:</p>

```<code>SELECT
     p1.onr,
     p1.prSh,
     p1.liteNr,
     p1.seqNr,
     p1.planQty
FROM
    pf_pqs p1
    INNER JOIN (
        SELECT
            liteNr,
            MAX(seqNr) AS seqNr
        FROM
            pf_pqs
        GROUP BY
            liteNr
    ) p2 ON
    p2.liteNr = p1.liteNr
    AND p2.seqNr = p1.seqNr
</code>```

Title: MySQL select distinct and max with all columns

Body:
I have a db table: pf_pqs:

+----------+------+--------+-------+---------+
|    onr   | prSh | liteNr | seqNr | planQty |
+----------+------+--------+-------+---------+
| 10347006 | HEG  |    1   |    0  |   5     |
| 10347006 | TEH  |    1   |    1  |   5     |
| 10347006 | KAR  |    1   |    2  |   5     |
| 10347006 | LEN  |    1   |    3  |   5     |
| 10347006 | HEG  |    2   |    0  |   5     |
| 10347006 | LEN  |    2   |    1  |   5     |
| 10347006 | HEG  |    3   |    0  |   5     |
| 10347006 | TEH  |    3   |    1  |   5     |
| 10347006 | KAR  |    3   |    2  |   5     |
| 10347006 | LEN  |    3   |    3  |   5     |

Result must include biggest seqNr in every liteNr and all other corresponding fields correctly; like this:

+----------+------+--------+-------+---------+
|    onr   | prSh | liteNr | seqNr | planQty |
+----------+------+--------+-------+---------+
| 10347006 | LEN  |    1   |    3  |   5     |
| 10347006 | LEN  |    2   |    1  |   5     |
| 10347006 | LEN  |    3   |    3  |   5     |

I tried different queries with joins and grouping but no luck so far :(.
Thanks in advance.

Body:
Assuming then liteNr and seqNr do not repeat themselfs, something like this should work:

SELECT
     p1.onr,
     p1.prSh,
     p1.liteNr,
     p1.seqNr,
     p1.planQty
FROM
    pf_pqs p1
    INNER JOIN (
        SELECT
            liteNr,
            MAX(seqNr) AS seqNr
        FROM
            pf_pqs
        GROUP BY
            liteNr
    ) p2 ON
    p2.liteNr = p1.liteNr
    AND p2.seqNr = p1.seqNr


问:
I am stuck at practice python exercise 4
```<code>number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
    if number % div == 0:
        list.append(div)
        div =+ 1

    print list
</code>```

this is my code which I made for this exercise :
 http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
 I am new to programming so i dont know what is wrong with my code but its not giving any output.

答:
Here is the code you need:

```<code>number = int(input("Enter a number :"))
list = []
# theoretically this is the limit you should test for divisors
for div in range(2, int(number/2 + 1)):
    if number % div == 0:
        # adds the divisor to the list
        list.append(div)
        div += 1

# prints all divisors in new line
for item in list:
    print(item)
</code>```

If you are using python 2.7, instead of input use raw_input

Body:
number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
    if number % div == 0:
        list.append(div)
        div =+ 1

    print list

this is my code which I made for this exercise :
 http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
 I am new to programming so i dont know what is wrong with my code but its not giving any output.

Body:
Here is the code you need:

number = int(input("Enter a number :"))
list = []
# theoretically this is the limit you should test for divisors
for div in range(2, int(number/2 + 1)):
    if number % div == 0:
        # adds the divisor to the list
        list.append(div)
        div += 1

# prints all divisors in new line
for item in list:
    print(item)

If you are using python 2.7, instead of input use raw_input


问:
Exposing a window object's document
I have a iframe whose content will be exposed by iframeObject.contentWindow. This returns a window object, according to mozilla developer network

this window object to access the iframe's document and it's internal
  dom.

However, I cannot figure out how to expose the document from the window object.

答:
You can access the contentDocument property

HTMLIFrameElement.contentDocument

Returns a Document, the active document in the inline frame's nested
    browsing context.

Title: Exposing a window object's document


问:
Hide (and show) links when div is dynamically resized
I am trying to resize a div when a user decides to hide (or show) particular content. For example, I have a contents page (https://jsfiddle.net/4b1g5jp9/1/), when a user clicks hide, I want the div to resize accordingly, hiding all contents except the actual Contents title.

Also, the 'Show' link should only show if the content is actually hidden and vice versa.

I have tried to adapt some JS based on a similar issue I found online and tried the following approach:

```<code><script language="javascript">
            function toggle() {
                var ele = document.getElementById("contents-list");
                if (ele.style.display == "block") {
                    ele.style.display = "none";
                } else {
                    ele.style.display = "block";
                }
            }
        </script>
</code>```

But the above achieves nothing. Any advice/solution would be appreciated.

答:
Use that structure as your HTML:

```<code><div id="contents-list">
    <ul>
        <li id="centerContents"><b> Contents </b>
            <a class="hideLinks" href="#">[Hide]</a>
            <a class="showLinks" href="#">[Show]</a>
        </li>
    </ul>
    <ul class="submenu">
        <li> <a href="#jumpQ1"> 1.  What is Mobility? </a> </li>
        <li> <a href="#jumpQ2"> 2.  Why Mobility is important </a> </li>
        <li> <a href="#jumpQ3"> 3.  Other </a> </li>
    </ul>
</div>
</code>```

Using jQuery:

```<code><script type="text/javascript">
    $("#contents-list ul li a.hideLinks").click(function(){
        $("ul.submenu").css("display", "none");
    });

    $("#contents-list ul li a.showLinks").click(function(){
        $("ul.submenu").css("display", "block");
    });
</script>
</code>```

Your jQuery script should be right after the HTML, or near the  tag. And make sure to call jQuery cdn inside head tag: .

NOTE: You can use Show() and Hide() functions instead of css display properties. You can read more about those functions Here.

Body:
I am trying to resize a div when a user decides to hide (or show) particular content. For example, I have a contents page (https://jsfiddle.net/4b1g5jp9/1/), when a user clicks hide, I want the div to resize accordingly, hiding all contents except the actual Contents title.

Also, the 'Show' link should only show if the content is actually hidden and vice versa.

I have tried to adapt some JS based on a similar issue I found online and tried the following approach:

But the above achieves nothing. Any advice/solution would be appreciated.

Body:
Use that structure as your HTML:

<div id="contents-list">
    <ul>
        <li id="centerContents"><b> Contents </b>
            <a class="hideLinks" href="#">[Hide]</a>
            <a class="showLinks" href="#">[Show]</a>
        </li>
    </ul>
    <ul class="submenu">
        <li> <a href="#jumpQ1"> 1.  What is Mobility? </a> </li>
        <li> <a href="#jumpQ2"> 2.  Why Mobility is important </a> </li>
        <li> <a href="#jumpQ3"> 3.  Other </a> </li>
    </ul>
</div>

Using jQuery:

<script type="text/javascript">
    $("#contents-list ul li a.hideLinks").click(function(){
        $("ul.submenu").css("display", "none");
    });

    $("#contents-list ul li a.showLinks").click(function(){
        $("ul.submenu").css("display", "block");
    });
</script>

Your jQuery script should be right after the HTML, or near the </body> tag. And make sure to call jQuery cdn inside head tag: <script src="jquery-3.0.0.min.js" type="text/javascript"></script>.

NOTE: You can use Show() and Hide() functions instead of css display properties. You can read more about those functions Here.


问:
How to specify and keep only a proportion of the Fourier Transforms of largest magnitude from an image
I want to write a short MATLAB program that enables me to specify and keep only a proportion of the Fourier Transforms of largest magnitude from an image representation.

Here is my code so far, where 'image123' is a 256x256 uint8:

```<code>I= image123;
F = fft2(I);
F = fftshift(F);
F = abs(F); % Get the magnitude
F = log(F + 1);
F = mat2gray(F);
figure, imshow(F,[])
</code>```

If I increase my value of 1 in 'F = log(F + 1)' will this increase the magnitude of the Fourier transform?

答:
You'll want to use a binary mask to set all values below a given threshold to zero and then use ifft2 to create an image from this modified Fourier data

```<code>% Load in some sample data
tmp = load('mri');
I = tmp.D(:,:,12);

% Take the 2D Fourier Transform
F = fft2(I);

% Set this to whatever you want
threshold = 2000;

% Force all values less than this cutoff to be zero
F(abs(F) < threshold) = 0;

% Take the inverse Fourier transform to get your image back
I2 = ifft2(F);

% Plot them
figure;
subplot(1,2,1);
imshow(I, []);
title('Original')

subplot(1,2,2);
imshow(I2, []);
title('Filtered')
</code>```

Body:
I want to write a short MATLAB program that enables me to specify and keep only a proportion of the Fourier Transforms of largest magnitude from an image representation.

Here is my code so far, where 'image123' is a 256x256 uint8:

I= image123;
F = fft2(I);
F = fftshift(F);
F = abs(F); % Get the magnitude
F = log(F + 1);
F = mat2gray(F);
figure, imshow(F,[])

If I increase my value of 1 in 'F = log(F + 1)' will this increase the magnitude of the Fourier transform?

Body:
You'll want to use a binary mask to set all values below a given threshold to zero and then use ifft2 to create an image from this modified Fourier data

% Load in some sample data
tmp = load('mri');
I = tmp.D(:,:,12);

% Take the 2D Fourier Transform
F = fft2(I);

% Set this to whatever you want
threshold = 2000;

% Force all values less than this cutoff to be zero
F(abs(F) < threshold) = 0;

% Take the inverse Fourier transform to get your image back
I2 = ifft2(F);

% Plot them
figure;
subplot(1,2,1);
imshow(I, []);
title('Original')

subplot(1,2,2);
imshow(I2, []);
title('Filtered')


问:
List sorting - two lists into one
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

```<code>names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])
</code>```

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

答:
Right, no zips and sets. We'll do this the hard way.

First, make a copy of wages:

```<code>>>> wages_c = wages[:]
</code>```

Sort the copy:

```<code>>>> wages_c.sort()
</code>```

And now, iterate over the copy and find the corresponding original name:

```<code>>>> for wage in wages_c:
...     key = wages.index(wage)
...     print(wages[key], names[key])
</code>```

This is stupid and will not work if you have either duplicate names or duplicate wages, but it doesn't use zip or sets.

Original solution:

We start with your lists:

```<code>>>> names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
>>> wages = [15000,1500,200,14500,2600]
</code>```

Merge them:

```<code>>>> names_and_wages = list(zip(names, wages))
</code>```

Sort by the second element:

```<code>>>> names_and_wages.sort(key=lambda x: x[1])
</code>```

And print:

```<code>>>> for name, wage in names_and_wages:
...     print(name, wage)
</code>```

Title: List sorting - two lists into one

Body:
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

Body:
Right, no zips and sets. We'll do this the hard way.

First, make a copy of wages:

>>> wages_c = wages[:]

Sort the copy:

>>> wages_c.sort()

And now, iterate over the copy and find the corresponding original name:

>>> for wage in wages_c:
...     key = wages.index(wage)
...     print(wages[key], names[key])

This is stupid and will not work if you have either duplicate names or duplicate wages, but it doesn't use zip or sets.

Original solution:

We start with your lists:

>>> names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
>>> wages = [15000,1500,200,14500,2600]

Merge them:

>>> names_and_wages = list(zip(names, wages))

Sort by the second element:

>>> names_and_wages.sort(key=lambda x: x[1])

And print:

>>> for name, wage in names_and_wages:
...     print(name, wage)


问:
Issues with Head First Android Example
I'm trying to work through the Head First Android Development book and I'm running into a bit of a roadblock. I'm assuming the main cause of this is that the text is outdated, but my example keeps failing at runtime and I can't seem to find the reason. Here is the relevant files:

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hfad.workout.MainActivity">

<fragment
    class="com.hfad.workout.WorkoutListFragment"
    android:id="@+id/list_frag"
    android:layout_width="0dp"
    android:layout_weight="2"
    android:layout_height="match_parent"></fragment>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="0dp"
    android:layout_weight="3"
    android:layout_height="match_parent"></FrameLayout>

</LinearLayout>
</code>```

MainActivity.java:

```<code>package com.hfad.workout;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements
WorkoutListFragment.WorkoutListListener {

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

@Override
public void itemClicked(long id) {
    WorkoutDetailFragment details = new WorkoutDetailFragment();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    details.setWorkout(id);
    ft.replace(R.id.fragment_container, details);
    ft.addToBackStack(null);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();
}

}
</code>```

I can add the other files if they happen to be relevant. I already had issues with the "getFragmentManager" code but a quick search told me the updated code required to be used is "getSupportFragmentManager" so I changed that. It is also saying that the override for itemClicked is never used, but because there is a fragment list included (the id is "list_frag") this method should be built in, correct? I've been following the book exactly but the instances of outdated code keeps setting me back from learning.

Edit:

```<code>package layout;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.hfad.workout.Workout;

public class WorkoutListFragment extends ListFragment {

public WorkoutListFragment() {
    // Required empty public constructor
}

static interface WorkoutListListener {
    void itemClicked(long id);
};

private WorkoutListListener listener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    String[] names = new String[Workout.workouts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = Workout.workouts[i].getName();
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>  (inflater.getContext(), android.R.layout.simple_list_item_1, names);
    setListAdapter(adapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.listener = (WorkoutListListener)activity;
}

@Override
public void onListItemClick (ListView l, View v, int position, long id) {
    if (listener != null) {
        listener.itemClicked(id);
    }
}

}
</code>```

Error:

Gradle tasks [:app:assembleDebug]

C:\Users\reega\AndroidStudioProjects\Workout\app\src\main\java\com\hfad\workout\MainActivity.java

Error:(15, 5) error: method does not override or implement a method from a supertype

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

Information:BUILD FAILED
Information:Total time: 8.256 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console

答:
ListFragment has no onAttach method. The error says that you are trying to override the method of a superclass but there's no method to override.

https://developer.android.com/reference/android/app/ListFragment.html

Title: Issues with Head First Android Example

Body:
I'm trying to work through the Head First Android Development book and I'm running into a bit of a roadblock. I'm assuming the main cause of this is that the text is outdated, but my example keeps failing at runtime and I can't seem to find the reason. Here is the relevant files:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hfad.workout.MainActivity">

<fragment
    class="com.hfad.workout.WorkoutListFragment"
    android:id="@+id/list_frag"
    android:layout_width="0dp"
    android:layout_weight="2"
    android:layout_height="match_parent"></fragment>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="0dp"
    android:layout_weight="3"
    android:layout_height="match_parent"></FrameLayout>

</LinearLayout>

MainActivity.java:

package com.hfad.workout;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements
WorkoutListFragment.WorkoutListListener {

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

@Override
public void itemClicked(long id) {
    WorkoutDetailFragment details = new WorkoutDetailFragment();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    details.setWorkout(id);
    ft.replace(R.id.fragment_container, details);
    ft.addToBackStack(null);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();
}

}

I can add the other files if they happen to be relevant. I already had issues with the "getFragmentManager" code but a quick search told me the updated code required to be used is "getSupportFragmentManager" so I changed that. It is also saying that the override for itemClicked is never used, but because there is a fragment list included (the id is "list_frag") this method should be built in, correct? I've been following the book exactly but the instances of outdated code keeps setting me back from learning.

Edit:

package layout;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.hfad.workout.Workout;

public class WorkoutListFragment extends ListFragment {

public WorkoutListFragment() {
    // Required empty public constructor
}

static interface WorkoutListListener {
    void itemClicked(long id);
};

private WorkoutListListener listener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    String[] names = new String[Workout.workouts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = Workout.workouts[i].getName();
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>  (inflater.getContext(), android.R.layout.simple_list_item_1, names);
    setListAdapter(adapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.listener = (WorkoutListListener)activity;
}

@Override
public void onListItemClick (ListView l, View v, int position, long id) {
    if (listener != null) {
        listener.itemClicked(id);
    }
}

}

Error:

Gradle tasks [:app:assembleDebug]

C:\Users\reega\AndroidStudioProjects\Workout\app\src\main\java\com\hfad\workout\MainActivity.java

Error:(15, 5) error: method does not override or implement a method from a supertype

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

Information:BUILD FAILED
Information:Total time: 8.256 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console


问:
Issue with MultipleUIPickerView in single UIViewcontroller
    in IOS Application I want to develope UIPickerview like this.code is below.

```<code>#import "CalcViewController.h"

@interface CalcViewController ()

@end

@implementation EZCalcViewController

+(CalcViewController *)viewcontroller{
    CalcViewController *rz=[[CalcViewController alloc]initWithNibName:@"CalcViewController" bundle:nil];
    return  rz;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    picker1 = [[UIPickerView alloc] init];
    [self.view addSubview:picker1];
    picker2 = [[UIPickerView alloc] init];
    [self.view addSubview:picker2];
    picker3 = [[UIPickerView alloc] init];
    [self.view addSubview:picker3];
    picker1.delegate=self;
    picker1.delegate=self;
    _customPickerArrayshap = [[NSMutableArray alloc] init];
    _customPickerArraycolor = [[NSMutableArray alloc] init];
    _customPickerArrayclarity = [[NSMutableArray alloc] init];

   /// [_customPickerArrayshap.count = 0];
    [self dropdownshape];
    [self dropdowncolor];
    [self dropdownclarity];

}
-(void)dropdownshape
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value1 xmlns=\"http://tempuri.org/\">\n"
                        “</value1>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@“ABC.asmx";

    NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request2 addValue:@"http://tempuri.org/Value1" forHTTPHeaderField:@"SOAPAction"];
    [request2 setHTTPMethod:@"POST"];
    [request2 setHTTPBody:envelope];
    [request2 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request2 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
    if (connection){
        resshap = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
-(void)dropdowncolor
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value2 xmlns=\"http://tempuri.org/\">\n"
                        “</value2>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value2" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
        rescolor = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}

-(void)dropdownclarity
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value3 xmlns=\"http://tempuri.org/\">\n"
                        “</value3>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
  NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value3" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
       resclarity = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    [resshap setLength:0];
    [rescolor setLength:0];
     [resclarity setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

   [resshap appendData:data];
    [rescolor appendData:data];
    [resclarity appendData:data];

}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"connection didFailWithError: %@ %@", error.localizedDescription,
          [error.userInfo objectForKey:NSURLErrorFailingURLStringErrorKey]);
    NSString *err=error.localizedDescription;
    UIAlertView *alr=[[UIAlertView alloc]initWithTitle:@"App" message:err delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // [[ActivityIndicator currentIndicator]displayCompleted];
    NSLog(@"DONE. Received Bytes:%d",[resshap length]);
     NSLog(@"DONE. Received Bytes:%d",[rescolor length]);
     NSLog(@"DONE. Received Bytes:%d",[resclarity length]);

    NSString *theXml1 = [[NSString alloc] initWithBytes:[resshap mutableBytes] length:[resshap length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 1--- :%@",theXml1);

    NSString *string1=[NSString stringWithFormat:@"r%@d",theXml1];
    NSLog(@"Object having value 1%@",string1);

      NSString *thexml2 = [[NSString alloc] initWithBytes:[rescolor mutableBytes] length:[rescolor length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 2--- :%@",theXml1);

    NSString *string2=[NSString stringWithFormat:@"r%@d",thexml2];
    NSLog(@"Object having value  2%@",string2);

      NSString *thexml3 = [[NSString alloc] initWithBytes:[resclarity mutableBytes] length:[resclarity length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 3--- :%@",theXml1);

    NSString *string3=[NSString stringWithFormat:@"r%@d",thexml3];
    NSLog(@"Object having value 3%@",string3);

    if(xmlParser1)
    {

    }
    xmlParser1 = [[NSXMLParser alloc] initWithData: resshap];
    [xmlParser1 setDelegate:self];
    [xmlParser1 setShouldResolveExternalEntities:YES];
    [xmlParser1 parse];
    //[theXml release];

    if(xmlParser2)
    {

    }
    xmlParser2 = [[NSXMLParser alloc] initWithData: rescolor];
    [xmlParser2 setDelegate:self];
    [xmlParser2 setShouldResolveExternalEntities:YES];
    [xmlParser2 parse];
    //[theXml release];

    if(xmlParser3)
    {

    }
    xmlParser3 = [[NSXMLParser alloc] initWithData: resclarity];
    [xmlParser3 setDelegate:self];
    [xmlParser3 setShouldResolveExternalEntities:YES];
    [xmlParser3 parse];
    //[theXml release];

}

//}
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *)attributeDict {
    if( [elementName isEqualToString:@“Value1Result"])
    {
        if (!soapResults1)
        {
            soapResults1 = [[NSMutableString alloc] init];
        }
        elementFound1 = YES;
    }
    else if([elementName isEqualToString:@“Value2Result"]){
        if (!soapResults2)
        {
            soapResults2 = [[NSMutableString alloc] init];
        }
        elementFound2 = YES;
    }else if( [elementName isEqualToString:@“value3Result"])
    {
        if (!soapResults3)
        {
            soapResults3 = [[NSMutableString alloc] init];
        }
        elementFound3 = YES;
    }

}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if (elementFound1)
    {
        [soapResults1 appendString: string];

        NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSLog(@"print array :%@",jsonarr1);
        for (NSDictionary * d in jsonarr1)
        {
            if ([d objectForKey:@"SHP"]!=[NSNull null])
            {
                [picker1 reloadAllComponents];
                self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V1”]];
                 NSLog(@"pVALUE FOR CLR :%@",self.shapestring);
                [_customPickerArrayshap addObject:self.shapestring];
               NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArrayshap.count);
                [picker1 reloadAllComponents];
            }
            else
            {self.shapestring=@"";
                            }
        }
    }
        if(elementFound2){
            [soapResults2 appendString: string];

            NSArray * jsonarr2 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr2);
            for (NSDictionary * d in jsonarr2)
            {

            if ([d objectForKey:@"RAPCOL"]!=[NSNull null])
            {
                [picker2 reloadAllComponents];
                self.colorstring=[NSString stringWithFormat:@"%@",[d objectForKey:@“v2”]];
                NSLog(@"pVALUE FOR CLR :%@",self.colorstring);
                [_customPickerArraycolor addObject:self.colorstring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                self.colorstring=@"";

            }

        }
        }
        if(elementFound3){
            [soapResults3 appendString: string];

            NSArray * jsonarr3 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr3);

            for (NSDictionary * d in jsonarr3)
            {

            if ([d objectForKey:@"CLR"]!=[NSNull null])
            {
                [picker3 reloadAllComponents];
                self.claritystring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V3”]];
                NSLog(@"pVALUE FOR CLR :%@",self.claritystring);
                [_customPickerArrayclarity addObject:self.claritystring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                 self.claritystring=@"";
            }

        }
        }
    }

-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@“value1Result"])
    {

        [self.customPickerArrayshap addObject:@“v1”];

        NSLog(@"%@",soapResults1);

        [soapResults1 setString:@""];
        elementFound1 = FALSE;

    }
   else if ([elementName isEqualToString:@“Value2Result"])
    {

        [self.customPickerArraycolor addObject:@“v2”];
             [soapResults2 setString:@""];
        elementFound2 = FALSE;

    }else if ([elementName isEqualToString:@“Value3Result"]){
        [self.customPickerArrayclarity addObject:@“V3”];
             [soapResults3 setString:@""];
        elementFound3 = FALSE;
    }

}
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

    if([pickerView tag]==1)
    {
        return _customPickerArrayshap.count;
    }
    else if([pickerView tag]==2)
    {

        return _customPickerArraycolor.count;
    }else if([pickerView tag]==3){

        return _customPickerArrayclarity.count;
    }

}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if([pickerView tag]==1)
    {

        return _customPickerArrayshap[row];
    }
    else if([pickerView tag]==2)
    {
        return _customPickerArraycolor[row];
    }else if([pickerView tag]==3){
        return _customPickerArrayclarity[row];
    }

}
</code>```

using above code i want to Develope like thissee referance image,I have 3 PickerView and data is set from soap WebService,for data assign i have add Indivisual soap response in  in differant array,and based on PickerView's tag value data is assign,but problem is that only first soap response  is assign in pickerview remaining 2 are null,please suggest me if i'm go wrong.

答:
You are calling 3 web services at a time

```<code>[self dropdownshape];

[self dropdowncolor];

[self dropdownclarity];
</code>```

Instead of that you will call first service in viewDidLoad

(void)viewDidLoad {

[super viewDidLoad];

[self dropdownshape];

}

after that First connection is Established in that you can call second web service

if (connection){

resshap = [NSMutableData data];

[self dropdowncolor];

}

Then Second connection is Established in that you can call third web service

if (connection){

```<code>rescolor = [NSMutableData data];

[self dropdownclarity];

}
</code>```

Check below link it will helpful to you

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response
{

```<code>if(connection == connection1) {

    //Do something with connection 1

}

else if(connection == connection2) {

    //Do something with connection 2

}
</code>```

else if(connection == connection3) {

```<code>    //Do something with connection 3

}
</code>```

}

https://stackoverflow.com/a/6434433/5184217

NOTE: Not Tested

Body:
    in IOS Application I want to develope UIPickerview like this.code is below.

#import "CalcViewController.h"

@interface CalcViewController ()

@end

@implementation EZCalcViewController

+(CalcViewController *)viewcontroller{
    CalcViewController *rz=[[CalcViewController alloc]initWithNibName:@"CalcViewController" bundle:nil];
    return  rz;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    picker1 = [[UIPickerView alloc] init];
    [self.view addSubview:picker1];
    picker2 = [[UIPickerView alloc] init];
    [self.view addSubview:picker2];
    picker3 = [[UIPickerView alloc] init];
    [self.view addSubview:picker3];
    picker1.delegate=self;
    picker1.delegate=self;
    _customPickerArrayshap = [[NSMutableArray alloc] init];
    _customPickerArraycolor = [[NSMutableArray alloc] init];
    _customPickerArrayclarity = [[NSMutableArray alloc] init];

   /// [_customPickerArrayshap.count = 0];
    [self dropdownshape];
    [self dropdowncolor];
    [self dropdownclarity];

}
-(void)dropdownshape
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value1 xmlns=\"http://tempuri.org/\">\n"
                        “</value1>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@“ABC.asmx";

    NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request2 addValue:@"http://tempuri.org/Value1" forHTTPHeaderField:@"SOAPAction"];
    [request2 setHTTPMethod:@"POST"];
    [request2 setHTTPBody:envelope];
    [request2 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request2 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
    if (connection){
        resshap = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
-(void)dropdowncolor
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value2 xmlns=\"http://tempuri.org/\">\n"
                        “</value2>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
    NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value2" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
        rescolor = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}

-(void)dropdownclarity
{

    NSLog(@"dropdown method is call");

    NSString *envalope=[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                        "<soap:Body>\n"
                        "<value3 xmlns=\"http://tempuri.org/\">\n"
                        “</value3>\n"
                        "</soap:Body>\n"
                        "</soap:Envelope>"];

    envalope=[NSString stringWithFormat:envalope];
    NSData *envelope = [envalope dataUsingEncoding:NSUTF8StringEncoding];
  NSString *url=@"http://ABC.asmx";

    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [request1 addValue:@"http://tempuri.org/value3" forHTTPHeaderField:@"SOAPAction"];
    [request1 setHTTPMethod:@"POST"];
    [request1 setHTTPBody:envelope];
    [request1 setValue:@"text/xml; charset=utf-8"
    forHTTPHeaderField:@"Content-Type"];
    [request1 setValue:[NSString stringWithFormat:@"%d", [envelope length]]forHTTPHeaderField:@"Content-Length"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
    if (connection){
       resclarity = [NSMutableData data];
        NSLog(@"connection Establish.");
    }
    else{
        NSLog(@"NSURLConnection initWithRequest: Failed to return a connection.");
    }

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    [resshap setLength:0];
    [rescolor setLength:0];
     [resclarity setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

   [resshap appendData:data];
    [rescolor appendData:data];
    [resclarity appendData:data];

}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"connection didFailWithError: %@ %@", error.localizedDescription,
          [error.userInfo objectForKey:NSURLErrorFailingURLStringErrorKey]);
    NSString *err=error.localizedDescription;
    UIAlertView *alr=[[UIAlertView alloc]initWithTitle:@"App" message:err delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // [[ActivityIndicator currentIndicator]displayCompleted];
    NSLog(@"DONE. Received Bytes:%d",[resshap length]);
     NSLog(@"DONE. Received Bytes:%d",[rescolor length]);
     NSLog(@"DONE. Received Bytes:%d",[resclarity length]);

    NSString *theXml1 = [[NSString alloc] initWithBytes:[resshap mutableBytes] length:[resshap length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 1--- :%@",theXml1);

    NSString *string1=[NSString stringWithFormat:@"r%@d",theXml1];
    NSLog(@"Object having value 1%@",string1);

      NSString *thexml2 = [[NSString alloc] initWithBytes:[rescolor mutableBytes] length:[rescolor length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 2--- :%@",theXml1);

    NSString *string2=[NSString stringWithFormat:@"r%@d",thexml2];
    NSLog(@"Object having value  2%@",string2);

      NSString *thexml3 = [[NSString alloc] initWithBytes:[resclarity mutableBytes] length:[resclarity length] encoding:NSUTF8StringEncoding];
    NSLog(@"The final result 3--- :%@",theXml1);

    NSString *string3=[NSString stringWithFormat:@"r%@d",thexml3];
    NSLog(@"Object having value 3%@",string3);

    if(xmlParser1)
    {

    }
    xmlParser1 = [[NSXMLParser alloc] initWithData: resshap];
    [xmlParser1 setDelegate:self];
    [xmlParser1 setShouldResolveExternalEntities:YES];
    [xmlParser1 parse];
    //[theXml release];

    if(xmlParser2)
    {

    }
    xmlParser2 = [[NSXMLParser alloc] initWithData: rescolor];
    [xmlParser2 setDelegate:self];
    [xmlParser2 setShouldResolveExternalEntities:YES];
    [xmlParser2 parse];
    //[theXml release];

    if(xmlParser3)
    {

    }
    xmlParser3 = [[NSXMLParser alloc] initWithData: resclarity];
    [xmlParser3 setDelegate:self];
    [xmlParser3 setShouldResolveExternalEntities:YES];
    [xmlParser3 parse];
    //[theXml release];

}

//}
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *)attributeDict {
    if( [elementName isEqualToString:@“Value1Result"])
    {
        if (!soapResults1)
        {
            soapResults1 = [[NSMutableString alloc] init];
        }
        elementFound1 = YES;
    }
    else if([elementName isEqualToString:@“Value2Result"]){
        if (!soapResults2)
        {
            soapResults2 = [[NSMutableString alloc] init];
        }
        elementFound2 = YES;
    }else if( [elementName isEqualToString:@“value3Result"])
    {
        if (!soapResults3)
        {
            soapResults3 = [[NSMutableString alloc] init];
        }
        elementFound3 = YES;
    }

}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if (elementFound1)
    {
        [soapResults1 appendString: string];

        NSArray * jsonarr1 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        NSLog(@"print array :%@",jsonarr1);
        for (NSDictionary * d in jsonarr1)
        {
            if ([d objectForKey:@"SHP"]!=[NSNull null])
            {
                [picker1 reloadAllComponents];
                self.shapestring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V1”]];
                 NSLog(@"pVALUE FOR CLR :%@",self.shapestring);
                [_customPickerArrayshap addObject:self.shapestring];
               NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArrayshap.count);
                [picker1 reloadAllComponents];
            }
            else
            {self.shapestring=@"";
                            }
        }
    }
        if(elementFound2){
            [soapResults2 appendString: string];

            NSArray * jsonarr2 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr2);
            for (NSDictionary * d in jsonarr2)
            {

            if ([d objectForKey:@"RAPCOL"]!=[NSNull null])
            {
                [picker2 reloadAllComponents];
                self.colorstring=[NSString stringWithFormat:@"%@",[d objectForKey:@“v2”]];
                NSLog(@"pVALUE FOR CLR :%@",self.colorstring);
                [_customPickerArraycolor addObject:self.colorstring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                self.colorstring=@"";

            }

        }
        }
        if(elementFound3){
            [soapResults3 appendString: string];

            NSArray * jsonarr3 =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            NSLog(@"print array :%@",jsonarr3);

            for (NSDictionary * d in jsonarr3)
            {

            if ([d objectForKey:@"CLR"]!=[NSNull null])
            {
                [picker3 reloadAllComponents];
                self.claritystring=[NSString stringWithFormat:@"%@",[d objectForKey:@“V3”]];
                NSLog(@"pVALUE FOR CLR :%@",self.claritystring);
                [_customPickerArrayclarity addObject:self.claritystring];
                // NSLog(@"pVALUE AFTER ARRAY FILL:%d",_customPickerArray1.);
                [picker3 reloadAllComponents];
            }
            else
            {
                 self.claritystring=@"";
            }

        }
        }
    }

-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@“value1Result"])
    {

        [self.customPickerArrayshap addObject:@“v1”];

        NSLog(@"%@",soapResults1);

        [soapResults1 setString:@""];
        elementFound1 = FALSE;

    }
   else if ([elementName isEqualToString:@“Value2Result"])
    {

        [self.customPickerArraycolor addObject:@“v2”];
             [soapResults2 setString:@""];
        elementFound2 = FALSE;

    }else if ([elementName isEqualToString:@“Value3Result"]){
        [self.customPickerArrayclarity addObject:@“V3”];
             [soapResults3 setString:@""];
        elementFound3 = FALSE;
    }

}
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{

    if([pickerView tag]==1)
    {
        return _customPickerArrayshap.count;
    }
    else if([pickerView tag]==2)
    {

        return _customPickerArraycolor.count;
    }else if([pickerView tag]==3){

        return _customPickerArrayclarity.count;
    }

}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if([pickerView tag]==1)
    {

        return _customPickerArrayshap[row];
    }
    else if([pickerView tag]==2)
    {
        return _customPickerArraycolor[row];
    }else if([pickerView tag]==3){
        return _customPickerArrayclarity[row];
    }

}

using above code i want to Develope like thissee referance image,I have 3 PickerView and data is set from soap WebService,for data assign i have add Indivisual soap response in  in differant array,and based on PickerView's tag value data is assign,but problem is that only first soap response  is assign in pickerview remaining 2 are null,please suggest me if i'm go wrong.

Body:
You are calling 3 web services at a time

[self dropdownshape];

[self dropdowncolor];

[self dropdownclarity];

Instead of that you will call first service in viewDidLoad

(void)viewDidLoad {

[super viewDidLoad];

[self dropdownshape];

}

after that First connection is Established in that you can call second web service

if (connection){

resshap = [NSMutableData data];

[self dropdowncolor];

}

Then Second connection is Established in that you can call third web service

if (connection){

rescolor = [NSMutableData data];

[self dropdownclarity];

}

Check below link it will helpful to you

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response
{

if(connection == connection1) {

    //Do something with connection 1

}

else if(connection == connection2) {

    //Do something with connection 2

}

else if(connection == connection3) {

    //Do something with connection 3

}

}

https://stackoverflow.com/a/6434433/5184217

NOTE: Not Tested


问:
Ionic 2 control font size from UI
I am in between a mobile App development and there is a requirement where an end user can click +/- sign to increase or decrease the font size.

I have done it for many time for web using JQuery/JavaScript but not sure how can I manage it here.

My post.html

```<code> <ion-header>
    <ion-navbar>
        <button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-buttons>
          <button (click)="fontSizeChange()" class="details_btn  blicon-text-file-font" ion-button icon-only>
          </button>
        </ion-buttons>
    </ion-navbar>
</ion-header>
<ion-content class="post" *ngIf="post">
    <div class="detail">
        <div class="detail_image">
            <h1>{{post.title.rendered}}</h1>
        </div>
        <div class="page_info">
          <span class="date"><span class="blicon-clock"></span> {{post.date | date: 'mediumDate'}} </span>
          <span class="tag"> News</span>
        </div>
        <ion-item *ngIf="authorData && authorData.avatar_urls">
            <ion-avatar item-left>
                <img [src]="authorData.avatar_urls[96]">
            </ion-avatar>
            <h2>{{authorData.name}}</h2>
        </ion-item>
        <div id="fontControl">
            <p padding [innerHtml]="post.content.rendered"></p>
        </div>
    </div>
<!-- detail -->

</ion-content>
</code>```

and my page.component.ts is:-

```<code>import { Component, ViewChild } from '@angular/core';
import { Content, NavParams, LoadingController, ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

@Component({
    selector: 'post-detail',
    templateUrl: './wordpress-post.html'
})
export class WordpressPost {
    @ViewChild(Content) content: Content;

    post: any;
    authorData: any;
    comments = [];
    favoritePosts: any;
    user: any;

    constructor(
            private navParams: NavParams,
            private loadingController: LoadingController,
            private toastController: ToastController,
            private storage: Storage
        ) {
        if (navParams.get('post')) {
            this.post = navParams.get('post');
            }
        }

    }

    fontSizeChange(){
         var s = document.getElementById('fontControl').style.fontSize;
         console.log(s);
         var p = s.split('px');
         var z = parseInt(p[0]) + 1;
         document.getElementById('fontControl').style.fontSize = z + "px";
         console.log(document.getElementById('fontControl').style.fontSize);
    }
}
</code>```

Please suggest.

Thanks in advance.

答:
There's a more simple approach by using ngStyle on the parent content.

Your incremental buttons, values are in ems:

```<code><ion-buttons>
    <button (click)="fontSizeChange(-0.2)" ion-button icon-only>
        <ion-icon name="remove"></ion-icon>
    </button>
    <button (click)="fontSizeChange(0.2)" ion-button icon-only>
        <ion-icon name="add"></ion-icon>
    </button>
</ion-buttons>

<ion-content [ngStyle]="{'font-size': fontSize+'em' }">
...
</ion-content>
</code>```

Method:

```<code>fontSize: number = 1.5; // default font size in `em`

fontSizeChange($val: number){
    this.fontSize +=$val;
}
</code>```

See Plunker in action.

Title: Ionic 2 control font size from UI

Body:
I am in between a mobile App development and there is a requirement where an end user can click +/- sign to increase or decrease the font size.

I have done it for many time for web using JQuery/JavaScript but not sure how can I manage it here.

My post.html

 <ion-header>
    <ion-navbar>
        <button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-buttons>
          <button (click)="fontSizeChange()" class="details_btn  blicon-text-file-font" ion-button icon-only>
          </button>
        </ion-buttons>
    </ion-navbar>
</ion-header>
<ion-content class="post" *ngIf="post">

{{post.title.rendered}}

           {{post.date | date: 'mediumDate'}}
           News

        <ion-item *ngIf="authorData && authorData.avatar_urls">
            <ion-avatar item-left>

            </ion-avatar>

{{authorData.name}}

        </ion-item>

</ion-content>

and my page.component.ts is:-

import { Component, ViewChild } from '@angular/core';
import { Content, NavParams, LoadingController, ToastController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

@Component({
    selector: 'post-detail',
    templateUrl: './wordpress-post.html'
})
export class WordpressPost {
    @ViewChild(Content) content: Content;

    post: any;
    authorData: any;
    comments = [];
    favoritePosts: any;
    user: any;

    constructor(
            private navParams: NavParams,
            private loadingController: LoadingController,
            private toastController: ToastController,
            private storage: Storage
        ) {
        if (navParams.get('post')) {
            this.post = navParams.get('post');
            }
        }

    }

    fontSizeChange(){
         var s = document.getElementById('fontControl').style.fontSize;
         console.log(s);
         var p = s.split('px');
         var z = parseInt(p[0]) + 1;
         document.getElementById('fontControl').style.fontSize = z + "px";
         console.log(document.getElementById('fontControl').style.fontSize);
    }
}

Please suggest.

Thanks in advance.

Body:
There's a more simple approach by using ngStyle on the parent content.

Your incremental buttons, values are in ems:

<ion-buttons>
    <button (click)="fontSizeChange(-0.2)" ion-button icon-only>
        <ion-icon name="remove"></ion-icon>
    </button>
    <button (click)="fontSizeChange(0.2)" ion-button icon-only>
        <ion-icon name="add"></ion-icon>
    </button>
</ion-buttons>

<ion-content [ngStyle]="{'font-size': fontSize+'em' }">
...
</ion-content>

Method:

fontSize: number = 1.5; // default font size in `em`

fontSizeChange($val: number){
    this.fontSize +=$val;
}

See Plunker in action.


问:
Git ignore whitelisting all files in a subdirectory, recursively
My software project is modular. Some files are committed by the developer under assigned subdirectories, other are uncompressed to provide an environment runtime (web resources) for development and shall not be committed.

```<code>- webapp
   - common (provided)
   - error (provided)
   - secure
      - admin (provided)
      - audit (provided)
      - ftt (provided)
   - WEB-INF (to ignore)
</code>```

I want to ignore everything under webapp except all files under /webapp/secure/ftt and its subdirectories.

I tried

```<code>/webapp
!/webapp/secure/ftt
</code>```

But Git still ignores ftt.

I expect those directories to contain only .jsp and .js files. But I can't know what happens in the future (e.g. gif, pdf, etc)

How can I tell Git to whitelist files under /webapp/secure/ftt and ignore everything else under /webapp?

From my research I found it may be impossible without listing each specific subdirectory and file pattern.

[Add] after @DevDonkey comment I tried to empty my entire gitignore file and leave what he posted

```<code>/webapp/*
!/webapp/secure/ftt
</code>```

Along with plenties of useless files (e.g. .class files) that are now candidate for indexing, because as I said I emptied the gitignore, I find sample.jsp still ignored

答:
You should follow some inelegant solution like deploying a separate .gitignore file to the /webapp/secure/ftt directory based on the following:

```<code># Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo
</code>```

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

```<code># Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo
</code>```

Body:
My software project is modular. Some files are committed by the developer under assigned subdirectories, other are uncompressed to provide an environment runtime (web resources) for development and shall not be committed.

- webapp
   - common (provided)
   - error (provided)
   - secure
      - admin (provided)
      - audit (provided)
      - ftt (provided)
   - WEB-INF (to ignore)

I want to ignore everything under webapp except all files under /webapp/secure/ftt and its subdirectories.

I tried

/webapp
!/webapp/secure/ftt

But Git still ignores ftt.

I expect those directories to contain only .jsp and .js files. But I can't know what happens in the future (e.g. gif, pdf, etc)

How can I tell Git to whitelist files under /webapp/secure/ftt and ignore everything else under /webapp?

From my research I found it may be impossible without listing each specific subdirectory and file pattern.

[Add] after @DevDonkey comment I tried to empty my entire gitignore file and leave what he posted

/webapp/*
!/webapp/secure/ftt

Along with plenties of useless files (e.g. .class files) that are now candidate for indexing, because as I said I emptied the gitignore, I find sample.jsp still ignored

Body:
You should follow some inelegant solution like deploying a separate .gitignore file to the /webapp/secure/ftt directory based on the following:

# Ignore any file in this directory except for this file and *.foo files
*
!/.gitignore
!*.foo

If you are unwilling or unable to add that .gitignore file, there is an inelegant solution:

# Ignore any file but *.foo under Resources. Update this if we add deeper directories
Resources/*
!Resources/*/
!Resources/*.foo
Resources/*/*
!Resources/*/*/
!Resources/*/*.foo
Resources/*/*/*
!Resources/*/*/*/
!Resources/*/*/*.foo
Resources/*/*/*/*
!Resources/*/*/*/*/
!Resources/*/*/*/*.foo


问:
Using hashing algorithm in CAPL (CANoe)
I want to implement a hashing algorithm like md5 in CAPL (CANoe). Is there any built-in hashing function in CAPL?  </p>

答:
I would suggest to create a CAPL Dll which implements your hash-algorithm in C++ and include it via #pragma library() in your code.
There is an example in "CANoe Sample Configurations\Programming\CAPLdll". For more infos take a look at the chapter "CAPL DLL" in your CANoe help.

Title: Using hashing algorithm in CAPL (CANoe)


问:
is it ok to use jquery inside ember controller or component
I wanted to follow ember js rules thoroughly.but I am novice to ember js so I am struggle to find ember standard way of doing coding.

Is it ok to do some jquery code inside ember component or controller ?

is it not good to use jquery inside there ?I think it not good to use jquery there.

答:
You should try to minimise the usage of the jQuery in your Ember application unless that is a 3-rd party addon/library.

The reason to do so is that if you introduce jQuery to the application. You have to manually manage your application's state (sync all the state between different components for example).

Doing so you lost the biggest advantage of using a Front-end framework like Ember.JS.

My advice is to try to use computed property to change your application's behavior.


问:
Expression of type Iteratee[Array[Byte], StatusHeader] doesn't conform to expected type Accumulater[Byte,Result] in Play scala?
```<code>class AuthorizedFilter extends EssentialFilter  {

  private def authorizationRequired(request: RequestHeader) = {
    val clientId = request.headers.get("clientId");
    val id = "74f6df0452";  //to match with clientID.Block remaining request
    clientId match {
      case Some(id) =>
        true;
      case _ =>
        false;
    }

  }

  def apply(next: EssentialAction):EssentialAction = new EssentialAction {
     def apply(request: RequestHeader)  = {
      println("result...",request.headers.get("clientId"));

      if(!authorizationRequired(request)) {
        *Iteratee.ignore[Array[Byte]].map(_ => Results.forbidden())*
      }
      else {
        println("YOU are authorized!!")
        next(request)
      }
      }
  }
}
</code>```

The above filter was added to block all the requests where clientID is not matched. I got error message in Iteratee.ignore[Array[Byte]].map(_ => Results.forbidden()).

答:
The problem is that you took a piece of code from an older version of play framework and you are now using a version >= 2.5. You need to replace the line Iteratee... with:

```<code>Accumulator.done(Results.forbidden())
</code>```

cf documentation

Body:
class AuthorizedFilter extends EssentialFilter  {

  private def authorizationRequired(request: RequestHeader) = {
    val clientId = request.headers.get("clientId");
    val id = "74f6df0452";  //to match with clientID.Block remaining request
    clientId match {
      case Some(id) =>
        true;
      case _ =>
        false;
    }

  }

  def apply(next: EssentialAction):EssentialAction = new EssentialAction {
     def apply(request: RequestHeader)  = {
      println("result...",request.headers.get("clientId"));

      if(!authorizationRequired(request)) {
        *Iteratee.ignore[Array[Byte]].map(_ => Results.forbidden())*
      }
      else {
        println("YOU are authorized!!")
        next(request)
      }
      }
  }
}

The above filter was added to block all the requests where clientID is not matched. I got error message in Iteratee.ignore[Array[Byte]].map(_ => Results.forbidden()).

Body:
The problem is that you took a piece of code from an older version of play framework and you are now using a version >= 2.5. You need to replace the line Iteratee... with:

Accumulator.done(Results.forbidden())

cf documentation


问:
Get static html / css snapshot of component
In short: How do I get the generated CSS of my component as a string?

-> I want to get a snapshot of my component. That is, what the very view looks looks like. Just what you see when you click right->inspect. Html & css to render the component independently from any Javascript.

Motivation: Use that snapshot for later export as PDF. I could create the PDFs server-wise, but since Angular has a neat templating engine, why not use it for that? Comments welcome.

I managed to get the snapshot html code from my banana-component like this:

// banana component file
@Component( {
    selector: 'banana',
    template: `<div id="report">some text</div>`,
    styles: [ '#report { font-weight:bold; }' ]
})
export class BananaComponent {
    constructor(public elementRef: ElementRef) { }
}

// parent component file
@Component(...)
export class App {
    @ViewChild(BananaComponent) myBanana;
    private getSnapshot() {
         let bananaSnapshotHtml = this.myBanana.elementRef.nativeElement.outerHTML;
         let bananaSnapshotCss = // ?? TODO
    }
}
```

<p>The <code>snapshotHtml</code> variable for example looks like this:</p>

<pre class="lang-html prettyprint-override"><code><banana _ngcontent-c2="" _nghost-c4="" ng-reflect-render="true"><!--bindings={
  "ng-reflect-ng-if": "true"
}--><div _ngcontent-c4="" id="report">
    some text
</div></banana>
</code>```

But I have no idea how to get the respective bananaSnapshotCss. According to Firefox, Angular somehow puts this inline:

#report[_ngcontent-c4] {
  font-weight: bold;
}
```

Is there a way to get this ^ somehow programmatically? I want my bananaSnapshotCss variable above to hold this exactly. Or is my entire approach wrong?

Right now, I am manually copying the contents of my css-files into bananaSnapshotCss and thus, it is part of my TS code. This is ugly and duplicate code and ignores nested child component styles.

See live sample here, including the current workaround (app/app.ts with a TODO)

答: In your @Component selector add a class using host: {'class':'reports'} . Then in your css you can set styles using the reports class. Hope this helps you

Body:
In short: How do I get the generated CSS of my component as a string?

-> I want to get a snapshot of my component. That is, what the very view looks looks like. Just what you see when you click right->inspect. Html & css to render the component independently from any Javascript.

Motivation: Use that snapshot for later export as PDF. I could create the PDFs server-wise, but since Angular has a neat templating engine, why not use it for that? Comments welcome.

I managed to get the snapshot html code from my banana-component like this:

// banana component file
@Component( {
    selector: 'banana',
    template: `<div id="report">some text</div>`,
    styles: [ '#report { font-weight:bold; }' ]
})
export class BananaComponent {
    constructor(public elementRef: ElementRef) { }
}

// parent component file
@Component(...)
export class App {
    @ViewChild(BananaComponent) myBanana;
    private getSnapshot() {
         let bananaSnapshotHtml = this.myBanana.elementRef.nativeElement.outerHTML;
         let bananaSnapshotCss = // ?? TODO
    }
}

The snapshotHtml variable for example looks like this:

<banana _ngcontent-c2="" _nghost-c4="" ng-reflect-render="true">

    some text

</banana>

But I have no idea how to get the respective bananaSnapshotCss. According to Firefox, Angular somehow puts this inline:

#report[_ngcontent-c4] {
  font-weight: bold;
}

Is there a way to get this ^ somehow programmatically? I want my bananaSnapshotCss variable above to hold this exactly. Or is my entire approach wrong?

Right now, I am manually copying the contents of my css-files into bananaSnapshotCss and thus, it is part of my TS code. This is ugly and duplicate code and ignores nested child component styles.

See live sample here, including the current workaround (app/app.ts with a TODO)


问:
Generalization for regular expression on any list
I'm working with a large list containing integers and I would like to do some pattern matching on them (like finding certain sequences). Regular expressions would be the perfect fit, except that they always seem to only handle lists of characters, a.k.a. strings. Is there any library (in any language) that can handle lists of an arbitrary type?

I'm aware that I could convert my integer list into a string and then do a normal regular expression search but that seems a bit wasteful and inelegant.

edit:

My requirements are fairly simple. No need for nested lists, no need for fancy character classes. Basically I'm just interested in occurrences of sequences that can get pretty complicated. (e.g. something like "[abc]{3,}.([ab]?[^a]{4,7})" etc. where a,b,c are integers). This should be possible to generalize over any type which can be checked for equality. For an enumerable type you could also get things like "[a-z]" to work.

答: Well, Erlang has pattern matching (of your type) built right in. I did something similar once in Ruby - a bit of probably not too well performing hackery, see http://radiospiel.org/0x16-its-a-bird </p>


问:
Code Coverage Issue with Spring ResultSetExtractor
Code coverage of Resultsetextractor anonymous class is not covered.
There is no excecption at run time , it is running fine.

We have mocked the jdbcTemplate using below sample code.

Mockito.when(mainTemplate.query(QUERY, new HashMap(),rs)).thenReturn(new Object());

Below Code (start with @Override annotation - extractData() method)  is not covered after execution.

return mainTemplate.query(Query, paramMap, new ResultSetExtractor>() {

```<code>        **@Override
        public Map<String, Object> extractData(ResultSet resultSet)
                throws SQLException, DataAccessException {
            Map<String, Object> keyMap = new HashMap<String, Object>();
            while (resultSet.next()) {
                keyMap.put("key1",
                        resultSet.getString("data1"));
                keyMap.put("key2", resultSet.getString("data2"));
            }
            return keyMap;
        }**
    });
</code>```

Please help.

```<code>Please check sample code for your information.

    **return jdbcTemplatre.query(Query, paramMap, new ResultSetExtractor<byte[]>() {
                @Override
                public byte[] extractData(ResultSet resultSet) throws SQLException,
                        DataAccessException {
                    byte[] data = null;
                    while (resultSet.next()) {
                        signature = resultSet.getBytes("data");
                    }
                    return data;
                }
            });**

    Mockito.when(mainTemplate.query(Query, new HashMap<String,Object>(),rs)).thenAnswer(new Answer<Object>(){
                 @Override
                    public byte[] answer(InvocationOnMock invocationOnMock) throws Throwable {
                        ResultSetExtractor resultSetExtractor = invocationOnMock.getArgumentAt(2,ResultSetExtractor.class);
                        return (byte[]) resultSetExtractor.extractData(resSet);
                    }
            });
</code>```

答:
The ResultSetExtractor code is not covered because it is never executed. And it is not executed because the mainTemplate.query call is mocked thus the ResultSetExtractor callback is never triggered.
You could triggered it while still using the mock by using Mockitos thenAnswer

```<code>Mockito.when(mainTemplate.query(QUERY, new HashMap(),rs)).thenAnswer(new Answer<Object>() {
    @Override
    public String answer(InvocationOnMock invocationOnMock) throws Throwable {
        ResultSetExtractor resultSetExtractor = invocationOnMock.getArgumentAt(2, ResultSetExtractor.class);
        resultSetExtractor.extractData(...);
        return new Object();
    }
});
</code>```

Or with java 8

```<code>Mockito.when(mainTemplate.query(QUERY, new HashMap(),rs)).thenAnswer(invocationOnMock -> {
    ResultSetExtractor resultSetExtractor = invocationOnMock.getArgumentAt(2, ResultSetExtractor.class);
    resultSetExtractor.extractData(...);
    return new Object();
});
</code>```

But testing this way you would have to create a ResultSet yourself.

But generally speaking: this way of calling resultSetExtractor.extractData in the mock might cause problems because it is making assumptions about how the jdbcTemplate.query method handles the ResultSetExtractor internally. But that behaviour might change and then your test does not represent anymore what actually happens in production.

Body:
Code coverage of Resultsetextractor anonymous class is not covered.
There is no excecption at run time , it is running fine.

We have mocked the jdbcTemplate using below sample code.

Mockito.when(mainTemplate.query(QUERY, new HashMap(),rs)).thenReturn(new Object());

Below Code (start with @Override annotation - extractData() method)  is not covered after execution.

return mainTemplate.query(Query, paramMap, new ResultSetExtractor>() {

        **@Override
        public Map<String, Object> extractData(ResultSet resultSet)
                throws SQLException, DataAccessException {
            Map<String, Object> keyMap = new HashMap<String, Object>();
            while (resultSet.next()) {
                keyMap.put("key1",
                        resultSet.getString("data1"));
                keyMap.put("key2", resultSet.getString("data2"));
            }
            return keyMap;
        }**
    });

Please help.

Please check sample code for your information.

    **return jdbcTemplatre.query(Query, paramMap, new ResultSetExtractor<byte[]>() {
                @Override
                public byte[] extractData(ResultSet resultSet) throws SQLException,
                        DataAccessException {
                    byte[] data = null;
                    while (resultSet.next()) {
                        signature = resultSet.getBytes("data");
                    }
                    return data;
                }
            });**

    Mockito.when(mainTemplate.query(Query, new HashMap<String,Object>(),rs)).thenAnswer(new Answer<Object>(){
                 @Override
                    public byte[] answer(InvocationOnMock invocationOnMock) throws Throwable {
                        ResultSetExtractor resultSetExtractor = invocationOnMock.getArgumentAt(2,ResultSetExtractor.class);
                        return (byte[]) resultSetExtractor.extractData(resSet);
                    }
            });

Body:
The ResultSetExtractor code is not covered because it is never executed. And it is not executed because the mainTemplate.query call is mocked thus the ResultSetExtractor callback is never triggered.
You could triggered it while still using the mock by using Mockitos thenAnswer

Mockito.when(mainTemplate.query(QUERY, new HashMap(),rs)).thenAnswer(new Answer<Object>() {
    @Override
    public String answer(InvocationOnMock invocationOnMock) throws Throwable {
        ResultSetExtractor resultSetExtractor = invocationOnMock.getArgumentAt(2, ResultSetExtractor.class);
        resultSetExtractor.extractData(...);
        return new Object();
    }
});

Or with java 8

Mockito.when(mainTemplate.query(QUERY, new HashMap(),rs)).thenAnswer(invocationOnMock -> {
    ResultSetExtractor resultSetExtractor = invocationOnMock.getArgumentAt(2, ResultSetExtractor.class);
    resultSetExtractor.extractData(...);
    return new Object();
});

But testing this way you would have to create a ResultSet yourself.

But generally speaking: this way of calling resultSetExtractor.extractData in the mock might cause problems because it is making assumptions about how the jdbcTemplate.query method handles the ResultSetExtractor internally. But that behaviour might change and then your test does not represent anymore what actually happens in production.


问:
Escape a forward slash on Cypher
I'm returning some data on Cypher and I want to label the column 'a/an', but 'RETURN x.name AS a/an' doesn't work, I'm assuming because I need to escape the forward slash. I've tried escaping it by adding one or two backslashes before it, and by using double and single quotes and brackets, but nothing seems to work.

The Neo4j manual has an example using \/ but this didn't work for me.(http://neo4j.com/docs/developer-manual/current/cypher/clauses/where/#query-where-patterns - see 'Escaping in regular expressions')

Likewise the quote marks suggestions in this stackoverflow answer don't seem to work.
(Neo4j how to handle special characters like ” \ in Cypher statements)

Any tips would be great! I'm pretty new to Cypher and programming in general so forgive me if I'm just doing something stupid!

I'm using neo4j community edition 3.1.2

Thanks!!

答:
Neo4j escape character is backtick.So in your case you would use:

```<code>RETURN x.name AS `a/an`
</code>```

Tried it and it works.

Hope this helps

Title: Escape a forward slash on Cypher

Body:
Neo4j escape character is backtick.So in your case you would use:

RETURN x.name AS `a/an`

Tried it and it works.

Hope this helps


问:
How can we use ES6 Fetch api to return json and other type of files like js?`
I use it for getting data from a REST API using response.json(); but i want to get data even if the response type is not json, it can he HTML, JS, CSS or anything.</p>

答:
This really is basic stuff. Remember to read the docs.</p>

```<code>fetch('endpoint/')
  .then(res => res.text())
  .then(textData => {
    console.log("Got data from endpoint", textData);
  })`
</code>```

Body:
This really is basic stuff. Remember to read the docs.

fetch('endpoint/')
  .then(res => res.text())
  .then(textData => {
    console.log("Got data from endpoint", textData);
  })`


问:
How to make edge sloped on a cylinder?
I'm beginner at 3D modelling and I'm making an office chair. Now I'm stuck at wheel area as I need a sloped edge cylinder for the base of the wheel.

Concept: The wheel is attached to a cylindrical base which is attached to the foot of the chair.

Current Situation: I draw foot of chair, made a circle on it and transformed into a cylinder. The end edge of the cylinder has no Face and I want to extrude the cylinder along one edge which will make a sloped area on the open side of area. That should look like this :

But I tried manythings to do, but failed. It's obvious as I said I'm beginner. Please help me do to this.

Note: I'm using blender 2.78

答:
The shear tool will move your mesh the way you want. It doesn't create the geometry so first extrude E and then shear ⎈ Ctrl⎇ Alt⇧ ShiftS the extruded section. Also note that the shear tool always uses the viewport axis, so switch to front or side view to keep the movement in line with your object.

You could also extrude past the point you want and use the knife or bisect tool to cut the geometry at the angle you want.

Title: How to make edge sloped on a cylinder?