问:
NSURLRequest timeout interval default time
Can you share your answer to me for

NSURLRequest default timeoutInterval time

NSMutableURLRequest default timeoutInterval time

答:
For reference, the default timeout interval is defined within the header file for NSURLRequest, by the side of +requestWithURL:

It explicitly says it's 60 seconds.


来源: stackexchange

问:
Parameterize docker build by passing jar file name from command line
I am trying to parameterize the final jar file name in docker build. I need docker-maven-plugin to take jar file name passed via command line parameter. Maven build is not throwing any error while building image.

If I hard-code the jar file name in dockerfile, it is working fine.

Maven command to docker build:

```<code>mvn -X -s settings.xml docker:build -DJAR_FILE_NAME=${filename}
</code>```

My docker file:

```<code>RUN curl -kfsSL https://example.com/UnlimitedJCEPolicyJDK8/US_export_policy.jar > US_export_policy.jar \
&& curl -kfsSL https://example.com//UnlimitedJCEPolicyJDK8/local_policy.jar > local_policy.jar \
    && mv local_policy.jar ${JAVA_HOME}/jre/lib/security \
    && mv US_export_policy.jar ${JAVA_HOME}/jre/lib/security \
    && rm -rf US_export_policy.jar local_policy.jar

ENV JAVA_KEYSTORE ${JAVA_HOME}/jre/lib/security/cacerts
RUN curl -kfsSL https://example.com/mycert.cer > mycert.cer \
    && ${JAVA_HOME}/bin/keytool -v -importcert -file mycert.cer -keystore ${JAVA_KEYSTORE} -storepass dummy -alias dummy -noprompt \
    && rm mycert.cer

VOLUME /tmp
#ADD myservice-2.0.2-SNAPSHOT.jar app.jar   <-hard-coded name works fine

RUN echo "final jar file name"
RUN echo ${JAR_FILE_NAME}

ADD ${JAR_FILE_NAME} app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
</code>```

My POM.xml

```<code><plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.0</version>
    <configuration>
        <imageName>${docker.image.prefix}/myservice</imageName>
        <dockerDirectory>src/main/docker</dockerDirectory>
        <resources>
            <resource>
                <targetPath>${docker.resource.targetPath}</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>
</code>```

Output from docker build process:

```<code>Step 6 : VOLUME /tmp
 ---> Using cache
 ---> xxxxxxxxx
Step 7 : RUN /bin/bash -c echo JAR_FILE_NAME1 in docker :$JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 8 : RUN /bin/bash -c echo JAR_FILE_NAME2 in docker :${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 9 : RUN echo $JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 10 : RUN echo "final jar file name"
 ---> Using cache
 ---> xxxxxxxxx
Step 11 : RUN echo ${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 12 : ADD ${JAR_FILE_NAME} app.jar
 ---> Using cache
 ---> xxxxxxxxx
Step 13 : RUN bash -c 'touch /app.jar'
 ---> Using cache
 ---> xxxxxxxxx
Step 14 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Using cache
 ---> xxxxxxxxx
Successfully built xxxxxxxxx
[INFO] Built xxx/myservice
</code>```

Output while pulling image:

```<code>I0603 13:48:32.849159 23106 exec.cpp:132] Version: 0.23.0
I0603 13:48:32.857393 23114 exec.cpp:206] Executor registered on slave 20170523-104056-1453378314-5050-11670-S48
Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.
Error: Invalid or corrupt jarfile /app.jar
</code>```

答:
I parameterized the output jar to be used in docker image in this way.

In Dockerfile, used a concrete name without any version. Removed ${JAR_FILE_NAME}, dynamic parameters from Dockerfile.

ADD myservice.jar app.jar

In POM.xml, I made maven to output artifact without version in the jar file name, by adding below element right under  tag.

<finalName>${project.artifactId}</finalName>

So, no manual update needed for Dockerfile. Forgetting to update Dockerfile and then build getting failed was really disturbing. I let Maven to manage versions and those versions are used as finite image tags, and thus "reproducible builds" work for me.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to parameterize the final jar file name in docker build. I need docker-maven-plugin to take jar file name passed via command line parameter. Maven build is not throwing any error while building image.

If I hard-code the jar file name in dockerfile, it is working fine.

Maven command to docker build:

mvn -X -s settings.xml docker:build -DJAR_FILE_NAME=${filename}

My docker file:

RUN curl -kfsSL https://example.com/UnlimitedJCEPolicyJDK8/US_export_policy.jar > US_export_policy.jar \
&& curl -kfsSL https://example.com//UnlimitedJCEPolicyJDK8/local_policy.jar > local_policy.jar \
    && mv local_policy.jar ${JAVA_HOME}/jre/lib/security \
    && mv US_export_policy.jar ${JAVA_HOME}/jre/lib/security \
    && rm -rf US_export_policy.jar local_policy.jar

ENV JAVA_KEYSTORE ${JAVA_HOME}/jre/lib/security/cacerts
RUN curl -kfsSL https://example.com/mycert.cer > mycert.cer \
    && ${JAVA_HOME}/bin/keytool -v -importcert -file mycert.cer -keystore ${JAVA_KEYSTORE} -storepass dummy -alias dummy -noprompt \
    && rm mycert.cer

VOLUME /tmp
#ADD myservice-2.0.2-SNAPSHOT.jar app.jar   <-hard-coded name works fine

RUN echo "final jar file name"
RUN echo ${JAR_FILE_NAME}

ADD ${JAR_FILE_NAME} app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

My POM.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.0</version>
    <configuration>
        <imageName>${docker.image.prefix}/myservice</imageName>
        <dockerDirectory>src/main/docker</dockerDirectory>
        <resources>
            <resource>
                <targetPath>${docker.resource.targetPath}</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>

Output from docker build process:

Step 6 : VOLUME /tmp
 ---> Using cache
 ---> xxxxxxxxx
Step 7 : RUN /bin/bash -c echo JAR_FILE_NAME1 in docker :$JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 8 : RUN /bin/bash -c echo JAR_FILE_NAME2 in docker :${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 9 : RUN echo $JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 10 : RUN echo "final jar file name"
 ---> Using cache
 ---> xxxxxxxxx
Step 11 : RUN echo ${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 12 : ADD ${JAR_FILE_NAME} app.jar
 ---> Using cache
 ---> xxxxxxxxx
Step 13 : RUN bash -c 'touch /app.jar'
 ---> Using cache
 ---> xxxxxxxxx
Step 14 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Using cache
 ---> xxxxxxxxx
Successfully built xxxxxxxxx
[INFO] Built xxx/myservice

Output while pulling image:

I0603 13:48:32.849159 23106 exec.cpp:132] Version: 0.23.0
I0603 13:48:32.857393 23114 exec.cpp:206] Executor registered on slave 20170523-104056-1453378314-5050-11670-S48
Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.
Error: Invalid or corrupt jarfile /app.jar


问:
Why is passenger hitting my index page so aggressively
I just moved my apache/mongrel setups to use passenger and I started noticing my index page is getting hit pretty aggressively (approx 5000 hits a day)

I chucked in some logging and it turns out the ip address (REMOTE_ADDR) is showing up as "::1" for these hits.

Has anyone seen this kind of activity? There must be a reason for it. Is there any setting I forgot to configure or set?

EDIT

Thanks Gavin, it looks like this is the dummy connection. Now the question is how I go about disabling it, Passenger conflicts with mod rewrite

I just posted a question on the passenger news group (may take a few mins to show up), will update this as soon as I hear back.

UPDATE 2

These 3 lines in my Apache configuration solve the issue:

```<code>RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]
</code>```

I am trying to find out if this belongs in passenger or is a bug local to my setup.

答: Do you have some type of monitoring system hitting the web server? I've used Passenger for months and haven't seen this.</p>

ContentLicense: CC BY-SA 2.5

Body:
I just moved my apache/mongrel setups to use passenger and I started noticing my index page is getting hit pretty aggressively (approx 5000 hits a day)

