问:
JSP java code + html table
I have encountered a problem that I don't really understand. I'm using java code to access a database and then using the jsp part, display in html format the result.
The code looks like this:

```<code>out.println("<html><body>");

out.println("<form method=\"GET\" action=\"http://localhost:1234/WebLabJSP/delete\">");

out.println("<table>");

out.println("<tr><th>Name</th><th>Quantity</th><th>Category</th></tr>");

ResultSet rs = s.executeQuery("select * from Products");

while(rs.next()){

out.println("<tr><td>" + rs.getString(2) + "</td><td>" + rs.getString(3) + "</td><td>" + rs.getString(4) + "</td><td><input type=\"submit\" value=\"Delete\" name=\"delete" + rs.getString(1) + "\"/></td><td><input type=\"submit\" value=\"Update\" name=\"update" + rs.getString(1) + "\"/></td></tr>");

   }

out.println("</table></form>");

out.println("</body></html>");
</code>```

The problem is, that if I have only the delete button in the form, it works perfectly, but when I added the second button, the page didn't display anything at all.
If anyone knows what's going on, please help.

答: Don't use connection process and other updating process in jsp page, try to use servlets or other javabeans.  tag to use that servlets... if u want to update means simply cal that function, declared inside that servlet. servlet s act as a controller of ur jsp page.its more powerful.</p>

Title: JSP java code + html table

Body:
I have encountered a problem that I don't really understand. I'm using java code to access a database and then using the jsp part, display in html format the result.
The code looks like this:

out.println("");

out.println("<form method=\"GET\" action=\"http://localhost:1234/WebLabJSP/delete\">");