I chucked in some logging and it turns out the ip address (REMOTE_ADDR) is showing up as "::1" for these hits.

Has anyone seen this kind of activity? There must be a reason for it. Is there any setting I forgot to configure or set?

EDIT

Thanks Gavin, it looks like this is the dummy connection. Now the question is how I go about disabling it, Passenger conflicts with mod rewrite

I just posted a question on the passenger news group (may take a few mins to show up), will update this as soon as I hear back.

UPDATE 2

These 3 lines in my Apache configuration solve the issue:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]

I am trying to find out if this belongs in passenger or is a bug local to my setup.

OwnerDisplayName: Matt Darby


问:
Set Android Gallery widget to show specific starting image
I have a task where the user can select an image from a GridView representing a photo album, and from this I start a new activity which displays a Gallery widget to show the images of the photo album. However, I can't seem to get the Gallery widget to show the contents of the photo album with a given image as the starting point. Ideally I would like a Gallery#setStartingImage(int position) or something similar.

Any ideas would be greatly appreciated.

答: After looking a little deeper into the inheritance hierarchy of Gallery, I found the method setSelection() defined in the AbsSpinner class which Gallery extends. This seems to do the job.</p>


问:
Find strings with maximum vowels
I want to find strings with maximum vowels in Python, but I don't know how.

Examples

Input

```<code>['Zak6aa','kak','ll','ak']
</code>```

Output:

```<code>['Zak6aa']
</code>```

Another if two or more strings tie for max vowels:

```<code>['Zaa', 'bii','ak']
</code>```

output is:

```<code>['Zaa', 'bii']
</code>```

My try:

```<code>def maxv(string):
    sam=0
    seq=[]
    for i in range(len(string)):
        k=0
        v=0
        for char in string[i]:
             if char in "aeiouy":
                v = v+1
        k=(len(string[i]))-v
        if (v >=k):
            seq=seq+[string[i]]
    return seq
</code>```

答:
You can sort them by the number of vowels:

```<code>l = ['Zak6aa','kak','ll','ak']
sorted(l, key=lambda x: sum(1 for y in x if y in 'aeiouAEIOU'), reverse=True)
['Zak6aa', 'kak', 'ak', 'll']
</code>```

If you need all with the same max lenght, you can use zip with the number of vowels before sorting and then just filter the higher "scores":

```<code>l = ['Zaa', 'bii','ak']
slist =sorted(zip(map(lambda x: sum(1 for y in x if y in 'aeiouAEIOU'), l), l), reverse=True)
filter(lambda x: x[0] == slist[0][0], slist)
[(2, 'bii'), (2, 'Zaa')]
</code>```

Title: Find strings with maximum vowels

Body:
I want to find strings with maximum vowels in Python, but I don't know how.

Examples

Input

['Zak6aa','kak','ll','ak']

Output:

['Zak6aa']

Another if two or more strings tie for max vowels:

['Zaa', 'bii','ak']

output is:

['Zaa', 'bii']

My try:

def maxv(string):
    sam=0
    seq=[]
    for i in range(len(string)):
        k=0
        v=0
        for char in string[i]:
             if char in "aeiouy":
                v = v+1
        k=(len(string[i]))-v
        if (v >=k):
            seq=seq+[string[i]]
    return seq

Body:
You can sort them by the number of vowels:

l = ['Zak6aa','kak','ll','ak']
sorted(l, key=lambda x: sum(1 for y in x if y in 'aeiouAEIOU'), reverse=True)
['Zak6aa', 'kak', 'ak', 'll']

If you need all with the same max lenght, you can use zip with the number of vowels before sorting and then just filter the higher "scores":

l = ['Zaa', 'bii','ak']
slist =sorted(zip(map(lambda x: sum(1 for y in x if y in 'aeiouAEIOU'), l), l), reverse=True)
filter(lambda x: x[0] == slist[0][0], slist)
[(2, 'bii'), (2, 'Zaa')]


问:
Defining global struct array of pointers
im learning c programing.
I want to define a global struct array of. so I would have a pointer to that array that each member of the array is a struct of complex numbers.
my goal is to be able to acces to this array by his pointer (*vars) and being able to change/read its members on every function at the main.

Im facing troubles with this issue and im not sure how and where to define each thing.
I tried this next code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct complext
{
    double real;
    double img;
} complex;
complex* vars;

int main()
{
    int i;
    vars = malloc(6 * sizeof(vars));
    for (i = 0; i < 6;)
        vars[i]->real = 0;
}
</code>```

Im getting an error when im trying to acces vars[i].
"request for member 'real' im something not a structure or a union.
Thanks!

答: vars is of type struct complext *, but vars[i] is of type struct complext, so you just have to use vars[i].real instead of vars[i]->real.

Body:
im learning c programing.
I want to define a global struct array of. so I would have a pointer to that array that each member of the array is a struct of complex numbers.
my goal is to be able to acces to this array by his pointer (*vars) and being able to change/read its members on every function at the main.

Im facing troubles with this issue and im not sure how and where to define each thing.
I tried this next code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct complext
{
    double real;
    double img;
} complex;
complex* vars;

int main()
{
    int i;
    vars = malloc(6 * sizeof(vars));
    for (i = 0; i < 6;)
        vars[i]->real = 0;
}

Im getting an error when im trying to acces vars[i].
"request for member 'real' im something not a structure or a union.
Thanks!


问:
Radio buttons are scrolling with background, how to fix this?
I've got a problem with the radio buttons.
I am trying to fix the radio buttons on the background just like the other elements.
But now they are scrolling with the background when I am making the page smaller.
Can you please help me?
Thanks in advance!
For example:

label[class=number]::before {
    counter-increment: section;
    content: counter(section) " " ;
    display: inline-block;
    color: white;
    width: 20px;
    background-color: black;
    text-align: center;
    padding-top: 1%;
    margin-left: 10px;
    padding-bottom: 1%;
}

label[class=number] {
 display: inline-block;
    margin-top: 20px;
    width: 345px;
}

#bestellen input[type=number], #bestellen input[type=text], select {
 width: 40px;
    margin-left: 102%;
    display: block;
    margin-top: -7%;
    border-color: skyblue;
    border-style: double;
}

input[type=range] {
    width: 40px;
    position: relative;
    margin-left: 102%;
    background-color: transparent;
    margin-top: -5%;
    display: block;
}

small {
 display: block;
    margin-left: 420px;
    margin-top: -1.5%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="bestellen" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
        <label class="number" id="David_Vann">David Vann - Aquarium: <input size="3" name="David_Vann" type="number" min="1"></label><small> Max. 10 exemplaren</small>
        <label class="number" id="Robert_Seethaler">Robert Seethaler - Een heel leven: <input size="3" name="Robert_Seethaler" type="text" pattern="[0-9]{2}"></label><small> Max. 99 exemplaren</small>
        <label id="Paula" class="number">Paula Hawkins - Het meisje in de trein: <input name="Paula_Hawkins" type="range" min="0" max="15" step="5" list="Paula_Hawkins"></label><small>Bestel 0, 5, 10 of 15 exemplaren</small>
          <datalist id="Paula_Hawkins">
            <option value="0">
            <option value="5">
            <option value="10">
            <option value="15">
         </datalist>
        <label class="number" id="Ernest_van_der_kwast">Ernest van der Kwast - De ijsmakers: </label>
        <label id="ernest"> <input type="radio" name="Ernest van der kwast" value="1">1</label>
        <label id="ernest"> <input type="radio" name="Ernest van der kwast" value="10">10</label>
        <label id="ernest"> <input type="radio" name="Ernest van der kwast" value="20">20</label><br>
        <label class="number" id="Bert_natter">Bert Natter - Remington:
            <select name="Bert Natter">
              <option value="geen">geen</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
             </select>
         </label>
   </form> </code>```

答:
if you want to set radio button after label then update code and move input radio after label tag</p>

```<code><label id="ernest"> 1<input type="radio" name="Ernest van der kwast" value="1"></label>
<label id="ernest"> 10<input type="radio" name="Ernest van der kwast" value="10"></label>
<label id="ernest"> 20<input type="radio" name="Ernest van der kwast" value="20"></label><br>
</code>```

Body:
I've got a problem with the radio buttons.
I am trying to fix the radio buttons on the background just like the other elements.
But now they are scrolling with the background when I am making the page smaller.
Can you please help me?
Thanks in advance!
For example:

label[class=number]::before {
    counter-increment: section;
    content: counter(section) " " ;
    display: inline-block;
    color: white;
    width: 20px;
    background-color: black;
    text-align: center;
    padding-top: 1%;
    margin-left: 10px;
    padding-bottom: 1%;
}

label[class=number] {
 display: inline-block;
    margin-top: 20px;
    width: 345px;
}

#bestellen input[type=number], #bestellen input[type=text], select {
 width: 40px;
    margin-left: 102%;
    display: block;
    margin-top: -7%;
    border-color: skyblue;
    border-style: double;
}

input[type=range] {
    width: 40px;
    position: relative;
    margin-left: 102%;
    background-color: transparent;
    margin-top: -5%;
    display: block;
}

small {
 display: block;
    margin-left: 420px;
    margin-top: -1.5%;
}

<form id="bestellen" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
        David Vann - Aquarium: <input size="3" name="David_Vann" type="number" min="1"> Max. 10 exemplaren
        Robert Seethaler - Een heel leven: <input size="3" name="Robert_Seethaler" type="text" pattern="[0-9]{2}"> Max. 99 exemplaren
        Paula Hawkins - Het meisje in de trein: <input name="Paula_Hawkins" type="range" min="0" max="15" step="5" list="Paula_Hawkins">Bestel 0, 5, 10 of 15 exemplaren
          <datalist id="Paula_Hawkins">
            <option value="0">
            <option value="5">
            <option value="10">
            <option value="15">
         </datalist>
        Ernest van der Kwast - De ijsmakers:
         <input type="radio" name="Ernest van der kwast" value="1">1
         <input type="radio" name="Ernest van der kwast" value="10">10
         <input type="radio" name="Ernest van der kwast" value="20">20

        Bert Natter - Remington:
            <select name="Bert Natter">
              <option value="geen">geen</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
             </select>

   </form>

Body:
if you want to set radio button after label then update code and move input radio after label tag

<label id="ernest"> 1<input type="radio" name="Ernest van der kwast" value="1"></label>
<label id="ernest"> 10<input type="radio" name="Ernest van der kwast" value="10"></label>
<label id="ernest"> 20<input type="radio" name="Ernest van der kwast" value="20"></label><br>


问:
Tkinter taking txt data from another definition of button
My code is looking like this right now:

```<code>def browse_button():
    ftypes1 = [('file', '*.txt')]
    filename1 = filedialog.askopenfilename(filetypes = ftypes1)
    print(filename1)
    with open(filename1) as newfile1:
        file1 = pd.read_table(newfile1, sep=',', names=('A', 'B', 'C'))
        print file1

    return filename1

def file_button():
    abc=browse_button()
    print abc
                  # in this definition i want to work on the input file that
                    i have imported at start in browse_button definition,but
                    it doesn't work good
</code>```

i am using this code to run them them

```<code>if __name__ == '__main__':
    root = Tk()
    root.title('title')
    root.geometry("450x150+200+200")
    b1 = Button(root, text='one', font=('arial', 12), command=browse_button)
    b1.pack(side=LEFT, padx=5, pady=5)
    b6 = Button(root, text='file', font=('arial', 12), command=file_button)
    b6.pack(side=LEFT, padx=5, pady=5)
</code>```

Thank You in advice!

答:
In your question you have stated you want to work on the file that you have opened but all you are doing is returning is only the file name.

return(filename1) this statement in your browse_button() function is only returning the name of the file to file_button() and not the data. In result say the file name was my_file the print abc will result in: my_file

Where you create the variable filename1 all you are doing is getting the file name. If you are trying to work with the content of the file then you need to return file1 from your with open statement instead.

Update:

I have created a similar code that opens a text file I created and will print out its content using the 2nd function.

EDIT: I added your buttons to my answer so you can see how it should all look together.

```<code># Python 3 imports
from tkinter import *
from tkinter.filedialog import askopenfilename

# Python 2 imports
# from Tkinter import *
# from tkFileDialog import askopenfilename

def browse_button():
    ftypes1 = [('file', '*.txt')]
    filename1 =  askopenfilename(filetypes = ftypes1)
    with open(filename1) as newfile1:
        file1 = newfile1.read()
        print (file1)

    return filename1

def file_button():
    abc=browse_button()
    print (abc)

if __name__ == '__main__':
    root = Tk()
    root.title('title')
    root.geometry("450x150+200+200")
    b1 = Button(root, text='one', font=('arial', 12), command=browse_button)
    b1.pack(side=LEFT, padx=5, pady=5)
    b6 = Button(root, text='file', font=('arial', 12), command=file_button)
    b6.pack(side=LEFT, padx=5, pady=5)

    root.mainloop()
</code>```

Result:

```<code>Content of my_file!
</code>```

Body:
My code is looking like this right now:

def browse_button():
    ftypes1 = [('file', '*.txt')]
    filename1 = filedialog.askopenfilename(filetypes = ftypes1)
    print(filename1)
    with open(filename1) as newfile1:
        file1 = pd.read_table(newfile1, sep=',', names=('A', 'B', 'C'))
        print file1

    return filename1

def file_button():
    abc=browse_button()
    print abc
                  # in this definition i want to work on the input file that
                    i have imported at start in browse_button definition,but
                    it doesn't work good

i am using this code to run them them

if __name__ == '__main__':
    root = Tk()
    root.title('title')
    root.geometry("450x150+200+200")
    b1 = Button(root, text='one', font=('arial', 12), command=browse_button)
    b1.pack(side=LEFT, padx=5, pady=5)
    b6 = Button(root, text='file', font=('arial', 12), command=file_button)
    b6.pack(side=LEFT, padx=5, pady=5)

Thank You in advice!

Body:
In your question you have stated you want to work on the file that you have opened but all you are doing is returning is only the file name.

return(filename1) this statement in your browse_button() function is only returning the name of the file to file_button() and not the data. In result say the file name was my_file the print abc will result in: my_file

Where you create the variable filename1 all you are doing is getting the file name. If you are trying to work with the content of the file then you need to return file1 from your with open statement instead.

Update:

I have created a similar code that opens a text file I created and will print out its content using the 2nd function.

EDIT: I added your buttons to my answer so you can see how it should all look together.

# Python 3 imports
from tkinter import *
from tkinter.filedialog import askopenfilename

# Python 2 imports
# from Tkinter import *
# from tkFileDialog import askopenfilename

def browse_button():
    ftypes1 = [('file', '*.txt')]
    filename1 =  askopenfilename(filetypes = ftypes1)
    with open(filename1) as newfile1:
        file1 = newfile1.read()
        print (file1)

    return filename1

def file_button():
    abc=browse_button()
    print (abc)

if __name__ == '__main__':
    root = Tk()
    root.title('title')
    root.geometry("450x150+200+200")
    b1 = Button(root, text='one', font=('arial', 12), command=browse_button)
    b1.pack(side=LEFT, padx=5, pady=5)
    b6 = Button(root, text='file', font=('arial', 12), command=file_button)
    b6.pack(side=LEFT, padx=5, pady=5)

    root.mainloop()

Result:

Content of my_file!


问:
What are some example javascript frameworks that people use?
I am really big fan of jQuery, but I don't see it as a framework for a site, more like a library.  I am looking for some sort of framework that will give me the tools to build really structured applications in javaScript.  I have found backbone.js, but find it somewhat confusing.  Is that a good one, and are there others similar to it?  an MVC pattern would be really cool, but I havent found anything.</p>

答:
I use currently RightJS with RequireJS. It has worked out well for my purposes. I used jQuery + jQuery UI previously. The current combo fits my style better (more barebone functionality instead of just DOM wrapper + UI plugins).