out.println("
");

out.println("
Name	Quantity	Category
");

ResultSet rs = s.executeQuery("select * from Products");

while(rs.next()){

out.println("
" + rs.getString(2) + "	" + rs.getString(3) + "	" + rs.getString(4) + "	<input type=\"submit\" value=\"Delete\" name=\"delete" + rs.getString(1) + "\"/>	<input type=\"submit\" value=\"Update\" name=\"update" + rs.getString(1) + "\"/>
");

   }

out.println("
</form>");

out.println("");

The problem is, that if I have only the delete button in the form, it works perfectly, but when I added the second button, the page didn't display anything at all.
If anyone knows what's going on, please help.


来源: stackexchange

问:
How to check process have running in python (in linux)?
I am trying to check if the process is running based on process name (test.py) ,  then exit

```<code>l = commands.getstatusoutput("ps aux |grep 'python2.7'| grep
'test.py' | grep -v 'grep' | wc -l")

if int(l[1]) == 1:
    pid = commands.getstatusoutput("ps -ef |grep 'python2.7'|  grep 'test.py ' |awk '{print $2}'")
    print "the process 'test.py ' have running ,the pid is :"+str(pid[1])
    sys.exit(0)

else:
   print "not running"
</code>```

Output:

```<code>georgetovrea@dev:/test$ python2.7  test.py
the process 'test.py ' have running ,the pid is :26517
26542
</code>```

then I try to check

```<code> $ ps aux | grep agg_test
 georgetovrea 25181  0.0  0.0  10944   932 pts/9    S+   23:26   0:00 grep --color=auto test
</code>```

the process is not running, I want to check if the process( test.py) have running ,then exit ,
but it's always print the process is running ,

How do I check the process have running ?  Any suggestions? Thanks for any help.

答:
The program runs fine for me.
I guess you are running the program with python instead of python2.7 specifically.

(a) Try using python instead of python2.7 in your grep statement,then the culprit is indeed your usage of python.

(b) Change it back to python2.7 and run your program with full path to python2.7

The program:

```<code>import commands
import sys

l = commands.getstatusoutput("ps aux |grep 'python2.7'| grep 'test.py' | grep -v 'grep' | wc -l")

print(l)
if int(l[1]) == 1:
    pid = commands.getstatusoutput("ps -ef |grep 'python2.7'|  grep 'test.py ' |awk '{print $2}'")
    print "the process 'test.py ' have running ,the pid is :"+str(pid[1])
    sys.exit(0)

else:
   print "not running"
</code>```

Output:

```<code>dhruv@dhruvpathak:/tmp$ /usr/bin/python2.7  test.py

(0, '1')

the process 'test.py ' have running ,the pid is :15620
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to check if the process is running based on process name (test.py) ,  then exit

l = commands.getstatusoutput("ps aux |grep 'python2.7'| grep
'test.py' | grep -v 'grep' | wc -l")

if int(l[1]) == 1:
    pid = commands.getstatusoutput("ps -ef |grep 'python2.7'|  grep 'test.py ' |awk '{print $2}'")
    print "the process 'test.py ' have running ,the pid is :"+str(pid[1])
    sys.exit(0)

else:
   print "not running"

Output:

georgetovrea@dev:/test$ python2.7  test.py
the process 'test.py ' have running ,the pid is :26517
26542

then I try to check

 $ ps aux | grep agg_test
 georgetovrea 25181  0.0  0.0  10944   932 pts/9    S+   23:26   0:00 grep --color=auto test

the process is not running, I want to check if the process( test.py) have running ,then exit ,
but it's always print the process is running ,

How do I check the process have running ?  Any suggestions? Thanks for any help.

Body:
The program runs fine for me.
I guess you are running the program with python instead of python2.7 specifically.

(a) Try using python instead of python2.7 in your grep statement,then the culprit is indeed your usage of python.

(b) Change it back to python2.7 and run your program with full path to python2.7

The program:

import commands
import sys

l = commands.getstatusoutput("ps aux |grep 'python2.7'| grep 'test.py' | grep -v 'grep' | wc -l")

print(l)
if int(l[1]) == 1:
    pid = commands.getstatusoutput("ps -ef |grep 'python2.7'|  grep 'test.py ' |awk '{print $2}'")
    print "the process 'test.py ' have running ,the pid is :"+str(pid[1])
    sys.exit(0)

else:
   print "not running"

Output:

dhruv@dhruvpathak:/tmp$ /usr/bin/python2.7  test.py

(0, '1')

the process 'test.py ' have running ,the pid is :15620


问:
Multi-line antd alert description
Is there a way to have a multi-line alert description that also includes HTML (ie  tags)

It seems that the description is escaped, so any markup or \n is rendered literally, eg https://codepen.io/anon/pen/awzNzP?editors=001.

答:
Ok, I figured it out.  I failed to notice that the description property can be a ReactNode, so you can do this

```<code>descriptionElement = (
  <code>
    Line 1
    <br />
    Line 2
  </code>
)
<Alert message='test' type='info' description={descriptionElement} />
</code>```

Running version

Title: Multi-line antd alert description

Body:
Ok, I figured it out.  I failed to notice that the description property can be a ReactNode, so you can do this

descriptionElement = (
  <code>
    Line 1
    <br />
    Line 2
  </code>
)
<Alert message='test' type='info' description={descriptionElement} />

Running version


问:
ManageIQ refreshing not working (error "Not allowing worker")
I made the openshift monitoring instance with ManageIQ. The connection to openshift is succeeded.

But refreshing the openshift monitoring does not work. The openshift variables show nothing on the dash board. These are the evm.log of ManageIQ logs.

```<code> ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [ManageIQ::Providers::Openshift::ContainerManager::RefreshWorker] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:47.397906 #211:2b001244513c]  INFO -- : MIQ(ManageIQ::Providers::Openshift::ContainerManager::EventCatcher.sync_workers) Workers are being synchronized: Current: [], Desired: ["ems_2"]
[----] E, [2017-05-27T06:15:47.398280 #211:2b001244513c] ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [ManageIQ::Providers::Openshift::ContainerManager::EventCatcher] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:47.415801 #211:2b001244513c]  INFO -- : MIQ(MiqGenericWorker.sync_workers) Workers are being synchronized: Current #: [1], Desired #: [2]
[----] E, [2017-05-27T06:15:47.416125 #211:2b001244513c] ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [MiqGenericWorker] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:47.420465 #211:2b001244513c]  INFO -- : MIQ(MiqReportingWorker.sync_workers) Workers are being synchronized: Current #: [0], Desired #: [2]
[----] E, [2017-05-27T06:15:47.420838 #211:2b001244513c] ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [MiqReportingWorker] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:49.532827 #479:2b001244513c]  INFO -- : MIQ(MiqScheduleWorker::Runner#do_work) Number of scheduled items to be processed: 1.
[----] I, [2017-05-27T06:15:49.546516 #479:2b001244513c]  INFO -- : MIQ(MiqQueue.put) Message id: [929],  id: [], Zone: [default], Role: [smartstate], Server: [], Ident: [generic], Target id: [], Instance id: [], Task id: [job_dispatcher], Command: [JobProxyDispatcher.dispatch], Timeout: [600], Priority: [20], State: [ready], Deliver On: [], Data: [], Args: []
</code>```

答:
It seems that worker, which takes care of refreshing, is not starting at all due to the insufficient resources on Manage IQ server. If your swap is more than 60% full (seen from the log) then the services already used all of your RAM.

You can get Basic ManageIQ server requirements for each type of server (Vagrant, Docker, Public cloud) here: http://manageiq.org/docs/get-started

ContentLicense: CC BY-SA 4.0

Body:
I made the openshift monitoring instance with ManageIQ. The connection to openshift is succeeded.

But refreshing the openshift monitoring does not work. The openshift variables show nothing on the dash board. These are the evm.log of ManageIQ logs.

 ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [ManageIQ::Providers::Openshift::ContainerManager::RefreshWorker] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:47.397906 #211:2b001244513c]  INFO -- : MIQ(ManageIQ::Providers::Openshift::ContainerManager::EventCatcher.sync_workers) Workers are being synchronized: Current: [], Desired: ["ems_2"]
[----] E, [2017-05-27T06:15:47.398280 #211:2b001244513c] ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [ManageIQ::Providers::Openshift::ContainerManager::EventCatcher] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:47.415801 #211:2b001244513c]  INFO -- : MIQ(MiqGenericWorker.sync_workers) Workers are being synchronized: Current #: [1], Desired #: [2]
[----] E, [2017-05-27T06:15:47.416125 #211:2b001244513c] ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [MiqGenericWorker] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:47.420465 #211:2b001244513c]  INFO -- : MIQ(MiqReportingWorker.sync_workers) Workers are being synchronized: Current #: [0], Desired #: [2]
[----] E, [2017-05-27T06:15:47.420838 #211:2b001244513c] ERROR -- : MIQ(MiqServer#start_algorithm_used_swap_percent_lt_value) Not allowing worker [MiqReportingWorker] to start since system memory usage has exceeded 60% of swap: Total: [1073737728], Used: [846049280]
[----] I, [2017-05-27T06:15:49.532827 #479:2b001244513c]  INFO -- : MIQ(MiqScheduleWorker::Runner#do_work) Number of scheduled items to be processed: 1.
[----] I, [2017-05-27T06:15:49.546516 #479:2b001244513c]  INFO -- : MIQ(MiqQueue.put) Message id: [929],  id: [], Zone: [default], Role: [smartstate], Server: [], Ident: [generic], Target id: [], Instance id: [], Task id: [job_dispatcher], Command: [JobProxyDispatcher.dispatch], Timeout: [600], Priority: [20], State: [ready], Deliver On: [], Data: [], Args: []


问:
How to extract all unique values from a column based on multiple criterion in Excel
I am trying to get a list of all the distinct values from a column based on a vlookup type match.

For example:

Sheet 1:

```<code>      (colA)         (colB)   (colC)
Health System Name    EMR     PMR

System A
System B
System C
System D
</code>```

Sheet 2 (where all the data is)

```<code>Healthy System Name        Tech ID      Vendor

System A                 PMR         ClinicA
System A                 EMR         ClinicE
System A                 EMR         ClinicA
System B                 EMR         ClinicB
System B                 PMR         ClinicC
System C                 PMR         ClinicA
System C                 PMR         ClinicB
System C                 EMR         ClinicD
System C                 PMR         ClinicD
System C                 EMR         ClinicG
</code>```

I want to be able to search the name of the healthy system from colA in sheet 1 in colA of Sheet 2...and based on whether it is a PMR or EMR...return the number of unique values from the Vendor column into one cell in sheet 1 under the appropriate column.

SO under the EMR column in Sheet 1 for System A, I want the distinct values from the vendor column in sheet 2 that have the tech ID as "EMR"for System A.

In this case it would be : ClinicA, ClinicE

Any help would be greatly appreciated!

答:
You would not be able to do this only with excel formulas and you would need a VBA solution. If your Sheet1 contains data like below,

and Sheet2,

Try this simple VBA code ,

```<code>Sub uniqueList()
Dim i As Long, j As Long, str As String
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    For j = 2 To Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
        If Cells(i, 1) = Sheets("Sheet2").Cells(j, 1) And Cells(1, 2) = Sheets("Sheet2").Cells(j, 2) Then
            If Cells(i, 2) <> "" Then
                str = Cells(i, 2) & " , " & Sheets("Sheet2").Cells(j, 3)
                Cells(i, 2) = str
            Else
                Cells(i, 2) = Sheets("Sheet2").Cells(j, 3)
            End If
        End If
        If Cells(i, 1) = Sheets("Sheet2").Cells(j, 1) And Cells(1, 3) = Sheets("Sheet2").Cells(j, 2) Then
            If Cells(i, 3) <> "" Then
                str = Cells(i, 3) & " , " & Sheets("Sheet2").Cells(j, 3)
                Cells(i, 3) = str
            Else
                Cells(i, 3) = Sheets("Sheet2").Cells(j, 3)
            End If
        End If
    Next j
Next i
End Sub
</code>```

Your output would be,

Body:
I am trying to get a list of all the distinct values from a column based on a vlookup type match.

For example:

Sheet 1:

      (colA)         (colB)   (colC)
Health System Name    EMR     PMR

System A
System B
System C
System D

Sheet 2 (where all the data is)

Healthy System Name        Tech ID      Vendor

System A                 PMR         ClinicA
System A                 EMR         ClinicE
System A                 EMR         ClinicA
System B                 EMR         ClinicB
System B                 PMR         ClinicC
System C                 PMR         ClinicA
System C                 PMR         ClinicB
System C                 EMR         ClinicD
System C                 PMR         ClinicD
System C                 EMR         ClinicG

I want to be able to search the name of the healthy system from colA in sheet 1 in colA of Sheet 2...and based on whether it is a PMR or EMR...return the number of unique values from the Vendor column into one cell in sheet 1 under the appropriate column.

SO under the EMR column in Sheet 1 for System A, I want the distinct values from the vendor column in sheet 2 that have the tech ID as "EMR"for System A.

In this case it would be : ClinicA, ClinicE

Any help would be greatly appreciated!

Body:
You would not be able to do this only with excel formulas and you would need a VBA solution. If your Sheet1 contains data like below,

and Sheet2,

Try this simple VBA code ,

Sub uniqueList()
Dim i As Long, j As Long, str As String
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
    For j = 2 To Sheets("Sheet2").Cells(Rows.Count, 1).End(xlUp).Row
        If Cells(i, 1) = Sheets("Sheet2").Cells(j, 1) And Cells(1, 2) = Sheets("Sheet2").Cells(j, 2) Then
            If Cells(i, 2) <> "" Then
                str = Cells(i, 2) & " , " & Sheets("Sheet2").Cells(j, 3)
                Cells(i, 2) = str
            Else
                Cells(i, 2) = Sheets("Sheet2").Cells(j, 3)
            End If
        End If
        If Cells(i, 1) = Sheets("Sheet2").Cells(j, 1) And Cells(1, 3) = Sheets("Sheet2").Cells(j, 2) Then
            If Cells(i, 3) <> "" Then
                str = Cells(i, 3) & " , " & Sheets("Sheet2").Cells(j, 3)
                Cells(i, 3) = str
            Else
                Cells(i, 3) = Sheets("Sheet2").Cells(j, 3)
            End If
        End If
    Next j
Next i
End Sub

Your output would be,


问:
java mail - use dynamic sender email address
I am using email services (with my custom domain) from google. I want to use dynamic sender email address i.e. When user registers he should receive email from register@example.com and when he place order, should receive email from orders@example.com

I have used java mail to send emails and application is developed using spring framework. Emails are sent, only issue they are always received from username specified in spring configuration xml.

Spring configuration:

```<code><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="username" />
    <property name="password" value="password" />

    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(order.getCustomer().getEmailAddress()));
                mimeMessage.setFrom(new InternetAddress("mail@mycompany.com"));
                mimeMessage.setText(
                        "Dear " + order.getCustomer().getFirstName() + " "
                            + order.getCustomer().getLastName()
                            + ", thank you for placing order. Your order number is "
                            + order.getOrderNumber());
            }
        };
</code>```

Any idea, where I am going wrong ?

答: Have you followed the Gmail instructions for sending from a different email address?</p>

Body:
I am using email services (with my custom domain) from google. I want to use dynamic sender email address i.e. When user registers he should receive email from register@example.com and when he place order, should receive email from orders@example.com

I have used java mail to send emails and application is developed using spring framework. Emails are sent, only issue they are always received from username specified in spring configuration xml.

Spring configuration:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="username" />
    <property name="password" value="password" />

    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(order.getCustomer().getEmailAddress()));
                mimeMessage.setFrom(new InternetAddress("mail@mycompany.com"));
                mimeMessage.setText(
                        "Dear " + order.getCustomer().getFirstName() + " "
                            + order.getCustomer().getLastName()
                            + ", thank you for placing order. Your order number is "
                            + order.getOrderNumber());
            }
        };

Any idea, where I am going wrong ?


问:
HTML form button not deleting rows from sqlite database
I have built a forum in pythonanywhere using python and html, in which users can post information that gets inserted into a sqlite database. At the bottom of each post is a delete button that will delete the post that it's under from the database and refresh the page. Right now the delete button only refreshes the page while the post remains. I am wondering how to edit the code so that the post which the form button is attached to is deleted and the page is refreshed.

HTML Code snippet

```<code>{% for post in forumposts %}
<tr>
    <td>
    <h1>{{post[1]}}</h1>
    <h3>{{post[3]}}</h3>
    <p>{{post[2]}}</p>
    <p>{{post[6]}}</p>
    <img src="{{post[7]}}" alt="Wrong image link.">
    <p></p>
    <form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
    <input type=hidden value="{{ postid }}"name=post_to_delete></input>
    <input type=submit></input>
    </form>
    </td>
</tr>
    {%endfor%}
</table>
</code>```

Python Code snippet

```<code>@app.route('/delete', methods=['POST'])
def delete_post():
    db = connect_db()
    db.execute('DELETE FROM posts WHERE postid = ?', [request.form['post_to_delete']])
    db.commit()
    db.close()
    return redirect(url_for('forum'))
</code>```

答:
Got the code working.

HTML

```<code>{% for post in forumposts %}
<tr>
    <td>
    <h1>{{post[1]}}</h1>
    <h3>{{post[3]}}</h3>
    <p>{{post[2]}}</p>
    <p>{{post[6]}}</p>
    <img src="{{post[7]}}" alt="Wrong image link.">
    <p></p>
    <form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
    <input type=hidden value={{post[0]}} name=post_to_delete></input>
    <input type=submit value=POST></input>
    </form>
    </td>
</tr>
    {%endfor%}
</table>
</code>```

PYTHON

```<code>@app.route('/delete', methods=['POST'])
def delete_post():
    if request.method == 'POST':
        db = connect_db()
        db.execute('DELETE FROM posts WHERE postid = ?', (request.form['post_to_delete'],))
        db.commit()
        db.close()
        return redirect(url_for('forum'))
</code>```

Hope this helps someone. :)

Body:
I have built a forum in pythonanywhere using python and html, in which users can post information that gets inserted into a sqlite database. At the bottom of each post is a delete button that will delete the post that it's under from the database and refresh the page. Right now the delete button only refreshes the page while the post remains. I am wondering how to edit the code so that the post which the form button is attached to is deleted and the page is refreshed.

HTML Code snippet

{% for post in forumposts %}

{{post[1]}}

{{post[3]}}

{{post[2]}}

{{post[6]}}

    <form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
    <input type=hidden value="{{ postid }}"name=post_to_delete></input>
    <input type=submit></input>
    </form>

    {%endfor%}

Python Code snippet

@app.route('/delete', methods=['POST'])
def delete_post():
    db = connect_db()
    db.execute('DELETE FROM posts WHERE postid = ?', [request.form['post_to_delete']])
    db.commit()
    db.close()
    return redirect(url_for('forum'))

Body:
Got the code working.

HTML

{% for post in forumposts %}
<tr>
    <td>
    <h1>{{post[1]}}</h1>
    <h3>{{post[3]}}</h3>
    <p>{{post[2]}}</p>
    <p>{{post[6]}}</p>
    <img src="{{post[7]}}" alt="Wrong image link.">
    <p></p>
    <form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
    <input type=hidden value={{post[0]}} name=post_to_delete></input>
    <input type=submit value=POST></input>
    </form>
    </td>
</tr>
    {%endfor%}
</table>

PYTHON

@app.route('/delete', methods=['POST'])
def delete_post():
    if request.method == 'POST':
        db = connect_db()
        db.execute('DELETE FROM posts WHERE postid = ?', (request.form['post_to_delete'],))
        db.commit()
        db.close()
        return redirect(url_for('forum'))

Hope this helps someone. :)


问:
Should Context be injected with Dagger?
I know it is possible to inject Context with Dagger. We can see examples here and here.

On the other end, there are numerous posts about not placing context on a static variable to avoid leaks.
Android Studio (lint) also warms about this:

Do not place Android context classes in static fields; this is a
  memory leak (and also breaks Instant Run)

I understand that by injecting a Context with Dagger, we are placing it on a singleton class, so context is somehow static. Doesn't this go against the lint warning?

Injecting the context seems to create cleaner code, since you don't have to pass it to several classes (that don't need it) so that they can further pass it to other classes that need it for some reason (getting a resource for instance).

I am just concerned that this may cause some undesired leak or breaks lint in some way.

答:
If you are aware of Android lifecycles and are careful to distinguish the Application Context and the Context of Activities and Services then there is no fault injecting the Context using Dagger 2.

If you are worried about the possibility of a memory leak you can use assertions to prevent injection of the wrong Context:

```<code>public class MyActivityHelper {
     private final Context context;

     @Inject
     public MyActivityHelper (Context context) {
         if (context instanceof Application) {
              throw new IllegalArgumentExecption("MyActivityHelper requires an Activity context");
         }
     }
}
</code>```

Alternatively you could use Dagger 2 Qualifiers to distinguish the two so you don't accidentally inject an app Context where an Activity Context is required. Then your constructor would look something like this:

```<code>@Inject
public class MyActivityHelper (@Named("activity") Context context) {
</code>```

Note also, as per David's comment, a Dagger 2 @Singelton is not necessarily a static reference.

Title: Should Context be injected with Dagger?

Body:
If you are aware of Android lifecycles and are careful to distinguish the Application Context and the Context of Activities and Services then there is no fault injecting the Context using Dagger 2.

If you are worried about the possibility of a memory leak you can use assertions to prevent injection of the wrong Context:

public class MyActivityHelper {
     private final Context context;

     @Inject
     public MyActivityHelper (Context context) {
         if (context instanceof Application) {
              throw new IllegalArgumentExecption("MyActivityHelper requires an Activity context");
         }
     }
}

Alternatively you could use Dagger 2 Qualifiers to distinguish the two so you don't accidentally inject an app Context where an Activity Context is required. Then your constructor would look something like this:

@Inject
public class MyActivityHelper (@Named("activity") Context context) {

Note also, as per David's comment, a Dagger 2 @Singelton is not necessarily a static reference.


问:
Specifying default value for django hidden form field - bone DRY?
So let's say at the last minute (in the view) I decide I want to specify a default for a field and make it hidden, like so:

```<code>form.fields['coconut'] = forms.ModelChoiceField(
    label="",
    widget=forms.HiddenInput(),
    queryset=swallow.coconuts.all(),
    initial=some_particular_coconut,
)
</code>```

My question is this:  Do I really need to specify queryset here?  I mean, I already know, from initial, exactly which coconut I'm talking about.  Why do I also need to specify that the universe of available coconuts is the set of coconuts which this particular swallow carried (by the husk)?

Is there a way I can refrain from specifying queryset?  Simply omitting causes django to raise TypeError.

If indeed it is required, isn't this a bit damp?

答:
The problem is that you're trying to set up a hidden ModelChoiceField. In order to have a Choice (dropdown, traditionally) it needs to know its Choices - this is why you give a queryset.

But you're not trying to give the user a choice, right? It's a hidden input, and you're setting it from the server (so it gets POSTed back, presumably).

My suggestion is to try to find a way around using the hidden input at all. I find them a bit hacky. But otherwise, why not just specify a text field with some_particular_coconut.id, and hide that? The model's only wrapping that id anyway.

Body:
So let's say at the last minute (in the view) I decide I want to specify a default for a field and make it hidden, like so:

form.fields['coconut'] = forms.ModelChoiceField(
    label="",
    widget=forms.HiddenInput(),
    queryset=swallow.coconuts.all(),
    initial=some_particular_coconut,
)

My question is this:  Do I really need to specify queryset here?  I mean, I already know, from initial, exactly which coconut I'm talking about.  Why do I also need to specify that the universe of available coconuts is the set of coconuts which this particular swallow carried (by the husk)?

Is there a way I can refrain from specifying queryset?  Simply omitting causes django to raise TypeError.

If indeed it is required, isn't this a bit damp?

ContentLicense: CC BY-SA 2.5


问:
Installing same application with different names
How can I install the sample application with different names on Android device ?

I have developed one application. I want to install two instances of the same application, one with real data and another one with dummy data.

How can I do this?

[solution]

I followed below steps for my dummy applicaiton:

project -> Android tools -> Rename Application package.

Now both instances are running fine.

答: If you use Android Studio browse the project to Gradle Scripts>build.gradle(Module:app) and change applicationId.


问:
Python: for loop iteration accumulate values in string variable
Say I have a for loop that iterates through the characters in a string one by one.

Ex:

```<code>string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
</code>```

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'.
I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration.
Any ideas?

答:
Not pretty clear question, but I'll give it a try.

Since you didn't mention it, I'll just presume that you got something like a scrambled list like scrambled_list = ['c', 'a', 'b'].

I guess you're asking for something like ''.join(scrambled_list), which will give you 'cab'.

```<code>scrambled_list = ['c', 'a', 'b']
sep = ''
output = sep.join(scrambled_list)

print(output)
'cab'
</code>```

the join() method of string returns a string concatenate by the seperater, so

'-'.join(scrambled_list) will gives you 'c-a-b'.

Body:
Say I have a for loop that iterates through the characters in a string one by one.

Ex:

string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'.
I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration.
Any ideas?

Body:
Not pretty clear question, but I'll give it a try.

Since you didn't mention it, I'll just presume that you got something like a scrambled list like scrambled_list = ['c', 'a', 'b'].

I guess you're asking for something like ''.join(scrambled_list), which will give you 'cab'.

scrambled_list = ['c', 'a', 'b']
sep = ''
output = sep.join(scrambled_list)

print(output)
'cab'

the join() method of string returns a string concatenate by the seperater, so

'-'.join(scrambled_list) will gives you 'c-a-b'.


问:
not able to accees inner properties of event inside directive?
i have a directive with on click method

```<code>  @Directive({
selector: '[clickOutside]'
   })
 export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) {
}

@Output()
public clickOutside = new EventEmitter<MouseEvent>();

@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {

    if (!targetElement) {
        return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {

        console.log(event)
       console.log(event.path) =>gives error,not able to compile

        console.log("targetelement",targetElement)
        console.log("native element",this._elementRef.nativeElement)
        this.clickOutside.emit(event);
    }
}
}
</code>```

I WANT TO ACCESS THE PATH PROPERTY OF event. when i console.log(event) its getting and i can see the path property, but when i tried to access event.path
i am getting compilation error, why it is so? how can i access the current click event and its inner properties inside the onClick method?

答:
There is no pathproperty listed in the documentation for MouseEvent, nor in the documentation of its superclasses. And as you discovered, there is no such path property in the TypeScript definition of MouseEvent either.

So you want to use a property that exists at runtime, in your browser, but that is not documented, and thus probably not standard, and thus probably non-existent in other browsers. You're free to do so, but you should be aware of the risks. Just use event['path'] instead of event.path.

Body:
i have a directive with on click method

  @Directive({
selector: '[clickOutside]'
   })
 export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) {
}

@Output()
public clickOutside = new EventEmitter<MouseEvent>();

@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {

    if (!targetElement) {
        return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {

        console.log(event)
       console.log(event.path) =>gives error,not able to compile

        console.log("targetelement",targetElement)
        console.log("native element",this._elementRef.nativeElement)
        this.clickOutside.emit(event);
    }
}
}

I WANT TO ACCESS THE PATH PROPERTY OF event. when i console.log(event) its getting and i can see the path property, but when i tried to access event.path
i am getting compilation error, why it is so? how can i access the current click event and its inner properties inside the onClick method?


问:
openWRT: admin control programmatically
I can login to openWRT router admin portal to configure everything. However, if I want to control the openWRT device programmatically, i.e. sending the command through a socket connection between the openWRT device and the server, any module to recommend?

add a user/password who can login to openWRT wifi network.

QoS which can limit the bandwidth usage of a user; calculate the data
usage for a user

Security, create firewalls between different users on openWRT device.

答:
You can use Luci for the local connection.

If you want to create a program in Python or C/C++, I would suggest using libcurl library or module.

Title: openWRT: admin control programmatically


问:
Get environment variable defined in Linux bash to webpack
I have checked out tons of SO questions about "environment variables in webpack" using e.g. the DefinePlugin:

```<code>new webpack.DefinePlugin({'ENV': JSON.stringify('staging')})
</code>```

but I cannot for the life of me find a way to inject an environment variable defined in the linux bash shell, instead of using the hard coded staging string

In my production and staging environements I have variables such as $ENV and $API_KEY defined, and I want to use their values in my webpack / ReactJs code.

Edit

I notice, if I run the a webpack command from cli:

```<code> $ ENVIRONMENT=staging
 $ node_modules/.bin/webpack -p
</code>```

And in my webpack.config.js file defines

```<code> new webpack.DefinePlugin({'ENV': JSON.stringify(process.env.ENVIRONMENT)})
</code>```

This does not work (ENV is undefined in my JS code),

However, if I run it on the same line, it seems to work - ENVIRONMENT seems to be available in the webpack.config.js file:

```<code>$ ENVIRONMENT=staging node_modules/.bin/webpack -p
</code>```

So I would really like to make this work without having to define the ENVIRONMENT variable on the same line as the webpack command.

答: In nodejs you can get your environment variables via process.env object. In your case you can do process.env.$ENV and process.env.$API_KEY to get $ENV and $API_KEY env vars respectively.

Body:
I have checked out tons of SO questions about "environment variables in webpack" using e.g. the DefinePlugin:

new webpack.DefinePlugin({'ENV': JSON.stringify('staging')})

but I cannot for the life of me find a way to inject an environment variable defined in the linux bash shell, instead of using the hard coded staging string

In my production and staging environements I have variables such as $ENV and $API_KEY defined, and I want to use their values in my webpack / ReactJs code.

Edit

I notice, if I run the a webpack command from cli:

 $ ENVIRONMENT=staging
 $ node_modules/.bin/webpack -p

And in my webpack.config.js file defines

 new webpack.DefinePlugin({'ENV': JSON.stringify(process.env.ENVIRONMENT)})

This does not work (ENV is undefined in my JS code),

However, if I run it on the same line, it seems to work - ENVIRONMENT seems to be available in the webpack.config.js file:

$ ENVIRONMENT=staging node_modules/.bin/webpack -p

So I would really like to make this work without having to define the ENVIRONMENT variable on the same line as the webpack command.


问:
Will conditionals that are always false be removed by compiler in C#
Say I have the following code snippet in c#

```<code>static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}
</code>```

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

答: You can define more symbols other than DEBUG/RELEASE ... just look in the project properties :-) then you can use the preprocessor directive syntax to optionally include things based on the project configuration</p>

OwnerDisplayName: WindyCityEagle

Body:
Say I have the following code snippet in c#

static const bool DO_PERFORMANCE_CODE = false;

if (DO_PERFORMANCE_CODE)
{
   // performance monitoring code goes here
}

Will that code get removed by the compiler? This is the functionality I'd like. Basically I want to mimic the conditional compilation stuff in C#, but I want more configurations other than Release and Debug. If there is a better way of doing this, I'd be open to hearing it.

LastEditorDisplayName: Dana

OwnerDisplayName: Joel Martinez


问:
how can i track users without cookies
ok... im looking to have a good round of brainstorming here...

say i was google... the adword/adsense/analytics division. i would be getting a little worried about the future, when users start to disable cookies (or at least delete them on a regular basis), use private browsing, roam on multiple devices. how could google alternatively track users without the benefits of cookies?

some ideas to get started (please elaborate on these and any others):

-track users using some other persistent local/client side storage

-use user-agent string fingerprinting

-test cache response - if user 304's an image, they were here

-track mac address

-any random/out of the box ideas?

答:
you can always resort back to good ol way, the HIT COUNTER.

on page, use  tag and link to external image on your server

on your server, when image is fetched, redirect it to php script through .htaccess and record header info about device id etc. {similar code as disabling the hotlinking of image}

Now you have all info, use php_session() to keep a track of it

you can always use js for the same purpose, but using  tag will ensure that js is not required and the script will run on all browsers

Title: how can i track users without cookies


问:
Conditions in unix ftp script
I'm trying to write a code that will check a specific date's file and if it exists it'll get it to my local home path and if it doesn't exists then will retrieve other file of different date.

```<code>#!/bin/ksh

FILE1="CAS_20170604.txt"
FILE2="CAS_20170603.txt"

/usr/bin/ftp -n 93.45.148.9 << EOF
    user usr passwd
    cd "/abc/def"
    bin
    get $FILE1

if [ ! -f $FILE1 ];
then
    cd "/abc/def"
    bin
    get $FILE2
fi
    bye
    !EOF!
</code>```

While on executing the script, I'm getting both the files, which is not required, and the below error:

?Invalid command
?Invalid command
```

Please someone could help me here.

答:
You cannot use shell commands in ftp script.

You have to split the script into two:

```<code>/usr/bin/ftp -n 93.45.148.9 << EOF
user usr passwd
cd "/abc/def"
bin
get $FILE1
bye
!EOF!

if [ ! -f $FILE1 ];
then
    /usr/bin/ftp -n 93.45.148.9 << EOF
    user usr passwd
    cd "/abc/def"
    bin
    get $FILE2
    bye
    !EOF!
fi
</code>```

Title: Conditions in unix ftp script

Body:
I'm trying to write a code that will check a specific date's file and if it exists it'll get it to my local home path and if it doesn't exists then will retrieve other file of different date.

#!/bin/ksh

FILE1="CAS_20170604.txt"
FILE2="CAS_20170603.txt"

/usr/bin/ftp -n 93.45.148.9 << EOF
    user usr passwd
    cd "/abc/def"
    bin
    get $FILE1

if [ ! -f $FILE1 ];
then
    cd "/abc/def"
    bin
    get $FILE2
fi
    bye
    !EOF!

While on executing the script, I'm getting both the files, which is not required, and the below error:

?Invalid command
?Invalid command

Please someone could help me here.

Body:
You cannot use shell commands in ftp script.

You have to split the script into two:

/usr/bin/ftp -n 93.45.148.9 << EOF
user usr passwd
cd "/abc/def"
bin
get $FILE1
bye
!EOF!

if [ ! -f $FILE1 ];
then
    /usr/bin/ftp -n 93.45.148.9 << EOF
    user usr passwd
    cd "/abc/def"
    bin
    get $FILE2
    bye
    !EOF!
fi


问:
Coudnot Install Gradle distribution - eclipse- Liferay
Error shows when I took a new Liferay module project

I am using eclipse with liferay plugin. when I take a new liferay module project it shows above error    (Synchronize Gradle builds with workspace failed due to an error connecting to the Gradle build.
Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-3.0-bin.zip'.
).

Is it related to any certificate issue
?. How can I resolve it. Please share your knowledge on this, Thanks.

答:
JDK8 is must for Liferay 7 / DXP. Make sure the JAVA_HOME is pointing to JDK and not JRE. My gradle.properties initializes JDK like org.gradle.java.home=c:/java/jdk8 .
Howeve, I feel the issue is more inclined to proxy. Please check the proxy restriction on your network. If you can take the machine to open network, I bet you won't find the issue, given everything else in your eclipse is set properly of is defaulted.


问:
Can't retrieve data back from UMLS
I have been trying to run the ctakes-temporal-demo on github.
Currently I have configured everything in eclipse correctly. I have set the correct password and id for UMLS account. When I try to run it I get the following error:

```<code>Exception in thread "main" java.lang.Exception: org.apache.uima.resource.ResourceInitializationException: Initialization of annotator class "org.apache.ctakes.dictionary.lookup2.ae.DefaultJCasTermAnnotator" failed.  (Descriptor: <unknown>)
       at com.optum.cda.Main.main(Main.java:103)
Caused by: org.apache.uima.resource.ResourceInitializationException: Initialization of annotator class "org.apache.ctakes.dictionary.lookup2.ae.DefaultJCasTermAnnotator" failed.  (Descriptor: <unknown>)
       at org.apache.uima.analysis_engine.impl.PrimitiveAnalysisEngine_impl.initializeAnalysisComponent(PrimitiveAnalysisEngine_impl.java:252)
       at org.apache.uima.analysis_engine.impl.PrimitiveAnalysisEngine_impl.initialize(PrimitiveAnalysisEngine_impl.java:156)
       at org.apache.uima.impl.AnalysisEngineFactory_impl.produceResource(AnalysisEngineFactory_impl.java:94)
       at org.apache.uima.impl.CompositeResourceFactory_impl.produceResource(CompositeResourceFactory_impl.java:62)
       at org.apache.uima.UIMAFramework.produceResource(UIMAFramework.java:269)
       at org.apache.uima.UIMAFramework.produceAnalysisEngine(UIMAFramework.java:387)
       at org.apache.uima.analysis_engine.asb.impl.ASB_impl.setup(ASB_impl.java:254)
       at org.apache.uima.analysis_engine.impl.AggregateAnalysisEngine_impl.initASB(AggregateAnalysisEngine_impl.java:431)
       at org.apache.uima.analysis_engine.impl.AggregateAnalysisEngine_impl.initializeAggregateAnalysisEngine(AggregateAnalysisEngine_impl.java:375)
       at org.apache.uima.analysis_engine.impl.AggregateAnalysisEngine_impl.initialize(AggregateAnalysisEngine_impl.java:185)
       at org.apache.uima.fit.factory.AnalysisEngineFactory.createEngine(AnalysisEngineFactory.java:711)
       at org.apache.uima.fit.factory.AggregateBuilder.createAggregate(AggregateBuilder.java:207)
       at com.optum.cda.Main.main(Main.java:101)
Caused by: org.apache.uima.resource.ResourceInitializationException: EXCEPTION MESSAGE LOCALIZATION FAILED: java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key Could not construct org.apache.ctakes.dictionary.lookup2.dictionary.UmlsJdbcRareWordDictionary
       at org.apache.ctakes.dictionary.lookup2.ae.AbstractJCasTermAnnotator.initialize(AbstractJCasTermAnnotator.java:131)
       at org.apache.uima.analysis_engine.impl.PrimitiveAnalysisEngine_impl.initializeAnalysisComponent(PrimitiveAnalysisEngine_impl.java:250)
       ... 12 more
Caused by: org.apache.uima.analysis_engine.annotator.AnnotatorContextException: EXCEPTION MESSAGE LOCALIZATION FAILED: java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key Could not construct org.apache.ctakes.dictionary.lookup2.dictionary.UmlsJdbcRareWordDictionary
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDictionary(DictionaryDescriptorParser.java:199)
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDictionaries(DictionaryDescriptorParser.java:156)
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDescriptor(DictionaryDescriptorParser.java:128)
       at org.apache.ctakes.dictionary.lookup2.ae.AbstractJCasTermAnnotator.initialize(AbstractJCasTermAnnotator.java:129)
       ... 13 more
Caused by: java.lang.reflect.InvocationTargetException
       at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
       at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
       at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
       at java.lang.reflect.Constructor.newInstance(Unknown Source)
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDictionary(DictionaryDescriptorParser.java:196)
       ... 16 more
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -7
       at java.lang.String.substring(Unknown Source)
       at org.apache.ctakes.dictionary.lookup2.util.JdbcConnectionFactory.getConnectionUrl(JdbcConnectionFactory.java:110)
       at org.apache.ctakes.dictionary.lookup2.util.JdbcConnectionFactory.getConnection(JdbcConnectionFactory.java:63)
       at org.apache.ctakes.dictionary.lookup2.dictionary.JdbcRareWordDictionary.<init>(JdbcRareWordDictionary.java:91)
       at org.apache.ctakes.dictionary.lookup2.dictionary.JdbcRareWordDictionary.<init>(JdbcRareWordDictionary.java:72)
       at org.apache.ctakes.dictionary.lookup2.dictionary.UmlsJdbcRareWordDictionary.<init>(UmlsJdbcRareWordDictionary.java:31)
       ... 21 more
</code>```

Can someone familiar with ctakes help me find out the error. I have tried the mailing list, but no replies.

答:
Finally found a solution ! It seems like the path to the XML descriptor of the dictionary-fast is not reachable. Thus after validating an UMLS user the database setup could not be proceeded.

One of the solution I used was to use a static address for the database (which I will have to change always if the project is moved.). This is not very elegant but works.

Love to hear if anyone has another solution.

Title: Can't retrieve data back from UMLS

Body:
I have been trying to run the ctakes-temporal-demo on github.
Currently I have configured everything in eclipse correctly. I have set the correct password and id for UMLS account. When I try to run it I get the following error:

Exception in thread "main" java.lang.Exception: org.apache.uima.resource.ResourceInitializationException: Initialization of annotator class "org.apache.ctakes.dictionary.lookup2.ae.DefaultJCasTermAnnotator" failed.  (Descriptor: <unknown>)
       at com.optum.cda.Main.main(Main.java:103)
Caused by: org.apache.uima.resource.ResourceInitializationException: Initialization of annotator class "org.apache.ctakes.dictionary.lookup2.ae.DefaultJCasTermAnnotator" failed.  (Descriptor: <unknown>)
       at org.apache.uima.analysis_engine.impl.PrimitiveAnalysisEngine_impl.initializeAnalysisComponent(PrimitiveAnalysisEngine_impl.java:252)
       at org.apache.uima.analysis_engine.impl.PrimitiveAnalysisEngine_impl.initialize(PrimitiveAnalysisEngine_impl.java:156)
       at org.apache.uima.impl.AnalysisEngineFactory_impl.produceResource(AnalysisEngineFactory_impl.java:94)
       at org.apache.uima.impl.CompositeResourceFactory_impl.produceResource(CompositeResourceFactory_impl.java:62)
       at org.apache.uima.UIMAFramework.produceResource(UIMAFramework.java:269)
       at org.apache.uima.UIMAFramework.produceAnalysisEngine(UIMAFramework.java:387)
       at org.apache.uima.analysis_engine.asb.impl.ASB_impl.setup(ASB_impl.java:254)
       at org.apache.uima.analysis_engine.impl.AggregateAnalysisEngine_impl.initASB(AggregateAnalysisEngine_impl.java:431)
       at org.apache.uima.analysis_engine.impl.AggregateAnalysisEngine_impl.initializeAggregateAnalysisEngine(AggregateAnalysisEngine_impl.java:375)
       at org.apache.uima.analysis_engine.impl.AggregateAnalysisEngine_impl.initialize(AggregateAnalysisEngine_impl.java:185)
       at org.apache.uima.fit.factory.AnalysisEngineFactory.createEngine(AnalysisEngineFactory.java:711)
       at org.apache.uima.fit.factory.AggregateBuilder.createAggregate(AggregateBuilder.java:207)
       at com.optum.cda.Main.main(Main.java:101)
Caused by: org.apache.uima.resource.ResourceInitializationException: EXCEPTION MESSAGE LOCALIZATION FAILED: java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key Could not construct org.apache.ctakes.dictionary.lookup2.dictionary.UmlsJdbcRareWordDictionary
       at org.apache.ctakes.dictionary.lookup2.ae.AbstractJCasTermAnnotator.initialize(AbstractJCasTermAnnotator.java:131)
       at org.apache.uima.analysis_engine.impl.PrimitiveAnalysisEngine_impl.initializeAnalysisComponent(PrimitiveAnalysisEngine_impl.java:250)
       ... 12 more
Caused by: org.apache.uima.analysis_engine.annotator.AnnotatorContextException: EXCEPTION MESSAGE LOCALIZATION FAILED: java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key Could not construct org.apache.ctakes.dictionary.lookup2.dictionary.UmlsJdbcRareWordDictionary
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDictionary(DictionaryDescriptorParser.java:199)
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDictionaries(DictionaryDescriptorParser.java:156)
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDescriptor(DictionaryDescriptorParser.java:128)
       at org.apache.ctakes.dictionary.lookup2.ae.AbstractJCasTermAnnotator.initialize(AbstractJCasTermAnnotator.java:129)
       ... 13 more
Caused by: java.lang.reflect.InvocationTargetException
       at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
       at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
       at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
       at java.lang.reflect.Constructor.newInstance(Unknown Source)
       at org.apache.ctakes.dictionary.lookup2.dictionary.DictionaryDescriptorParser.parseDictionary(DictionaryDescriptorParser.java:196)
       ... 16 more
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -7
       at java.lang.String.substring(Unknown Source)
       at org.apache.ctakes.dictionary.lookup2.util.JdbcConnectionFactory.getConnectionUrl(JdbcConnectionFactory.java:110)
       at org.apache.ctakes.dictionary.lookup2.util.JdbcConnectionFactory.getConnection(JdbcConnectionFactory.java:63)
       at org.apache.ctakes.dictionary.lookup2.dictionary.JdbcRareWordDictionary.<init>(JdbcRareWordDictionary.java:91)
       at org.apache.ctakes.dictionary.lookup2.dictionary.JdbcRareWordDictionary.<init>(JdbcRareWordDictionary.java:72)
       at org.apache.ctakes.dictionary.lookup2.dictionary.UmlsJdbcRareWordDictionary.<init>(UmlsJdbcRareWordDictionary.java:31)
       ... 21 more

Can someone familiar with ctakes help me find out the error. I have tried the mailing list, but no replies.


问:
how to call web service(.wsdl) using asp.net
I got .wsdl file from my client. by using this webservice i need validate customer information. So how to achieve this one .if customer is there or not
xml :

```<code> <xs:element name="FetchClubMembershipRequest">
        <xs:annotation>
          <xs:documentation>Request to fetch customers' membership information.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_ID" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_Code" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Last_Name" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="First_Name" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
</code>```

this is from wsdl.file

答:
Go to Project > Add Web Reference and enter url or local path to your wsdl file and then
VS will fetch the WSDL file, and if everything is fine, it will display it on the left, and enable the Add Reference button at the bottom, so we can add it to our Project.</p>

```<code>public yourWebService.xyz ws = new yourWebService.xyz();
Private void btnValidate_Click()
{
   // your webservice validation logic..
   // here m considering your webservice as checking wheather a input is number
 if(ws.checkIsNumber(txtNumber.text))
   //something if true
 else
   //something if wrong
}
</code>```

Body:
I got .wsdl file from my client. by using this webservice i need validate customer information. So how to achieve this one .if customer is there or not
xml :

 <xs:element name="FetchClubMembershipRequest">
        <xs:annotation>
          <xs:documentation>Request to fetch customers' membership information.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_ID" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Customer_Code" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="Last_Name" type="xs:string" />
            <xs:element minOccurs="1" maxOccurs="1" name="First_Name" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

this is from wsdl.file

Body:
Go to Project > Add Web Reference and enter url or local path to your wsdl file and then
VS will fetch the WSDL file, and if everything is fine, it will display it on the left, and enable the Add Reference button at the bottom, so we can add it to our Project.

public yourWebService.xyz ws = new yourWebService.xyz();
Private void btnValidate_Click()
{
   // your webservice validation logic..
   // here m considering your webservice as checking wheather a input is number
 if(ws.checkIsNumber(txtNumber.text))
   //something if true
 else
   //something if wrong
}


问:
How sublime replace some word
How can I replace some words by sublime text 3, for example:

```<code>function test()
    print("test t")
    print("test t")
    print("test t")
end
</code>```

I just want to replace the ‘t’ to 'a' which in 'test t', like print("test a").
Thanks.

答:
In this case, select this - t", press ctrl + h, type this - a" as a replacement & hit enter!

Another way - select t" and press ctrl + d for no. of times as per your expected count of matching words; no. of cursors will select that much words & then type your replacement. That's it!

Title: How sublime replace some word

Body:
How can I replace some words by sublime text 3, for example:

function test()
    print("test t")
    print("test t")
    print("test t")
end

I just want to replace the ‘t’ to 'a' which in 'test t', like print("test a").
Thanks.


问:
Firebase database authentication
I am trying to add text(32424234) into my firebase under the userid of the user but it doesnt let me do it.

This is my rules section under firebase

```<code>{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid == auth.uid",
        ".write": "$uid == auth.uid"
      }
    }
  }
}
</code>```

This is my java code:

```<code>public void kullanicikontrol(String kullaniciadi){
        mRootRef = new Firebase("https://xxxx.firebaseio.com/users");
        Firebase chieldref = mRootRef.child(kullaniciadi);
        chieldref.setValue("32424234");
}
</code>```

if i change rules like ".read": true" there is no problem like the screenshot below:

but i dont want to. What i am doing wrong?

答:
In firebase .read and .write is read write permission. If you set it to true than it allow all user.

You can create new user and authentication by following link
https://firebase.google.com/docs/auth/web/manage-users

I hope this will help you.

Title: Firebase database authentication

Body:
I am trying to add text(32424234) into my firebase under the userid of the user but it doesnt let me do it.

This is my rules section under firebase

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid == auth.uid",
        ".write": "$uid == auth.uid"
      }
    }
  }
}