I know RightJS isn't that popular. The docs are adequate and the author is responsive. This makes up for that. :)

Some other alternatives:

qooxdoo

MooTools

Prototype

I'm sure there are plenty of more alternatives. It really comes down to your preferences and exact needs.

Personally I have been looking at Sencha's offerings (ExtJS, Sencha Touch) lately. The latter is particularly interesting as it provides simple means to write cross-platform apps for mobile devices. Works great in iPad at least!


问:
PHP header conflict
Hello i make a project and i have the fallowing problem.
In my index page i have a dynamic layout:

```<code><html>
<head>
    <link rel="stylesheet" type="text/css" href="index2.css">
</head>
<body class="news">
  <header>
    <div class="nav">
      <ul>
        <li class="home"><a href="index2.php?page=welcome">Home</a></li>
        <li class="logare"><a class="active" a href="index2.php?page=admin_login">Admin</a></li>
        <li class="registration"><a href="index2.php?page=registration">Registration</a></li>
        <li class="produse"><a href="index2.php?page=produse">Produse</a></li>
      </ul>
    </div>
  </header>

  <div id="content">
<?php
 $p=$_GET['page'];

 switch($p){
        case "welcome":
          include('welcome.php');
          break;
        case "admin_login":
          include('Admin_login.php');
          break;
        case "registration":
          include('Registration.php');
          break;
        case "produse":
          include('produse.php');
          break;
        default:
           include('welcome.php');
          break;
 }?>
 </div>

</body>
</html>
</code>```

in default and welcome case it;s redirecting me to my welcome.php page:

```<code><?php
    session_start();

 if(!$_SESSION['email'])
    {

        header("Location: login.php");//redirect to login page to secure the welcome page without login access.
    }

    ?>

<html>
<head>

<title>
Registration
</title>
</head>

<body>
<h1>Welcome</h1><br>
<?php
    echo $_SESSION['email'];
    ?>

<h1><a href="logout.php">Logout here</a> </h1>

</body>

</html>
</code>```

Because i have a redirecting in welcome.php too ,my header is not loading from the dynamic layout.How can i repair this,but still redirecting me to login?

答:
To avoid PHP header conflicts, I prefer to use JS redirection instead. See the below code that I have modified for you.

```<code><?php
    session_start();

    if(!$_SESSION['email']) {
        ?>
            <script language="javascript" type="text/javascript">
                alert("User not logged in.");
                window.location = 'login.php';
            </script>
        <?php
    }
?>
</code>```

Hope this helps.

Title: PHP header conflict

Body:
Hello i make a project and i have the fallowing problem.
In my index page i have a dynamic layout:

    <link rel="stylesheet" type="text/css" href="index2.css">

Home

Admin

Registration

Produse

<?php
 $p=$_GET['page'];

 switch($p){
        case "welcome":
          include('welcome.php');
          break;
        case "admin_login":
          include('Admin_login.php');
          break;
        case "registration":
          include('Registration.php');
          break;
        case "produse":
          include('produse.php');
          break;
        default:
           include('welcome.php');
          break;
 }?>

in default and welcome case it;s redirecting me to my welcome.php page:

<?php
    session_start();

 if(!$_SESSION['email'])
    {

        header("Location: login.php");//redirect to login page to secure the welcome page without login access.
    }

    ?>

<title>
Registration
</title>

Welcome

<?php
    echo $_SESSION['email'];
    ?>

Logout here

Because i have a redirecting in welcome.php too ,my header is not loading from the dynamic layout.How can i repair this,but still redirecting me to login?

Body:
To avoid PHP header conflicts, I prefer to use JS redirection instead. See the below code that I have modified for you.

<?php
    session_start();

    if(!$_SESSION['email']) {
        ?>
            <script language="javascript" type="text/javascript">
                alert("User not logged in.");
                window.location = 'login.php';
            </script>
        <?php
    }
?>

Hope this helps.


问:
How specify php2wsdl @param cardinality?
I'd like to generate a WSDL such that SoapUI would mock a request as:

```<code><soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="https://v121d164.prevnet/webservices/server.php">
  <soapenv:Header/>
  <soapenv:Body>
    <ser:myService soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <!--Zero or more repetitions:-->
      <code xsi:type="xsd:string">?</code>
    </ser:myService>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

PHP2WSDL documentation have examples for instance variables:

```<code>/**
 * @var string
 * @maxOccurs 0
 */
</code>```

But it says nothing about params.
I've tried to use

```<code>/**
 * @param string
 * @maxOccurs 0
 */
</code>```

But no luck.

答:
Create a class and use it as a parameter for your method. You can define cardinality for properties of that class with @minOccurs tag:</p>

```<code>Class MyServiceInput
{
   /**
    * @var string
    * @minOccurs 0
    */
   public $str;
}

class MyService
{
   /**
    * @soap
    * @param MyServiceInput $inputParam
    */
    public function myMethod($inputParam)
    {
    }
}
</code>```

Body:
I'd like to generate a WSDL such that SoapUI would mock a request as:

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="https://v121d164.prevnet/webservices/server.php">
  <soapenv:Header/>
  <soapenv:Body>
    <ser:myService soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

      ?
    </ser:myService>
  </soapenv:Body>
</soapenv:Envelope>

PHP2WSDL documentation have examples for instance variables:

/**
 * @var string
 * @maxOccurs 0
 */

But it says nothing about params.
I've tried to use

/**
 * @param string
 * @maxOccurs 0
 */

But no luck.

Body:
Create a class and use it as a parameter for your method. You can define cardinality for properties of that class with @minOccurs tag:

Class MyServiceInput
{
   /**
    * @var string
    * @minOccurs 0
    */
   public $str;
}

class MyService
{
   /**
    * @soap
    * @param MyServiceInput $inputParam
    */
    public function myMethod($inputParam)
    {
    }
}


问:
Setting a decimal value on a form doesnt always work - Dynamics CRM 2013
Hope someone can help with this. I know how to set a field value on a form and it works in a way. My query is around the fact that it only works if I put this line below into the form load event as a line by itself.

Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

However, in reality I need to have some conditional checks before I set this value and when I put this line into those conditional checks, then what I notice is that the textbox is blank but if I look at the value in the data entity it does indicate it has the value of 1.01.

alert("No. in entity:" + Xrm.Page.data.entity.attributes.get('cal_entrynumber').getValue());

So I wanted to know if anyone can pinpoint me to anything that potentially might be the cause for this ... here is the code in which the line sits (and doesnt work).

```<code>var queryString = "?$select=cal_EntryNumber&$filter=cal_SafetyProgrammeNo eq '" + spNo + "'&top=1&$orderby=cal_EntryNumber desc";
SDK.REST.retrieveMultipleRecords(
    "cal_operation",
    queryString,
    function (results) {
        //alert(results.length);
        if (results.length == 0) {
            //var entry = 1.01;
            //alert("Entry No:" + Number(entry));
            Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

        }
        else {
            // Code to go here.
        }
    },
    errorHandler,
    function () {
        // OnComplete handler
    }
    );