This is my java code:

public void kullanicikontrol(String kullaniciadi){
        mRootRef = new Firebase("https://xxxx.firebaseio.com/users");
        Firebase chieldref = mRootRef.child(kullaniciadi);
        chieldref.setValue("32424234");
}

if i change rules like ".read": true" there is no problem like the screenshot below:

but i dont want to. What i am doing wrong?


问:
how to transpose column to row in bash
I am trying to rearrange my text file:

```<code>Record    :   Field1
              Field2
              Field3
Record    :   Field1
Record    :   Field1
Record    :   Field1
              Field2
              Field3
              Field4
              Field5
</code>```

How can I use awk or sed to rearrange it so that my output looks like this?

```<code>Field1, Field2, Field3
Field1
Field1
Field1, Field2, Field3, Field4, Field5
</code>```

答:
This might work for you (GNU sed):

```<code>sed '/^Record.*:\s*/{s///;:a;N;s/\s*\n\s\+/, /;ta;P;D}' file
</code>```

Focus on lines beginning with Record followed by a number of characters, then a : and finally some spaces. Remove the front of this line using the match. Append the next line (if there is one) and replace any newline with spaces either side with a , and a space. Repeat if necessary, then print the line and repeat.

Title: how to transpose column to row in bash

Body:
I am trying to rearrange my text file:

Record    :   Field1
              Field2
              Field3
Record    :   Field1
Record    :   Field1
Record    :   Field1
              Field2
              Field3
              Field4
              Field5

How can I use awk or sed to rearrange it so that my output looks like this?

Field1, Field2, Field3
Field1
Field1
Field1, Field2, Field3, Field4, Field5

Body:
This might work for you (GNU sed):

sed '/^Record.*:\s*/{s///;:a;N;s/\s*\n\s\+/, /;ta;P;D}' file

Focus on lines beginning with Record followed by a number of characters, then a : and finally some spaces. Remove the front of this line using the match. Append the next line (if there is one) and replace any newline with spaces either side with a , and a space. Repeat if necessary, then print the line and repeat.


问:
TransactionTooLargeException in Nougat
Exception

```<code> 05-12 15:42:45.791 11043-11043/ E/UncaughtException: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                    Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.os.BinderProxy.transactNative(Native Method)
                                                                       at android.os.BinderProxy.transact(Binder.java:615)
                                                                       at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
05-12 15:42:47.247 11043-11043/ E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: , PID: 11043
                                                                java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                 Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.os.BinderProxy.transactNative(Native Method)
                                                                    at android.os.BinderProxy.transact(Binder.java:615)
                                                                    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

Fragment OnItemClick:-

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });
</code>```