</code>```

答:
This should be working.

```<code>Xrm.Page.getAttribute("fieldname").setValue(parseFloat(eval(1.01)));
</code>```

Or this should also work.

```<code>Xrm.Page.getAttribute("fieldname").setValue("1.01");
</code>```

References:

https://social.microsoft.com/Forums/en-US/487202fe-9982-45e1-8133-33b883927c35/haw-to-set-the-precision-of-a-dicimal-field-using-javascrip?forum=crmdevelopment

http://mscrmtutorials.blogspot.com/2015/10/get-or-set-values-of-all-data-types.html

Body:
Hope someone can help with this. I know how to set a field value on a form and it works in a way. My query is around the fact that it only works if I put this line below into the form load event as a line by itself.

Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

However, in reality I need to have some conditional checks before I set this value and when I put this line into those conditional checks, then what I notice is that the textbox is blank but if I look at the value in the data entity it does indicate it has the value of 1.01.

alert("No. in entity:" + Xrm.Page.data.entity.attributes.get('cal_entrynumber').getValue());

So I wanted to know if anyone can pinpoint me to anything that potentially might be the cause for this ... here is the code in which the line sits (and doesnt work).

var queryString = "?$select=cal_EntryNumber&$filter=cal_SafetyProgrammeNo eq '" + spNo + "'&top=1&$orderby=cal_EntryNumber desc";
SDK.REST.retrieveMultipleRecords(
    "cal_operation",
    queryString,
    function (results) {
        //alert(results.length);
        if (results.length == 0) {
            //var entry = 1.01;
            //alert("Entry No:" + Number(entry));
            Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

        }
        else {
            // Code to go here.
        }
    },
    errorHandler,
    function () {
        // OnComplete handler
    }
    );

Body:
This should be working.

Xrm.Page.getAttribute("fieldname").setValue(parseFloat(eval(1.01)));

Or this should also work.

Xrm.Page.getAttribute("fieldname").setValue("1.01");

References:

https://social.microsoft.com/Forums/en-US/487202fe-9982-45e1-8133-33b883927c35/haw-to-set-the-precision-of-a-dicimal-field-using-javascrip?forum=crmdevelopment

http://mscrmtutorials.blogspot.com/2015/10/get-or-set-values-of-all-data-types.html


问:
Include square brackets in posting from jsp
Can we post square brackets in parameter name of a text area field in html/jsp? I am trying to post a jsp array like <textarea name = "arr['$i']">and variable i has [] in them. So what is the best way to encode them in a way that I can post them?

Thanks in advance

答:
Not required to pass it as squarebracket and generate a unique id. Note: $i is not applicable in JSP for a variable. The getParameter() indeed returns only the first one when there are multiple values on the same name. You need to use getParameterValues() instead to get all of those values.

```<code><textarea name="txtarea">Content 1 </textarea>
<textarea name="txtarea">Content 2 </textarea>
</code>```

String[] txtareaids = request.getParameterValues("txtarea");

Body:
Not required to pass it as squarebracket and generate a unique id. Note: $i is not applicable in JSP for a variable. The getParameter() indeed returns only the first one when there are multiple values on the same name. You need to use getParameterValues() instead to get all of those values.

<textarea name="txtarea">Content 1 </textarea>
<textarea name="txtarea">Content 2 </textarea>

String[] txtareaids = request.getParameterValues("txtarea");


问:
Returning object after deserializing if property exists c#
I have a Person class and Interest class. Person class has a property that contains a list of the Interest class. Currently, I am deserializing the json and then I am looping through each of the Person object to see if it contains a list of interests. This approach is taking a very long time to complete. Is there a more efficient way of doing this instead of looping through all of Person object?</p>

答:
Have you tried something like this?

```<code>var returnedPersons = Deserialize(Result); //replace with whatever you deserialize to.

returnedPersons.Where(x => x.Interests.Count > 0).ToList(); //here you use linq to grab whatever you want
</code>```

Again, not sure how big of a return you have of persons and how long is a very long time. But this would be the industry standard to getting a list of all the persons that have a list of interests

Body:
Have you tried something like this?

var returnedPersons = Deserialize(Result); //replace with whatever you deserialize to.

returnedPersons.Where(x => x.Interests.Count > 0).ToList(); //here you use linq to grab whatever you want

Again, not sure how big of a return you have of persons and how long is a very long time. But this would be the industry standard to getting a list of all the persons that have a list of interests


问:
facebook like chat application in ASP.net
I want to build web based facebook like lightweight chat for my site.

Website build on ASP .net on SQL server 2005.

I am interesetd in XMPP commmunication, but not able to find open source XMPP server with supportedlibrary for C# so that I can create client for my site.

Have checked googling butno luck for C# library; all I could found is plugin and jar.

Is it possible to implement chat logic and XMPP server communication in different language, and accessing thisdata through iframe or by other means on my site.

Thanks,
Hitesh.

答:
http://www.ag-software.de/agsxmpp-sdk/

That library seems to be pretty good.


问:
SharedPreferences Logout not working
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

```<code>SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}
</code>```

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

```<code>void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
</code>```

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

答:
Try it.   </p>

```<code> SharedPreferences mySPref = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = mySPrefs.edit();
        editor.remove(String key);
        editor.apply();