In DetailActivity,

```<code>Bundle bundle = getIntent().getBundleExtra("bundle");
    if (bundle != null) {
        ProdModel model = (ProdModel) bundle.getSerializable("object");
    }
</code>```

DetailActivity Manifest,

```<code>  <activity
        android:name="com.mass.mysample.DetailActivity"
        android:screenOrientation="portrait" />
</code>```

Image Loading Using Picasso,

```<code> Picasso.with(this).load(model.getImage())
             .placeholder(R.drawable.logo_without)
             .fit().into(productimage);
</code>```

Model Class

```<code>public class ProdModel implements Serializable {
private String seller_id;
String name;
private String image;
private float price;
private float specialprice;
private String entity_id;
private String productNumQuantity;
private String storetitle;
private String description;
private String discount;
private String max_price;
private String store_name;
private String StoreUrl;

public String getProductNumQuantity() {
    return productNumQuantity;
}

public void setProductNumQuantity(String productNumQuantity) {
    this.productNumQuantity = productNumQuantity;
}

public String getDiscount() {
    return discount;
}

public void setDiscount(String discount) {
    this.discount = discount;
}

public String getMax_price() {
    return max_price;
}

public void setMax_price(String max_price) {
    this.max_price = max_price;
}

public String getStore_name() {
    return store_name;
}

public void setStore_name(String store_name) {
    this.store_name = store_name;
}

public String getStoreUrl() {
    return StoreUrl;
}

public void setStoreUrl(String storeUrl) {
    StoreUrl = storeUrl;
}

public String getStoretitle() {
    return storetitle;
}

public void setStoretitle(String storetitle) {
    this.storetitle = storetitle;
}

public String getSeller_id() {
    return seller_id;
}

public void setSeller_id(String seller_id) {
    this.seller_id = seller_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getEntity_id() {
    return entity_id;
}

public void setEntity_id(String entity_id) {
    this.entity_id = entity_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public float getSpecialPrice() {
    return specialprice;
}

public void setSpecialPrice(float specialprice) {
    this.specialprice = specialprice;
}

}
</code>```

Data flow from TabActivity to fragment,

```<code>1.I have a TabActivity with ViewPager and Fragment.
2.In Fragment, I have a ListView.
3.The Data to fragment is passed from view pager adapter by set arguments.
</code>```

Solutions I tried

```<code>1.A POJO class that implements Serialization.
2.I use Picasso to load the image from image URL.
3.This exception is thrown when OnItemClick on ListView in fragment passes data to DetailActivity to show all passed data.
4.I get this exception after the DetailActivity load's image and other data then app suddenly crashes.
5.I pass data in Intent was all POJO Object with Id, Name, Image URL, Price etc.,
</code>```

Note:-
App Crash only in NOUGAT

Finally, The fix I implemented

changing the targetSdkVersion to 23 from 25

After changing, my application not crashing in Nougat too.

All I have to Know is this proper solution or is there any workaround.

Please Guide to the proper way.

Thanks in advance.

Fragment

```<code>public class ProdFragment extends Fragment {
ListView listview;
SharedPreferences spref;
Boolean isInternetPresent = false;
ConnectionDetector cd;

private String toBeDisplayed,CatID;
private static final String TAG = ProdFragment.class.getSimpleName();
String totalProductCart;
private ArrayList<Root_SubCatModel> subCatList;
private ArrayList<ProdModel> prodList;
ProdAdapter adapter;

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spref = getActivity().getSharedPreferences(getResources().getString(R.string.myPref),
            Context.MODE_PRIVATE);
    Bundle bundle = getArguments();
    if (bundle != null) {
        int tabPosition = bundle.getInt("Tab_Position");
        toBeDisplayed = bundle.getString("Tab_ToBeDisplayed");
        CatID = bundle.getString("CategoryId");
        subCatList = (ArrayList<Root_SubCatModel>) bundle.getSerializable("Tab_Data");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.prod_listview, container, false);

    cd = new ConnectionDetector(getActivity());
    listview = (ListView) rootView.findViewById(R.id.prodlist);
    if (subCatList != null) {
        adapter = new ProdAdapter(getActivity(),
                CatID,
                toBeDisplayed,
                R.layout.list_product,
                subCatList,
                (ProductCartCountListener)getActivity());
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        prodList = new ArrayList<>();
        for(int i = 0; i<subCatList.size();i++){
            if (subCatList.get(i).getProd() != null) {
                if(toBeDisplayed.equals("SubCategory")){
                    if (CatID.equals(subCatList.get(i).getCategory_id())) {
                        this.prodList = subCatList.get(i).getProd();
                    }
                }else if(toBeDisplayed.equals("Products")) {
                    this.prodList = subCatList.get(i).getProd();
                }
            }
        }

    }

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("object", prodList.get(position));
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent,1);
        }

    });

    return rootView;
}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Bundle b = data.getExtras();
            if (b != null) {
                ProdModel myobj = (ProdModel) b.getSerializable("Cart_Quantity");
                if (myobj != null) {
                    if (prodList != null) {
                        for (ProdModel P : prodList) {
                            if (P.getEntity_id().equals(myobj.getEntity_id())) {
                                P.setProductNumQuantity(myobj.getProductNumQuantity());
                            }
                        }
                    }
                    Log.d(TAG,"Product_Id : " + myobj.getEntity_id()
                            + ", Product_Cart_Count : " + myobj.getProductNumQuantity());
                }
            }
        } else if (resultCode == 0) {
            Log.d(TAG,"RESULT CANCELLED");
        }
    }
    adapter.notifyDataSetChanged();
    String totalProductCart = spref.getString("Cart_Count_Tool", "0");
    Activity activity = getActivity();
    if(activity instanceof TabActivity){
        TabActivity myActivity = (TabActivity) activity;
        Toolbar toolbar = (Toolbar) myActivity.findViewById(R.id.back_toolbar);
        ImageView cart_imageview = (ImageView) toolbar.findViewById(R.id.cart_imageview);
        cart_imageview.setImageDrawable(myActivity.buildCounterDrawable(
                Integer.parseInt(totalProductCart)));
    }
    Log.d(TAG,"RESULT NOTIFIED");
}

public void refreshData(String productId, boolean isAddAsyncTaskComplete,
                        boolean isAddAsyncTaskLimitReached, boolean isDeleteAsyncTaskComplete){
    adapter.setQuantityCount(prodList, productId, isAddAsyncTaskComplete,
            isAddAsyncTaskLimitReached, isDeleteAsyncTaskComplete);

}
</code>```