</code>```

Title: SharedPreferences Logout not working

Body:
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

Body:
Try it.

 SharedPreferences mySPref = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = mySPrefs.edit();
        editor.remove(String key);
        editor.apply();


问:
Can STL algorithms be used with circular lists?
Creating an STL compliant iterator for your custom list is pretty mundane.

Yet, if the reffered list is a circular one, it seems quite pointless since all STL algorithms are operating on a [first, last) range and in a circular list first = last.

Is there a standard/consice way to overcome this obstacle and have STL algorithms operate on "home made" circular lists ?

I'm supposing defining STL compliant iterators is the first step to this goal, but a solution that would operate on ranges might also be possible.

I need to implement this for a plethora of "home made" structs. My current solution is to derive from boost::iterator_facade and then create a custom range class (like Rudolph's) and use any algorithm wrapped around range-based execution. Still this has some logical obstacles and would like to see alternatives and or solutions that worked out.

答:
Said that in many algorithms (I'm not talking about STL, but in general) a null-leaf(s) or null element(s) is(are) inserted in the internal data structure in order to improve performance, I feel like keeping an empty/null element in your circular list can make the trick.

The null element is not fixed in position, obviously, and it will move according to your data flow.

At the same time you'll keep the last N sample in your data struct (size N + 1 empty element) contiguous.

That makes feasible a range [first,last) where first != last.

The null element is the one pointed by last, and it's where the next insertion will take place.

At every insertion, once N elements are in the container, the element pointed by first is "nullified", and first incremented.

Hope this may help.


问:
Can you request permissions synchronously in Android Marshmallow (API 23)'s runtime permissions model?
Say you have a method like this:

```<code>public boolean saveFile (Url url, String content) {

   // save the file, this can be done a lot of different ways, but
   // basically the point is...

   return save_was_successful;
}
</code>```

Throughout your app, if you want to save a file to external storage, you do something like...

```<code>if (saveFile(external_storage_url, "this is a test")) {
   // yay, success!
} else { // notify the user something was wrong or handle the error }
</code>```

This is a simplified example, so don't get on my case about blocking the UI, handling exceptions properly, etc.  If you don't like file saving, you could imagine a getContact() or getPhoneState() or whatever.  The point is it's a permission-needing operation that returns some value(s) and it's used throughout the app.

In Android <= Lollipop, if the user had installed and agreed to granting android.permission.WRITE_EXTERNAL_STORAGE or whatever, all would be good.

But in the new Marshmallow (API 23) runtime permission model, before you can save the file to external storage, you're supposed to (1) check if the permission has been granted.  If not, possibly (2) show a rationale for the request (if the system thinks it's a good idea) with a toast or whatever and (3) ask the user to grant permission via a dialog, then basically sit back and wait for a callback...

(so your app sits around, waiting...)

(4) When the user finally responds to the dialog, the onRequestPermissionsResult() method fires off, and your code now (5) has to sift through WHICH permission request they are actually responding to, whether the user said yes or no (to my knowledge there's no way to handle "no" vs. "no and don't ask again"), (6) figure out what they were trying to accomplish in the first place that prompted the whole ask-for-permissions process, so that the program can finally  (7) go ahead and do that thing.

To know what the user was trying to do in step (6) involves having previously passed a special code (the "permissions request response") which is described in the docs as an identifier of the type of permission request (camera/contact/etc.) but seems to me more like a "specifically, what you were trying to do when you realized you'd need to ask for permissions" code, given that the same permission/group may be used for multiple purposes in your code, so you'd need to use this code to return execution to the appropriate place after getting the permission.

I could be totally misunderstanding how this is supposed to work-- so please let me know if I'm way off-- but the larger point is I'm really not sure how to even think about doing all of the above w/the saveFile() method described previously due to the asynchronous "wait for the user to respond" part.  The ideas I've considered are pretty hacky and certainly wrong.

Today's Android Developer Podcast hinted that there may be a synchronous solution around the corner, and there was even talk about a magic, one-step alt-enter type of "add a permissions request" tool in Android Studio.  Still, how the runtime permission process might be shoved into a saveFile() or whatever-- I'm thinking something along the lines of :

```<code>public boolean saveFile(Url url, String content) {
   //   this next line will check for the permission, ask the user
   //   for permission if required, maybe even handle the rationale
   //   situation
   if (!checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        R.string.permission_storage_rationale))
       {
           return false; // or throw an exception or whatever
       } else {

   // try to save the file

   return save_was_successful;

   }
}
</code>```

So the above checkPermission() would fail if the user didn't have and also refused to grant the permission.  Maybe one could use a loop around checkPermission() to try asking up to 3 times or something, or better would be if a sane dont-be-annoying-policy was handled by the method.

Is such a thing possible?  Desirable?  Would any such solution block the UI thread?  From the podcast it sounded like Google may have a solution like this coming 'round the corner, but I wanted to get thoughts on whether there was something-- a convenience class, a pattern, something-- that doesn't involve everyone having to refactor all permission-requiring operations, which I must assume could get pretty messy.

Sorry for the long-winded question, but I wanted to be as complete as possible.  I'll take my answer off the air.  Thanks!

Update:  Here is the transcript from the podcast mentioned above.

Listen at about 41:20.  In this discussion:

Rough transcript:

Tor Norbye (Tools team):  "So it doesn't seem like it should be a lot of work for developers.  But I understand part of the problem is that these are not synchronous calls, right?.  So what you have to- actually change the way your activity is written to have a callback-- so it's really kinda like a state machine where... for this state, you-"

Poiesz (product manager): "Ah- I thought- there was a- there might be an option for synchronous response--"

Norbye: "Oh.  that would make things--"

Poiesz: "I can talk with folks internally.  I recall a discussion about synchronous- but we can find out."

Norbye: "Yeah. In fact we should probably make it into the tools.  Where you have an easy refactoring..."

Then he talks about using annotations in the tools to determine which APIs require permissions.. (which as of now doesn't work that great IMO) and how he wants the tools someday to actually generate the required code if it finds an unchecked "dangerous" method call:

Norbye:  "...then if you're on M as well it'll say, 'hey, are you actually checking for this permission or are you catching security exceptions?', and if you're not, we'll say 'you probably need to do something for requesting the permission here.'   What I would like though is for that to have a quick fix where you can go 'CHING!' and it inserts all the right stuff for asking, but the way things were back when I looked, this required restructuring a lot of things-- adding interfaces and callbacks, and changing the flow, and that we couldn't do.  But if there's an easy synchronous mode as a temporary thing or a permanent thing, that would [be great]."

答:
Here's how I solved the "synchronicity" issue without having to explicitly block (and busy-wait), or without requiring a separate "boot-loader" Activity. I refactored splash screen Activity as follows:

update: A more complete example can be found here.

note: Because the requestPermissions() API calls startActivityForResult()

```<code>public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
    Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
    startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
}
</code>```

the main view-creation logic was moved from OnCreate() to OnCreate2(), and OnCreate() now handles the permissions check. If RequestPermissions() needs to be called, then the associated OnRequestPermissionsResult() restarts this activity (forwarding a copy of the original bundle).

```<code>[Activity(Label = "MarshmellowActivated",
    MainLauncher = true,
    Theme = "@style/Theme.Transparent",
    Icon = "@drawable/icon"
    ////////////////////////////////////////////////////////////////
    // THIS PREVENTS OnRequestPermissionsResult() from being called
    //NoHistory = true
)]
public class MarshmellowActivated : Activity
{
    private const int ANDROID_PERMISSION_REQUEST_CODE__SDCARD = 112;
    private Bundle _savedInstanceState;

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
    {
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode)
        {
            case ANDROID_PERMISSION_REQUEST_CODE__SDCARD:
                if (grantResults.Length > 0 && grantResults[0] == Permission.Granted)
                {
                    Intent restartThisActivityIntent = new Intent(this, this.GetType());
                    if (_savedInstanceState != null)
                    {
                        // *ref1: Forward bundle from one intent to another
                        restartThisActivityIntent.PutExtras(_savedInstanceState);
                    }
                    StartActivity(restartThisActivityIntent);
                }
                else
                {
                    throw new Exception("SD Card Write Access: Denied.");
                }
                break;
        }
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Android v6 requires explicit permission granting from user at runtime for extra sweet security goodness
        Permission extStoragePerm = ApplicationContext.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage);

        //if(extStoragePerm == Permission.Denied)
        if (extStoragePerm != Permission.Granted)
        {
            _savedInstanceState = savedInstanceState;
            // **calls startActivityForResult()**
            RequestPermissions(new[] { Android.Manifest.Permission.WriteExternalStorage }, ANDROID_PERMISSION_REQUEST_CODE__SDCARD);
        }
        else
        {
            OnCreate2(savedInstanceState);
        }
    }

    private void OnCreate2(Bundle savedInstanceState)
    {
        //...
    }
}
</code>```

ref1: Forward bundle from one intent to another

note: This can be refactored to handle more permissions generally. It currently handles the sdcard write permission only, which should convey the pertinent logic with sufficient clarity.

Body:
Say you have a method like this:

public boolean saveFile (Url url, String content) {

   // save the file, this can be done a lot of different ways, but
   // basically the point is...

   return save_was_successful;
}

Throughout your app, if you want to save a file to external storage, you do something like...

if (saveFile(external_storage_url, "this is a test")) {
   // yay, success!
} else { // notify the user something was wrong or handle the error }

This is a simplified example, so don't get on my case about blocking the UI, handling exceptions properly, etc.  If you don't like file saving, you could imagine a getContact() or getPhoneState() or whatever.  The point is it's a permission-needing operation that returns some value(s) and it's used throughout the app.

In Android <= Lollipop, if the user had installed and agreed to granting android.permission.WRITE_EXTERNAL_STORAGE or whatever, all would be good.

But in the new Marshmallow (API 23) runtime permission model, before you can save the file to external storage, you're supposed to (1) check if the permission has been granted.  If not, possibly (2) show a rationale for the request (if the system thinks it's a good idea) with a toast or whatever and (3) ask the user to grant permission via a dialog, then basically sit back and wait for a callback...

(so your app sits around, waiting...)

(4) When the user finally responds to the dialog, the onRequestPermissionsResult() method fires off, and your code now (5) has to sift through WHICH permission request they are actually responding to, whether the user said yes or no (to my knowledge there's no way to handle "no" vs. "no and don't ask again"), (6) figure out what they were trying to accomplish in the first place that prompted the whole ask-for-permissions process, so that the program can finally  (7) go ahead and do that thing.

To know what the user was trying to do in step (6) involves having previously passed a special code (the "permissions request response") which is described in the docs as an identifier of the type of permission request (camera/contact/etc.) but seems to me more like a "specifically, what you were trying to do when you realized you'd need to ask for permissions" code, given that the same permission/group may be used for multiple purposes in your code, so you'd need to use this code to return execution to the appropriate place after getting the permission.

I could be totally misunderstanding how this is supposed to work-- so please let me know if I'm way off-- but the larger point is I'm really not sure how to even think about doing all of the above w/the saveFile() method described previously due to the asynchronous "wait for the user to respond" part.  The ideas I've considered are pretty hacky and certainly wrong.

Today's Android Developer Podcast hinted that there may be a synchronous solution around the corner, and there was even talk about a magic, one-step alt-enter type of "add a permissions request" tool in Android Studio.  Still, how the runtime permission process might be shoved into a saveFile() or whatever-- I'm thinking something along the lines of :

public boolean saveFile(Url url, String content) {
   //   this next line will check for the permission, ask the user
   //   for permission if required, maybe even handle the rationale
   //   situation
   if (!checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        R.string.permission_storage_rationale))
       {
           return false; // or throw an exception or whatever
       } else {

   // try to save the file

   return save_was_successful;

   }
}

So the above checkPermission() would fail if the user didn't have and also refused to grant the permission.  Maybe one could use a loop around checkPermission() to try asking up to 3 times or something, or better would be if a sane dont-be-annoying-policy was handled by the method.

Is such a thing possible?  Desirable?  Would any such solution block the UI thread?  From the podcast it sounded like Google may have a solution like this coming 'round the corner, but I wanted to get thoughts on whether there was something-- a convenience class, a pattern, something-- that doesn't involve everyone having to refactor all permission-requiring operations, which I must assume could get pretty messy.

Sorry for the long-winded question, but I wanted to be as complete as possible.  I'll take my answer off the air.  Thanks!

Update:  Here is the transcript from the podcast mentioned above.

Listen at about 41:20.  In this discussion:

Rough transcript:

Tor Norbye (Tools team):  "So it doesn't seem like it should be a lot of work for developers.  But I understand part of the problem is that these are not synchronous calls, right?.  So what you have to- actually change the way your activity is written to have a callback-- so it's really kinda like a state machine where... for this state, you-"

Poiesz (product manager): "Ah- I thought- there was a- there might be an option for synchronous response--"

Norbye: "Oh.  that would make things--"

Poiesz: "I can talk with folks internally.  I recall a discussion about synchronous- but we can find out."

Norbye: "Yeah. In fact we should probably make it into the tools.  Where you have an easy refactoring..."

Then he talks about using annotations in the tools to determine which APIs require permissions.. (which as of now doesn't work that great IMO) and how he wants the tools someday to actually generate the required code if it finds an unchecked "dangerous" method call:

Norbye:  "...then if you're on M as well it'll say, 'hey, are you actually checking for this permission or are you catching security exceptions?', and if you're not, we'll say 'you probably need to do something for requesting the permission here.'   What I would like though is for that to have a quick fix where you can go 'CHING!' and it inserts all the right stuff for asking, but the way things were back when I looked, this required restructuring a lot of things-- adding interfaces and callbacks, and changing the flow, and that we couldn't do.  But if there's an easy synchronous mode as a temporary thing or a permanent thing, that would [be great]."

Body:
Here's how I solved the "synchronicity" issue without having to explicitly block (and busy-wait), or without requiring a separate "boot-loader" Activity. I refactored splash screen Activity as follows:

update: A more complete example can be found here.

note: Because the requestPermissions() API calls startActivityForResult()

public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
    Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
    startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
}

the main view-creation logic was moved from OnCreate() to OnCreate2(), and OnCreate() now handles the permissions check. If RequestPermissions() needs to be called, then the associated OnRequestPermissionsResult() restarts this activity (forwarding a copy of the original bundle).

[Activity(Label = "MarshmellowActivated",
    MainLauncher = true,
    Theme = "@style/Theme.Transparent",
    Icon = "@drawable/icon"
    ////////////////////////////////////////////////////////////////
    // THIS PREVENTS OnRequestPermissionsResult() from being called
    //NoHistory = true
)]
public class MarshmellowActivated : Activity
{
    private const int ANDROID_PERMISSION_REQUEST_CODE__SDCARD = 112;
    private Bundle _savedInstanceState;

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
    {
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode)
        {
            case ANDROID_PERMISSION_REQUEST_CODE__SDCARD:
                if (grantResults.Length > 0 && grantResults[0] == Permission.Granted)
                {
                    Intent restartThisActivityIntent = new Intent(this, this.GetType());
                    if (_savedInstanceState != null)
                    {
                        // *ref1: Forward bundle from one intent to another
                        restartThisActivityIntent.PutExtras(_savedInstanceState);
                    }
                    StartActivity(restartThisActivityIntent);
                }
                else
                {
                    throw new Exception("SD Card Write Access: Denied.");
                }
                break;
        }
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Android v6 requires explicit permission granting from user at runtime for extra sweet security goodness
        Permission extStoragePerm = ApplicationContext.CheckSelfPermission(Android.Manifest.Permission.WriteExternalStorage);

        //if(extStoragePerm == Permission.Denied)
        if (extStoragePerm != Permission.Granted)
        {
            _savedInstanceState = savedInstanceState;
            // **calls startActivityForResult()**
            RequestPermissions(new[] { Android.Manifest.Permission.WriteExternalStorage }, ANDROID_PERMISSION_REQUEST_CODE__SDCARD);
        }
        else
        {
            OnCreate2(savedInstanceState);
        }
    }

    private void OnCreate2(Bundle savedInstanceState)
    {
        //...
    }
}

ref1: Forward bundle from one intent to another

note: This can be refactored to handle more permissions generally. It currently handles the sdcard write permission only, which should convey the pertinent logic with sufficient clarity.


问:
Could doctrine provide records filtered by user roles, groups or permissions?
I've a project with a huge amount of data. I need to make query based on user role/group/permission. This means that a query like

```<code>$fooRepository = $this->getDoctrine()
    ->getManager()
    ->getRepository(Foo::class)
    ->findAll();
</code>```

should return different records if done by a ROLE_SUPER_ADMIN or by  ROLE_USER. Also, I need to filter record based on relations and so on.

I've different solution in mind:

inject user role inside the repository's query

create a role based repository

create a query for each role

Inject user role in repository's query

In this case each repository should be responsible to provide right data. This is a solution similar to this. In that solution record are filtered by tenant.

Create role based repository

In this case I'll need to create different repositories and instantiate them differently. But I don think this can be easy in doctrine? while I am writing, ... I am thinking this is an exaggerated solution.

Create queries for each roles

At the moment I think this is the more natural way to do queries. I just imagine that a repository should contain

```<code>+ findAllStuffForGuestRole()
+ findAllStuffForAdminRole()
</code>```

Each time I need to add a query, I MUST create different queries.

答: This is actually very straight forward with Symfony/Doctrine. Here's a great page in the official docs that explains it better than I could: http://symfony.com/doc/current/doctrine/repository.html</p>

Body:
I've a project with a huge amount of data. I need to make query based on user role/group/permission. This means that a query like

$fooRepository = $this->getDoctrine()
    ->getManager()
    ->getRepository(Foo::class)
    ->findAll();

should return different records if done by a ROLE_SUPER_ADMIN or by  ROLE_USER. Also, I need to filter record based on relations and so on.

I've different solution in mind:

inject user role inside the repository's query

create a role based repository

create a query for each role

Inject user role in repository's query

In this case each repository should be responsible to provide right data. This is a solution similar to this. In that solution record are filtered by tenant.

Create role based repository

In this case I'll need to create different repositories and instantiate them differently. But I don think this can be easy in doctrine? while I am writing, ... I am thinking this is an exaggerated solution.

Create queries for each roles

At the moment I think this is the more natural way to do queries. I just imagine that a repository should contain

+ findAllStuffForGuestRole()
+ findAllStuffForAdminRole()

Each time I need to add a query, I MUST create different queries.


问:
How do I intercept spring boot bean loading at startup?
I have a javafx application that uses spring boot. I want to display the beans being loaded at a splash screen.

How do I intercept the bean loading so I can get it's name?

I was previously pointed that it was already answered here:
Print all the Spring beans that are loaded

But I want to know which bean is being loaded, not the beans that are already loaded.

答:
You can use a BeanPostProcessor for this. It will be notified of any bean before and after initialisation:

```<code>public class PrintingBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before init: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After init: " + beanName);
        return bean;
    }

}
</code>```

To register it, in my configuration class I simply do:

```<code>  @Bean
    public BeanPostProcessor postProcessor() {
        return new PrintingBeanPostProcessor();
    }