TabActivity Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/storeimage"
        android:textAlignment="center"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_dark_blue"
        app:tabSelectedTextColor="@color/color_orange"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 </android.support.design.widget.CoordinatorLayout>
</code>```

ListView

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });
</code>```0

答:
Android 7.0 (Nogat) includes a variety of system and API behaviour changes.
Regarding TransactionTooLarge Exception :

In Android 7.0, many platform APIs have now started checking for large
  payloads being sent across Binder transactions, and the system now
  rethrows TransactionTooLargeExceptions as RuntimeExceptions, instead
  of silently logging or suppressing them. One common example is storing
  too much data in Activity.onSaveInstanceState(), which causes
  ActivityThread.StopInfo to throw a RuntimeException when your app
  targets Android 7.0.

Possible Solutions :
 1. Save required object in global cache and pass only the key to DetailsActivity to retrieve the object.

Title: TransactionTooLargeException in Nougat

Body:
Exception

 05-12 15:42:45.791 11043-11043/ E/UncaughtException: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                    Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.os.BinderProxy.transactNative(Native Method)
                                                                       at android.os.BinderProxy.transact(Binder.java:615)
                                                                       at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
05-12 15:42:47.247 11043-11043/ E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: , PID: 11043
                                                                java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                 Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.os.BinderProxy.transactNative(Native Method)
                                                                    at android.os.BinderProxy.transact(Binder.java:615)
                                                                    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Fragment OnItemClick:-

 listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });

In DetailActivity,

Bundle bundle = getIntent().getBundleExtra("bundle");
    if (bundle != null) {
        ProdModel model = (ProdModel) bundle.getSerializable("object");
    }

DetailActivity Manifest,

  <activity
        android:name="com.mass.mysample.DetailActivity"
        android:screenOrientation="portrait" />

Image Loading Using Picasso,

 Picasso.with(this).load(model.getImage())
             .placeholder(R.drawable.logo_without)
             .fit().into(productimage);

Model Class

public class ProdModel implements Serializable {
private String seller_id;
String name;
private String image;
private float price;
private float specialprice;
private String entity_id;
private String productNumQuantity;
private String storetitle;
private String description;
private String discount;
private String max_price;
private String store_name;
private String StoreUrl;

public String getProductNumQuantity() {
    return productNumQuantity;
}

public void setProductNumQuantity(String productNumQuantity) {
    this.productNumQuantity = productNumQuantity;
}

public String getDiscount() {
    return discount;
}

public void setDiscount(String discount) {
    this.discount = discount;
}

public String getMax_price() {
    return max_price;
}

public void setMax_price(String max_price) {
    this.max_price = max_price;
}

public String getStore_name() {
    return store_name;
}

public void setStore_name(String store_name) {
    this.store_name = store_name;
}

public String getStoreUrl() {
    return StoreUrl;
}

public void setStoreUrl(String storeUrl) {
    StoreUrl = storeUrl;
}

public String getStoretitle() {
    return storetitle;
}

public void setStoretitle(String storetitle) {
    this.storetitle = storetitle;
}

public String getSeller_id() {
    return seller_id;
}

public void setSeller_id(String seller_id) {
    this.seller_id = seller_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getEntity_id() {
    return entity_id;
}

public void setEntity_id(String entity_id) {
    this.entity_id = entity_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public float getSpecialPrice() {
    return specialprice;
}

public void setSpecialPrice(float specialprice) {
    this.specialprice = specialprice;
}

}

Data flow from TabActivity to fragment,

1.I have a TabActivity with ViewPager and Fragment.
2.In Fragment, I have a ListView.
3.The Data to fragment is passed from view pager adapter by set arguments.

Solutions I tried

1.A POJO class that implements Serialization.
2.I use Picasso to load the image from image URL.
3.This exception is thrown when OnItemClick on ListView in fragment passes data to DetailActivity to show all passed data.
4.I get this exception after the DetailActivity load's image and other data then app suddenly crashes.
5.I pass data in Intent was all POJO Object with Id, Name, Image URL, Price etc.,

Note:-
App Crash only in NOUGAT

Finally, The fix I implemented

changing the targetSdkVersion to 23 from 25

After changing, my application not crashing in Nougat too.

All I have to Know is this proper solution or is there any workaround.

Please Guide to the proper way.

Thanks in advance.

Fragment

public class ProdFragment extends Fragment {
ListView listview;
SharedPreferences spref;
Boolean isInternetPresent = false;
ConnectionDetector cd;

private String toBeDisplayed,CatID;
private static final String TAG = ProdFragment.class.getSimpleName();
String totalProductCart;
private ArrayList<Root_SubCatModel> subCatList;
private ArrayList<ProdModel> prodList;
ProdAdapter adapter;

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spref = getActivity().getSharedPreferences(getResources().getString(R.string.myPref),
            Context.MODE_PRIVATE);
    Bundle bundle = getArguments();
    if (bundle != null) {
        int tabPosition = bundle.getInt("Tab_Position");
        toBeDisplayed = bundle.getString("Tab_ToBeDisplayed");
        CatID = bundle.getString("CategoryId");
        subCatList = (ArrayList<Root_SubCatModel>) bundle.getSerializable("Tab_Data");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.prod_listview, container, false);

    cd = new ConnectionDetector(getActivity());
    listview = (ListView) rootView.findViewById(R.id.prodlist);
    if (subCatList != null) {
        adapter = new ProdAdapter(getActivity(),
                CatID,
                toBeDisplayed,
                R.layout.list_product,
                subCatList,
                (ProductCartCountListener)getActivity());
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        prodList = new ArrayList<>();
        for(int i = 0; i<subCatList.size();i++){
            if (subCatList.get(i).getProd() != null) {
                if(toBeDisplayed.equals("SubCategory")){
                    if (CatID.equals(subCatList.get(i).getCategory_id())) {
                        this.prodList = subCatList.get(i).getProd();
                    }
                }else if(toBeDisplayed.equals("Products")) {
                    this.prodList = subCatList.get(i).getProd();
                }
            }
        }

    }

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("object", prodList.get(position));
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent,1);
        }

    });

    return rootView;
}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Bundle b = data.getExtras();
            if (b != null) {
                ProdModel myobj = (ProdModel) b.getSerializable("Cart_Quantity");
                if (myobj != null) {
                    if (prodList != null) {
                        for (ProdModel P : prodList) {
                            if (P.getEntity_id().equals(myobj.getEntity_id())) {
                                P.setProductNumQuantity(myobj.getProductNumQuantity());
                            }
                        }
                    }
                    Log.d(TAG,"Product_Id : " + myobj.getEntity_id()
                            + ", Product_Cart_Count : " + myobj.getProductNumQuantity());
                }
            }
        } else if (resultCode == 0) {
            Log.d(TAG,"RESULT CANCELLED");
        }
    }
    adapter.notifyDataSetChanged();
    String totalProductCart = spref.getString("Cart_Count_Tool", "0");
    Activity activity = getActivity();
    if(activity instanceof TabActivity){
        TabActivity myActivity = (TabActivity) activity;
        Toolbar toolbar = (Toolbar) myActivity.findViewById(R.id.back_toolbar);
        ImageView cart_imageview = (ImageView) toolbar.findViewById(R.id.cart_imageview);
        cart_imageview.setImageDrawable(myActivity.buildCounterDrawable(
                Integer.parseInt(totalProductCart)));
    }
    Log.d(TAG,"RESULT NOTIFIED");
}

public void refreshData(String productId, boolean isAddAsyncTaskComplete,
                        boolean isAddAsyncTaskLimitReached, boolean isDeleteAsyncTaskComplete){
    adapter.setQuantityCount(prodList, productId, isAddAsyncTaskComplete,
            isAddAsyncTaskLimitReached, isDeleteAsyncTaskComplete);

}

TabActivity Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/storeimage"
        android:textAlignment="center"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_dark_blue"
        app:tabSelectedTextColor="@color/color_orange"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 </android.support.design.widget.CoordinatorLayout>

ListView

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/prodlist"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</FrameLayout>


问:
How to share the url on a social websites like facebook,google?
I am doing a live stream application.In that I am getting one link.How to share the link on social websites when click on the share button?</p>

答:
You can use this library angular-socialshare.

Add the references and use it as a dependency,

```<code> angular.module('myApp', [
    '720kb.socialshare'
  ]);
</code>```

Body:
You can use this library angular-socialshare.

Add the references and use it as a dependency,

 angular.module('myApp', [
    '720kb.socialshare'
  ]);


问:
Get key used to change Spaces
Is there any way to programatically determine what key is set in System Preferences to change to a specific Space.

This setting is configured in the Expose & Spaces preference, under the Spaces tab. The last drop down box is titled "To switch directly to a space" and you can choose from the control key, the command key, the option key or no key.

This is the value I'd like to programatically determine.

Possible?

答:
You could try using AppleScript's GUI scripting to programatically open the preferences pane and see what is in the drop down box. An example is here. To invoke it from Objective-C, check out Scripting Bridge if you're using OS 10.5 or later, otherwise there's an older API but I can't seem to find it at the moment.

If you want a solution that doesn't require popping up the System Preferences window and showing all its animations to the user, the actual value is stored somewhere in ~/Library/Preferences/com.apple.symbolichotkeys.plist, but the format is not human-readable. You could change the key binding from System Preferences and compare that file before and after. Keep in mind that this may be different between versions of OS X.

Hope this helps, and welcome to Stack Overflow!

Title: Get key used to change Spaces