</code>```

This then prints on startup:

```<code>Before init: resourceHandlerMapping
After init: resourceHandlerMapping
Before init: defaultServletHandlerMapping
After init: defaultServletHandlerMapping
Before init: mvcUriComponentsContributor
After init: mvcUriComponentsContributor
Before init: httpRequestHandlerAdapter
After init: httpRequestHandlerAdapter
</code>```

(this is obviously just a fraction of what it prints)

Hope that helps,

Artur

Body:
You can use a BeanPostProcessor for this. It will be notified of any bean before and after initialisation:

public class PrintingBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before init: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After init: " + beanName);
        return bean;
    }

}

To register it, in my configuration class I simply do:

  @Bean
    public BeanPostProcessor postProcessor() {
        return new PrintingBeanPostProcessor();
    }

This then prints on startup:

Before init: resourceHandlerMapping
After init: resourceHandlerMapping
Before init: defaultServletHandlerMapping
After init: defaultServletHandlerMapping
Before init: mvcUriComponentsContributor
After init: mvcUriComponentsContributor
Before init: httpRequestHandlerAdapter
After init: httpRequestHandlerAdapter

(this is obviously just a fraction of what it prints)

Hope that helps,

Artur


问:
Hibernate 5.0.12 Wrong column definition escape with Mysql 5.7
I'm using Hibernate + Spring JPA and Mysql 5.7 as DBMS. I want to use some reserved keywords as column name and for that I eanbled:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

Some columns have a custom definition like:

```<code>@CreatedDate
    @Column(updatable = false, columnDefinition = "DATETIME(6)")
    private LocalDateTime createdDate;
</code>```

Unfortunately Hibernate translate this as:

```<code>`created_date` `DATETIME(6)`
</code>```

instead of

```<code>`created_date` DATETIME(6)
</code>```

I opened an issue on Hibernate JIRA (JIRA); I was wondering if there is a workaround to use meanwhile.

答:
I found the right solution thanks to Hibernate people:

To avoid that column definition is quoted there is a specific setting:

```<code>spring.jpa.properties.hibernate.globally_quoted_identifiers_skip_column_definitions=true
</code>```

Unfortunately, right now, it works backwards (see this bug): so if you want to skip column definition you have to set it to false.

Body:
I'm using Hibernate + Spring JPA and Mysql 5.7 as DBMS. I want to use some reserved keywords as column name and for that I eanbled:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

Some columns have a custom definition like:

@CreatedDate
    @Column(updatable = false, columnDefinition = "DATETIME(6)")
    private LocalDateTime createdDate;

Unfortunately Hibernate translate this as:

`created_date` `DATETIME(6)`

instead of

`created_date` DATETIME(6)

I opened an issue on Hibernate JIRA (JIRA); I was wondering if there is a workaround to use meanwhile.

Body:
I found the right solution thanks to Hibernate people:

To avoid that column definition is quoted there is a specific setting:

spring.jpa.properties.hibernate.globally_quoted_identifiers_skip_column_definitions=true

Unfortunately, right now, it works backwards (see this bug): so if you want to skip column definition you have to set it to false.


问:
Excel download is not working in MEAN stack app
I want to download the excel file when i click the button.

When i click the download button, I want to create a Excel file with dynamic data from data base and download it (Note: Don't want to create and store the excel file into physical path and then download it).

Html Code

```<code><button ng-click="exportData()" class="btn btn-sm btn-primary btn-create">Download</button>
</code>```

Controller Code

```<code> $scope.exportData = function () {
     $http.get('/Getexcel').then(function (response) {
     });
 };
</code>```

Server code

```<code> const ExcelConfig = require('./public/Models/Schema/excel');
    app.get('/Getexcel', ExcelConfig.getexceldata);
</code>```

note :
  ExcelConfig contain path of schema code

excel.js code

```<code>// Require library
var xl = require('excel4node');
const tempfile = require('tempfile');

// Create a new instance of a Workbook class
var wb = new xl.Workbook();

// Add Worksheets to the workbook
var ws = wb.addWorksheet('MaterialFlowSheet');
// Create a reusable style
var style = wb.createStyle({
    font: {
        color: '#FF0800',
        size: 12
    },
    numberFormat: '$#,##0.00; ($#,##0.00); -'
});

exports.getexceldata = (req, res) => {
    ws.cell(1, 1).string('BatchId').style(style);
    ws.cell(1, 2).string('Source').style(style);
    ws.column(2).setWidth(50);
    ws.row(1).setHeight(20);
    ws.cell(1, 3).string('Destination').style(style);
    ws.column(3).setWidth(50);
    ws.row(1).setHeight(20);
    ws.cell(1, 4).string('DistanceBetweenTwoBuilding').style(style);
    ws.column(4).setWidth(25);
    ws.row(1).setHeight(20);
    ws.cell(1, 5).string('SKU').style(style);
    ws.cell(1, 6).string('UOM').style(style);
    ws.cell(1, 7).string('QtyToBeDelivered').style(style);
    ws.column(7).setWidth(20);
    ws.row(1).setHeight(20);
    ws.cell(1, 8).string('CartType').style(style);
wb.write('Excel.xlsx');
res.download('\Excel.xlsx');
};
</code>```

I have tried with above sample file download. So when I click the Download button, the file is not downloading instead nothing happened in UI. But I'm Getting downloaded If I access this URL http://localhost:8080/Getexcel.
Can anyone give the solution to download the excel file by clicking the Download button?

答:
You must send response as file</p>

```<code>app.get('/spreadsheet', function(req, res, next) {
  res.setHeader('Content-disposition', `attachment;filename=data.xls`);
  res.setHeader('Content-type', 'application/vnd.ms-excel');
  res.charset = 'UTF-8';
  res.status(200).end(xls);
});
</code>```

Body:
I want to download the excel file when i click the button.

When i click the download button, I want to create a Excel file with dynamic data from data base and download it (Note: Don't want to create and store the excel file into physical path and then download it).

Html Code

<button ng-click="exportData()" class="btn btn-sm btn-primary btn-create">Download</button>

Controller Code

 $scope.exportData = function () {
     $http.get('/Getexcel').then(function (response) {
     });
 };

Server code

 const ExcelConfig = require('./public/Models/Schema/excel');
    app.get('/Getexcel', ExcelConfig.getexceldata);

note :
  ExcelConfig contain path of schema code

excel.js code

// Require library
var xl = require('excel4node');
const tempfile = require('tempfile');

// Create a new instance of a Workbook class
var wb = new xl.Workbook();

// Add Worksheets to the workbook
var ws = wb.addWorksheet('MaterialFlowSheet');
// Create a reusable style
var style = wb.createStyle({
    font: {
        color: '#FF0800',
        size: 12
    },
    numberFormat: '$#,##0.00; ($#,##0.00); -'
});

exports.getexceldata = (req, res) => {
    ws.cell(1, 1).string('BatchId').style(style);
    ws.cell(1, 2).string('Source').style(style);
    ws.column(2).setWidth(50);
    ws.row(1).setHeight(20);
    ws.cell(1, 3).string('Destination').style(style);
    ws.column(3).setWidth(50);
    ws.row(1).setHeight(20);
    ws.cell(1, 4).string('DistanceBetweenTwoBuilding').style(style);
    ws.column(4).setWidth(25);
    ws.row(1).setHeight(20);
    ws.cell(1, 5).string('SKU').style(style);
    ws.cell(1, 6).string('UOM').style(style);
    ws.cell(1, 7).string('QtyToBeDelivered').style(style);
    ws.column(7).setWidth(20);
    ws.row(1).setHeight(20);
    ws.cell(1, 8).string('CartType').style(style);
wb.write('Excel.xlsx');
res.download('\Excel.xlsx');
};

I have tried with above sample file download. So when I click the Download button, the file is not downloading instead nothing happened in UI. But I'm Getting downloaded If I access this URL http://localhost:8080/Getexcel.
Can anyone give the solution to download the excel file by clicking the Download button?

Body:
You must send response as file

app.get('/spreadsheet', function(req, res, next) {
  res.setHeader('Content-disposition', `attachment;filename=data.xls`);
  res.setHeader('Content-type', 'application/vnd.ms-excel');
  res.charset = 'UTF-8';
  res.status(200).end(xls);
});