问:
Excel JavaScript API requirement set 1.8 events
New event features planned for requirement set 1.8 of the Excel JavasScript API are listed in the ExcelApi OpenSepc site.

Will the events tableDataChangedEvent and worksheetDataChangedEvent fire under the following conditions:

The user hides/unhides rows.

Rows are hidden/unhidden as a result of applying a filter.

When cells containing formulas change values due to modifications in another worksheet.

答:
The upcoming data change event in Worksheet will be fired when data is actually changed. Apply this criteria to cells:

The user hides/unhides rows -> No firing. Since the data weren't changed.

Rows are hidden/unhidden as a result of applying a filter.-> No firing. Since the data weren't changed.

When cells containing formulas change values due to modifications in another worksheet.-> No firing. Since the data weren't changed. In this case, cell treats the formula as its data, rather than the outcome of the formula. In addition, we are developing another events called Calculate Events, which would be fired when the dependencies of formula are changed and caused the outcome changing.

Any feedback on DataChange/Calculate events designing are welcome :)


来源: stackexchange

问:
How to tweet with Twitterizer by using C#
i downloaded latest Twitterizer  . added these references.

```<code>using Twitterizer.Core;
using Twitterizer.Data;
using Twitterizer.Entities;
using Twitterizer.Streaming;
</code>```

now what do i need to do ? i searched internet but examples are old and probably not supported by twitter. can anbody explain me step by step ?

i just want to tweet via my account.

Edit: Problem solved by using TweetSharp. i suggest you to use TweetSharp instead of Twitterizer .

答:
Have you see the code examples on this page:

http://www.twitterizer.net/

Also see the docs page:

http://www.twitterizer.net/documentation/

The API seems a little confusing to me, never heard of this library.

Why not use Linq to Twitter : http://linqtotwitter.codeplex.com/

Its used by a lot of people.

ContentLicense: CC BY-SA 2.5

Body:
i downloaded latest Twitterizer  . added these references.

using Twitterizer.Core;
using Twitterizer.Data;
using Twitterizer.Entities;
using Twitterizer.Streaming;

now what do i need to do ? i searched internet but examples are old and probably not supported by twitter. can anbody explain me step by step ?

i just want to tweet via my account.

Edit: Problem solved by using TweetSharp. i suggest you to use TweetSharp instead of Twitterizer .


问:
Grafana table that shows top 5 objects from an Array
I'm trying to create a table that shows the top 5 nested objects in an array.
My documents look something like this:

```<code>{
 "_id": 1,
 "workers": [
     {
       "worker_id": 1,
       "units": [
          {
            "unit_id": 1,
            "time": 100
          },
          {
            "unit_id": 2,
            "time": 200
          },
          {
            "unit_id": 3,
            "time": 300
          },
          {
            "unit_id": 4,
            "time": 400
          }
       ]
    },
    {
       "worker_id": 2,
       "units": [
          {
            "unit_id": 11,
            "time": 1000
          },
          {
            "unit_id": 12,
            "time": 200
          },
          {
            "unit_id": 13,
            "time": 300
          },
          {
            "unit_id": 14,
            "time": 350
          }
       ]
    }
 ]
}
</code>```

I would like to have two columns in the table. One column with the _id of the document and the other with the unit_id. In the second column should be only the top five units that have the highest time.

Is this possible with Grafana?

答: For computing the top 5 entries from the nested Object, you can use simple-json-datasource plugin. You can create a simple Webapp which does the JSON Parsing logic and return the data in the format you want</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a table that shows the top 5 nested objects in an array.
My documents look something like this:

{
 "_id": 1,
 "workers": [
     {
       "worker_id": 1,
       "units": [
          {
            "unit_id": 1,
            "time": 100
          },
          {
            "unit_id": 2,
            "time": 200
          },
          {
            "unit_id": 3,
            "time": 300
          },
          {
            "unit_id": 4,
            "time": 400
          }
       ]
    },
    {
       "worker_id": 2,
       "units": [
          {
            "unit_id": 11,
            "time": 1000
          },
          {
            "unit_id": 12,
            "time": 200
          },
          {
            "unit_id": 13,
            "time": 300
          },
          {
            "unit_id": 14,
            "time": 350
          }
       ]
    }
 ]
}

I would like to have two columns in the table. One column with the _id of the document and the other with the unit_id. In the second column should be only the top five units that have the highest time.

Is this possible with Grafana?


问:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I have been following a manual to install a software suite on Ubuntu. I have no knowledge of MySQL at all. I have done the following installations on my Ubuntu.

sudo apt-get update
sudo apt-get install mysql-server-5.5
sudo apt-get install mysql-client-5.5
sudo apt-get install mysql-common
sudo apt-get install glade
sudo apt-get install ntp
```
<p>Then I do</p>
<pre class="lang-none prettyprint-override"><code>cd ~/Desktop/iPDC-v1.3.1/DBServer-1.1
mysql -uroot -proot <"Db.sql"
</code>```

I ended up with the following error message.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

How may I fix it and continue?

答:
The answer may sound silly, but after wasting hours of time, this is how I got it to work:

```<code>mysql -u root -p
</code>```

I got the error message

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Even though I was typing the correct password (the temporary password you get when you first install MySQL).

I got it right when I typed in the password when the password prompt was blinking.

ContentLicense: CC BY-SA 4.0

Body:
I have been following a manual to install a software suite on Ubuntu. I have no knowledge of MySQL at all. I have done the following installations on my Ubuntu.

sudo apt-get update
sudo apt-get install mysql-server-5.5
sudo apt-get install mysql-client-5.5
sudo apt-get install mysql-common
sudo apt-get install glade
sudo apt-get install ntp

Then I do

cd ~/Desktop/iPDC-v1.3.1/DBServer-1.1
mysql -uroot -proot <"Db.sql"

I ended up with the following error message.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

How may I fix it and continue?

Body:
The answer may sound silly, but after wasting hours of time, this is how I got it to work:

mysql -u root -p

I got the error message

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Even though I was typing the correct password (the temporary password you get when you first install MySQL).

I got it right when I typed in the password when the password prompt was blinking.


问:
Joining a List<String> in Java with commas and "and"
Given a list

```<code>List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");
</code>```

I have a method

```<code>String join(List<String> messages) {
        if (messages.isEmpty()) return "";
        if (messages.size() == 1) return messages.get(0);
        String message = "";
        message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");
        message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");
        return message;
    }
</code>```

which, for l, produces "one, two, and three".
My question is, is there a standard (apache-commons) method that does the same?, eg

```<code>WhatEverUtils.join(l, ", ", ", and ");
</code>```

To clarify. My problem is not getting this method to work. It works just as I want it to, it's tested and all is well. My problem is that I could not find some apache-commons-like module which implements such functionality. Which surprises me, since I cannot be the first one to need this.

But then maybe everyone else has just done

```<code>StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");
</code>```

答:
To produce grammatical output in English there are 3 cases to consider when concatenating a list of strings:

"A"

"A and B"

"A, B, and C.

This can be accomplished using standard Java or Guava like below. The solutions are basically the same and just up to preference what you want to use.

```<code>import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;

import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;

public class JoinListTest {

    @Test
    public void test_join() {
        // create cases (don't need to use ImmutableList builder from guava)
        final List<String> case1 = new ImmutableList.Builder<String>().add("A").build();
        final List<String> case2 = new ImmutableList.Builder<String>().add("A", "B").build();
        final List<String> case3 = new ImmutableList.Builder<String>().add("A", "B", "C").build();
        // test with standard java
        assertEquals("A", joinListGrammaticallyWithJava(case1));
        assertEquals("A and B", joinListGrammaticallyWithJava(case2));
        assertEquals("A, B, and C", joinListGrammaticallyWithJava(case3));
        // test with guava
        assertEquals("A", joinListGrammaticallyWithGuava(case1));
        assertEquals("A and B", joinListGrammaticallyWithGuava(case2));
        assertEquals("A, B, and C", joinListGrammaticallyWithGuava(case3));
    }

    private String joinListGrammaticallyWithJava(final List<String> list) {
        return list.size() > 1
                ? String.join(", ", list.subList(0, list.size() - 1))
                    .concat(String.format("%s and ", list.size() > 2 ? "," : ""))
                    .concat(list.get(list.size() - 1))
                : list.get(0);
    }

    private String joinListGrammaticallyWithGuava(final List<String> list) {
        return list.size() > 1
                ? Joiner.on(", ").join(list.subList(0, list.size() - 1))
                    .concat(String.format("%s and ", list.size() > 2 ? "," : ""))
                    .concat(list.get(list.size() - 1))
                : list.get(0);
    }

}
</code>```

Body:
Given a list

List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");

I have a method

String join(List<String> messages) {
        if (messages.isEmpty()) return "";
        if (messages.size() == 1) return messages.get(0);
        String message = "";
        message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");
        message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");
        return message;
    }

which, for l, produces "one, two, and three".
My question is, is there a standard (apache-commons) method that does the same?, eg

WhatEverUtils.join(l, ", ", ", and ");

To clarify. My problem is not getting this method to work. It works just as I want it to, it's tested and all is well. My problem is that I could not find some apache-commons-like module which implements such functionality. Which surprises me, since I cannot be the first one to need this.

But then maybe everyone else has just done

StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");

Body:
To produce grammatical output in English there are 3 cases to consider when concatenating a list of strings:

"A"

"A and B"

"A, B, and C.

This can be accomplished using standard Java or Guava like below. The solutions are basically the same and just up to preference what you want to use.

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;

import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;

public class JoinListTest {

    @Test
    public void test_join() {
        // create cases (don't need to use ImmutableList builder from guava)
        final List<String> case1 = new ImmutableList.Builder<String>().add("A").build();
        final List<String> case2 = new ImmutableList.Builder<String>().add("A", "B").build();
        final List<String> case3 = new ImmutableList.Builder<String>().add("A", "B", "C").build();
        // test with standard java
        assertEquals("A", joinListGrammaticallyWithJava(case1));
        assertEquals("A and B", joinListGrammaticallyWithJava(case2));
        assertEquals("A, B, and C", joinListGrammaticallyWithJava(case3));
        // test with guava
        assertEquals("A", joinListGrammaticallyWithGuava(case1));
        assertEquals("A and B", joinListGrammaticallyWithGuava(case2));
        assertEquals("A, B, and C", joinListGrammaticallyWithGuava(case3));
    }

    private String joinListGrammaticallyWithJava(final List<String> list) {
        return list.size() > 1
                ? String.join(", ", list.subList(0, list.size() - 1))
                    .concat(String.format("%s and ", list.size() > 2 ? "," : ""))
                    .concat(list.get(list.size() - 1))
                : list.get(0);
    }

    private String joinListGrammaticallyWithGuava(final List<String> list) {
        return list.size() > 1
                ? Joiner.on(", ").join(list.subList(0, list.size() - 1))
                    .concat(String.format("%s and ", list.size() > 2 ? "," : ""))
                    .concat(list.get(list.size() - 1))
                : list.get(0);
    }

}


问:
How to import JSON data in php file into Python
Please can anyone get me started with the following question?

I get a php file from a website that contains lots of data but I only need some of it. The file is so large I cannot paste it here.

I want to extract the data which is in JSON format and work with it in python.

The file for the example is named JSON1.php. When I open it using a text editor the contents are laid out in this format. Though this is a JSON example I found online.

```<code>{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}
</code>```

From what I can see it is standard JSON.

What I have been able to google and what I have found here doesn't deal with JSON data saved in a file with .php extention.

Many thanks!

答:
You can access json from a .php file the same way as a .json file.

Example code:

```<code>import json

with open("JSON1.php", "rb") as f:
    jsonData = json.loads(f.read())

# Now you can use the json as a python dictionary
</code>```

Body:
Please can anyone get me started with the following question?

I get a php file from a website that contains lots of data but I only need some of it. The file is so large I cannot paste it here.

I want to extract the data which is in JSON format and work with it in python.

The file for the example is named JSON1.php. When I open it using a text editor the contents are laid out in this format. Though this is a JSON example I found online.

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

From what I can see it is standard JSON.

What I have been able to google and what I have found here doesn't deal with JSON data saved in a file with .php extention.

Many thanks!

Body:
You can access json from a .php file the same way as a .json file.

Example code:

import json

with open("JSON1.php", "rb") as f:
    jsonData = json.loads(f.read())

# Now you can use the json as a python dictionary


问:
Return a list of similar authors
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

```<code>authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}
</code>```

And the function I came up with is this:

```<code>def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]
</code>```

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

```<code>get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
</code>```

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

答:
I'd use recursion to find similar authors in this fashion.  Come to find out, it is even more inconvenient (and dangerous and slower) to want to return duplicates.

```<code>authors = {'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'], 'Harlan Ellison': ['Neil Stephenson',
           'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'], 'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams',
           'Neil Stephenson', 'Jeff Vandemeer'], 'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'], 'Isaac Asimov':
           ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'], 'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']}

def get_similar(author_list, author, currentList=[]):
    for similar in author_list[author]:
        if similar not in currentList:
            currentList.append(similar)
            if similar in authors:
                get_similar(author_list, author, currentList)
    return sorted(currentList)

print(get_similar(authors, "Harlan Ellison"))
</code>```

Returns:

```<code>['Douglas Adams', 'Kurt Vonnegut', 'Neil Stephenson', 'Richard Morgan']
</code>```

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
I'd use recursion to find similar authors in this fashion.  Come to find out, it is even more inconvenient (and dangerous and slower) to want to return duplicates.

authors = {'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'], 'Harlan Ellison': ['Neil Stephenson',
           'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'], 'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams',
           'Neil Stephenson', 'Jeff Vandemeer'], 'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'], 'Isaac Asimov':
           ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'], 'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']}

def get_similar(author_list, author, currentList=[]):
    for similar in author_list[author]:
        if similar not in currentList:
            currentList.append(similar)
            if similar in authors:
                get_similar(author_list, author, currentList)
    return sorted(currentList)

print(get_similar(authors, "Harlan Ellison"))

Returns:

['Douglas Adams', 'Kurt Vonnegut', 'Neil Stephenson', 'Richard Morgan']


问:
Using MySQL Connector/NET with NHibernate web application
I have an IIS server with MySQL Connector/NET version 6.2.3 installed on it. I'm using NHibernate, and I'm not entirely sure how to set up my web application to use this driver. Am I correct in saying that I can use any version of the .NET connector so long as it's referenced by the application? If so, where/how do I reference the driver in Web.config?

I initially was using version 6.3.6, which had an installer and didn't require me to add any references in my project. However, upon deploying to the server, I discovered that the version installed there was 6.2.3, which gave this error:

Unable to find the requested .Net Framework Data Provider.  It may not be installed.

答: I figured it out. Just needed to set providerName to MySql.Data.MySqlClient in connectionStrings.


问:
convert SOAP to REST and return many records from a function
Convert working SOAP WCF to REST and still use Function that reads and returns the values I need.

ActiveCallSevice reads entity to return several records using SOAP in VB.  How can I code it to return all the records when changing to REST? I have tried many different versions of the uriTemplate but nothing is working. I basically should read a view and return the data without getting any parms from uri.  I used good example from here, but that one is manually coding value returned from looping and I have a Function that reads and returns the values I need.

My IActiveCalls.vb code current on WebGet line - error states - Constant expression is required.    C:\inetpub\VS2013\wcfWazeP1\IActiveCalls.vb 10  13  WcfWazeP1.

```<code>Public Interface IActiveCalls

Property UriTemplate As String

<WebGet(UriTemplate = "Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)")>
<OperationContract()>
Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)

Implements IActiveCalls
Dim dbP1RDW As New ReportingDWEntities

Public Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents) Implements IActiveCalls.GetWazeCalls
    Return dbP1RDW.DIT_CurrentSOTrafficIncidents.OrderBy(Function(o) o.IncidentDate).ToList()
End Function

<DataContract()>
Public Class ActiveCalls

End Class
</code>```

My ActiveCalls.vb code on Implement line – error states -Class 'ActiveCallsService' must implement 'Property UriTemplate As String' for interface 'IActiveCalls'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers.    C:\inetpub\VS2013\wcfWazeP1\ActiveCalls.vb  9   16  WcfWazeP1.

```<code>Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text

Public Class ActiveCallsService
    Implements IActiveCalls
    Dim dbP1RDW As New ReportingDWEntities

    Public Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents) Implements IActiveCalls.GetWazeCalls
        Return dbP1RDW.DIT_CurrentSOTrafficIncidents.OrderBy(Function(o) o.IncidentDate).ToList()
    End Function
End Class
</code>```

12/07/2017 Thanks GMan80013, After changes. Still have errors that prevent it from running.  I tried several placements of the UriTemplate declaration with no luck.  How important is the name of the UriTemplate? Could I call it anything, or should it reference the ActiveCallsService? Sorry to be so uninformed.
ActiveCalls.vb two errors
1- Field or property 'UriTemplate' is not found.    C:\inetpub\VS2013\wcfWazeP1\IActiveCalls.vbWcfWazeP1
2- 'WebGetAttribute' cannot be used as an attribute because it does not inherit from 'System.Attribute'.    C:\inetpub\VS2013\wcfWazeP1\IActiveCalls.vb

    Public Interface IActiveCalls

```<code>    Property UriTemplate As String

    <WebGet(UriTemplate:="currentSOTrafficeIncidents")>
    <OperationContract()>
    Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)

End Interface
</code>```

ActiveCalls.vb – I added the Public Property UriTemplate and no errors here
    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Runtime.Serialization
    Imports System.ServiceModel
    Imports System.Text

```<code>Public Class ActiveCallsService
    Implements IActiveCalls
    Dim dbP1RDW As New ReportingDWEntities
    Public Property UriTemplate As String Implements IActiveCalls.UriTemplate

    Public Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)
    Implements IActiveCalls.GetWazeCalls
    Return dbP1RDW.DIT_CurrentSOTrafficIncidents.OrderBy(Function(o)
o.IncidentDate).ToList()
    End Function
End Class
</code>```

答:
1) The URI Template value is meant to represent the part of the URL after the host name.  If your site address is http://www.myhouse.com/ and you want clients to get all records with this address http://www.myhouse.com/currentSOTrafficIncidents Then "currentSOTrafficIncidents" is the URI Template.  Also, possibly the cause of the error, be sure after UriTemplate you have := not just =.  This is required in vb any time you are specifying the parameter name.

```<code><WebGet(UriTemplate:= "currentSOTrafficIncidents")>
<OperationContract()>
Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)
</code>```

2) In your interface you declared Property UriTemplate As String and this public property is missing from the ActiveCalls.vb class.  I don't think you need this, however and could remove it from the IActiveCalls class.  If you really want to keep it there, correct the error by adding this to ActiveCalls.vb.

```<code>Public Property UriTemplate As String Implements IActiveCalls.UriTemplate
</code>```

Body:
Convert working SOAP WCF to REST and still use Function that reads and returns the values I need.

ActiveCallSevice reads entity to return several records using SOAP in VB.  How can I code it to return all the records when changing to REST? I have tried many different versions of the uriTemplate but nothing is working. I basically should read a view and return the data without getting any parms from uri.  I used good example from here, but that one is manually coding value returned from looping and I have a Function that reads and returns the values I need.

My IActiveCalls.vb code current on WebGet line - error states - Constant expression is required.    C:\inetpub\VS2013\wcfWazeP1\IActiveCalls.vb 10  13  WcfWazeP1.

Public Interface IActiveCalls

Property UriTemplate As String

<WebGet(UriTemplate = "Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)")>
<OperationContract()>
Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)

Implements IActiveCalls
Dim dbP1RDW As New ReportingDWEntities

Public Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents) Implements IActiveCalls.GetWazeCalls
    Return dbP1RDW.DIT_CurrentSOTrafficIncidents.OrderBy(Function(o) o.IncidentDate).ToList()
End Function

<DataContract()>
Public Class ActiveCalls

End Class

My ActiveCalls.vb code on Implement line – error states -Class 'ActiveCallsService' must implement 'Property UriTemplate As String' for interface 'IActiveCalls'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers.    C:\inetpub\VS2013\wcfWazeP1\ActiveCalls.vb  9   16  WcfWazeP1.

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text

Public Class ActiveCallsService
    Implements IActiveCalls
    Dim dbP1RDW As New ReportingDWEntities

    Public Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents) Implements IActiveCalls.GetWazeCalls
        Return dbP1RDW.DIT_CurrentSOTrafficIncidents.OrderBy(Function(o) o.IncidentDate).ToList()
    End Function
End Class

12/07/2017 Thanks GMan80013, After changes. Still have errors that prevent it from running.  I tried several placements of the UriTemplate declaration with no luck.  How important is the name of the UriTemplate? Could I call it anything, or should it reference the ActiveCallsService? Sorry to be so uninformed.
ActiveCalls.vb two errors
1- Field or property 'UriTemplate' is not found.    C:\inetpub\VS2013\wcfWazeP1\IActiveCalls.vbWcfWazeP1
2- 'WebGetAttribute' cannot be used as an attribute because it does not inherit from 'System.Attribute'.    C:\inetpub\VS2013\wcfWazeP1\IActiveCalls.vb

    Public Interface IActiveCalls

    Property UriTemplate As String

    <WebGet(UriTemplate:="currentSOTrafficeIncidents")>
    <OperationContract()>
    Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)

End Interface

ActiveCalls.vb – I added the Public Property UriTemplate and no errors here
    Imports System
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Runtime.Serialization
    Imports System.ServiceModel
    Imports System.Text

Public Class ActiveCallsService
    Implements IActiveCalls
    Dim dbP1RDW As New ReportingDWEntities
    Public Property UriTemplate As String Implements IActiveCalls.UriTemplate

    Public Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)
    Implements IActiveCalls.GetWazeCalls
    Return dbP1RDW.DIT_CurrentSOTrafficIncidents.OrderBy(Function(o)
o.IncidentDate).ToList()
    End Function
End Class

Body:
1) The URI Template value is meant to represent the part of the URL after the host name.  If your site address is http://www.myhouse.com/ and you want clients to get all records with this address http://www.myhouse.com/currentSOTrafficIncidents Then "currentSOTrafficIncidents" is the URI Template.  Also, possibly the cause of the error, be sure after UriTemplate you have := not just =.  This is required in vb any time you are specifying the parameter name.

<WebGet(UriTemplate:= "currentSOTrafficIncidents")>
<OperationContract()>
Function GetWazeCalls() As List(Of DIT_CurrentSOTrafficIncidents)

2) In your interface you declared Property UriTemplate As String and this public property is missing from the ActiveCalls.vb class.  I don't think you need this, however and could remove it from the IActiveCalls class.  If you really want to keep it there, correct the error by adding this to ActiveCalls.vb.

Public Property UriTemplate As String Implements IActiveCalls.UriTemplate


问:
How to view Apple Watch Crash logs on device (without Xcode)
This link discusses how to obtain crash reports on the iPhone, but I'm unclear once I get to the Analytics data (1) what I'm looking at and (2) specifically I'm trying to trace down the cause of a recent crash of my Apple Watch app, how can I locate this information? </p>

答: After some digging, going to Xcode -> Devices and Simulators -> View Device Logs... lists iPhone as well as watch crashes in an easy to read format.  </p>


问:
Opening spinner by clicking on EditText
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

```<code>    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });
</code>```

Layout:

```<code><EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />
</code>```

答:
You can achieve what you want by this:

Add this in your xml instead of edittext and spinner

```<code><AutoCompleteTextView
   android:id="@+id/gender_list"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="65dp"
   android:ems="10"
   android:editable="false" >
</code>```

and this in your java code

```<code>ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                 android.R.layout.simple_dropdown_item_1line, GENDERLIST);
         AutoCompleteTextView textView = (AutoCompleteTextView)
                 findViewById(R.id.gender_list);
         textView.setAdapter(adapter);
textView.setOnTouchListener(new OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            // TODO Auto-generated method stub
            textView.showDropDown();
            textView.requestFocus();
            return false;
        }
    });
</code>```

Title: Opening spinner by clicking on EditText

Body:
Sorry to bother you guys, but I've been strangling to get this to work.

What I want it to do:

EditText to display hint.

User clicks on EditText, opens spinner and selects their sex. That then get's turned into a string and put inside the EditText(gender)

What it is actually doing:
"Male" the first element in my spinner is already put inside my EditText before the user even clicks on it.(I never see my hint: "Sex")....and the spinner won't open at all when I try clicking on the EditText(gender)

What's going on?

My code:

    private Spinner sexSpinner;
    String[] arrayForSpinner = {"Male", "Female"};

    //Inside OnCreate method:
    sexSpinner = (Spinner)findViewById(R.id.spinner);
    adapter = new ArrayAdapter<String>(this, R.layout.spinner_row, arrayForSpinner);
    sexSpinner.setAdapter(adapter);

sexSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
            gender.setText(sexSpinner.getSelectedItem().toString());

        }

gender.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View arg0, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                sexSpinner.performClick();
            }
        }
    });

Layout:

<EditText
        android:layout_width="75dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:focusable="false"
        android:longClickable="false"
        android:clickable="true"
        android:inputType="date"
        android:maxLines="1"
        android:singleLine="true"
        android:hint="Gender"
        android:textColorHint="@color/white"
        android:textColor="@color/white"
        android:ems="10"
        android:id="@+id/signup_input_gender"
        android:layout_below="@+id/signup_input_birthday"
        android:layout_centerHorizontal="true"
        android:backgroundTint="@android:color/white"/>

<Spinner
        android:background="@color/Blue"
        android:id="@+id/spinner"
        android:paddingLeft="0dp"
        android:layout_width="75dp"
        android:layout_height="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="6dp"
        android:layout_below="@+id/linearlayout"
        android:visibility="invisible" />

Body:
You can achieve what you want by this:

Add this in your xml instead of edittext and spinner

<AutoCompleteTextView
   android:id="@+id/gender_list"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="65dp"
   android:ems="10"
   android:editable="false" >

and this in your java code

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                 android.R.layout.simple_dropdown_item_1line, GENDERLIST);
         AutoCompleteTextView textView = (AutoCompleteTextView)
                 findViewById(R.id.gender_list);
         textView.setAdapter(adapter);
textView.setOnTouchListener(new OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
            // TODO Auto-generated method stub
            textView.showDropDown();
            textView.requestFocus();
            return false;
        }
    });


问:
How To Get Total Value Of Inputs With Vanilla Javascript?
I'm trying to get the total amount from input value with pure JavaScript but It's returning blank. The format of the amount value for each input is as follow 0.00

PHP

```<code>//rest of code
$i = 0;
while ($row = mysqli_fetch_array($result)) {$i++;
    <input id="Amount'.$i.'"  name="Amount" value="'.$plan['price'].'" type="text">
}

echo ' <input id="total"  name="finalResult" value="" type="text">';
</code>```

JS

```<code>function totalResult(){
    var arr = document.getElementsByName('Amount');
    var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            total += parseInt(arr[i].value);
    }
    document.getElementById('total').value = total;
}
</code>```

答:
Use HTML5's query selctor API querySelectorAll() like the following:

function totalResult(){
    var arr = document.querySelectorAll('input[name=Amount]');
    var total=0;
    arr.forEach(function(item){
      if(parseInt(item.value))
            total += parseInt(item.value);
    });
    document.getElementById('total').value = parseFloat(total).toFixed(2);
}
totalResult();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="Amount1"  name="Amount" value="10.00" type="text" />
<input id="Amount2"  name="Amount" value="20.00" type="text" />
<input id="Amount3"  name="Amount" value="30.00" type="text" /><br>
Result:
<input id="total"  name="finalResult" value="" type="text"></code>```

Body:
I'm trying to get the total amount from input value with pure JavaScript but It's returning blank. The format of the amount value for each input is as follow 0.00

PHP

//rest of code
$i = 0;
while ($row = mysqli_fetch_array($result)) {$i++;
    <input id="Amount'.$i.'"  name="Amount" value="'.$plan['price'].'" type="text">
}

echo ' <input id="total"  name="finalResult" value="" type="text">';

JS

function totalResult(){
    var arr = document.getElementsByName('Amount');
    var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            total += parseInt(arr[i].value);
    }
    document.getElementById('total').value = total;
}

Body:
Use HTML5's query selctor API querySelectorAll() like the following:

function totalResult(){
    var arr = document.querySelectorAll('input[name=Amount]');
    var total=0;
    arr.forEach(function(item){
      if(parseInt(item.value))
            total += parseInt(item.value);
    });
    document.getElementById('total').value = parseFloat(total).toFixed(2);
}
totalResult();

<input id="Amount1"  name="Amount" value="10.00" type="text" />
<input id="Amount2"  name="Amount" value="20.00" type="text" />
<input id="Amount3"  name="Amount" value="30.00" type="text" /><br>
Result:
<input id="total"  name="finalResult" value="" type="text">


问:
Quote only the required columns using pandas to_csv
I need to generate a csv using pandas to_csv function. I tried quote=csv.QUOTE_NONNUMERIC. But for one of the date time column I dont need double quotes.

Is there a way to select the columns for which we want double quotes?

答:
Thanks people. I got the answer so just thought to share.

First I got the list of headers to be quoted and looped them something like below:

```<code>for col in quoteColumnsList:
    df[col] = '"' + df[col] + '"'
</code>```

Here my quotechar is '"'. Now I used to_csv with quote parameter as csv.QUOTE_NONE. This way we get the double quotes only to the required columns.

Body:
Thanks people. I got the answer so just thought to share.

First I got the list of headers to be quoted and looped them something like below:

for col in quoteColumnsList:
    df[col] = '"' + df[col] + '"'

Here my quotechar is '"'. Now I used to_csv with quote parameter as csv.QUOTE_NONE. This way we get the double quotes only to the required columns.


问:
Angular 2 Display issues with ngIf inside ngFor
Has anyone seen display issues while nesting either ngSwitch/ngIf directives inside ngFor in angular 2?

```<code><ng-container *ngIf="allowedActions">
  <button *ngFor="let action of displayActions(row)" mat-menu-item>
    <ng-container *ngIf="action === 'publish'">
      <i class="material-icons md-24">mdi-publish</i> Publish Collection
    </ng-container>
    <ng-container *ngIf="action === 'security'">
      <i class="material-icons md-24">mdi-security</i> Collection Security
    </ng-container>
  </button>
</ng-container>
</code>```

is displaying like:

console output

答:
I think this is not about Angular but material-icons.

Try removing mdi- in mdi-publish as the following codes.

```<code><ng-container *ngIf="allowedActions">
   <button *ngFor="let action of displayActions(row)" mat-menu-item>
   <ng-container *ngIf="action === 'publish'">
     <i class="material-icons md-24">publish</i> Publish Collection
   </ng-container>
   <ng-container *ngIf="action === 'security'">
     <i class="material-icons md-24">security</i> Collection Security
   </ng-container>
 </button>
</ng-container>
</code>```

Will results like this

Reference on https://material.io

Body:
Has anyone seen display issues while nesting either ngSwitch/ngIf directives inside ngFor in angular 2?

<ng-container *ngIf="allowedActions">
  <button *ngFor="let action of displayActions(row)" mat-menu-item>
    <ng-container *ngIf="action === 'publish'">
      mdi-publish Publish Collection
    </ng-container>
    <ng-container *ngIf="action === 'security'">
      mdi-security Collection Security
    </ng-container>
  </button>
</ng-container>

is displaying like:

console output

Body:
I think this is not about Angular but material-icons.

Try removing mdi- in <i class="material-icons md-24">mdi-publish</i> as the following codes.

<ng-container *ngIf="allowedActions">
   <button *ngFor="let action of displayActions(row)" mat-menu-item>
   <ng-container *ngIf="action === 'publish'">
     <i class="material-icons md-24">publish</i> Publish Collection
   </ng-container>
   <ng-container *ngIf="action === 'security'">
     <i class="material-icons md-24">security</i> Collection Security
   </ng-container>
 </button>
</ng-container>

Will results like this

Reference on https://material.io


问:
Element UI - Table with nested data - How to loop a property
I'm using last version of vue-js and element-ui whose documentation can be found here.

Context

I want to display a table containing some information about  interested and attending people for a given date and room

Issue

I do not manage to display the attending and interested for each room and for each date.

The main problem is how to loop through each room

https://jsfiddle.net/k7Lzv38b/

Data

```<code>tableData: [{
        date: 'Jan 2017',
        rooms: [{
          name: 'Room A',
          attending: 10,
          interested: 5
        }, {
          name: 'Room B',
          attending: 10,
          interested: 0
        }]
      }, {
        date: 'Feb 2017',
        rooms: [{
          name: 'Room A',
          attending: 10,
          interested: 5
        }, {
          name: 'Room B',
          attending: 10,
          interested: 0
        }]
      }]
</code>```

答:
var Main = {
  data() {
    return {
      tableData: [{
        date: 'Jan 2017',
        rooms: [{
          name: 'Room A',
          attending: 10,
          interested: 5
        }, {
          name: 'Room B',
          attending: 5,
          interested: 10
        }]
      }, {
        date: 'Feb 2017',
        rooms: [{
          name: 'Room A',
          attending: 0,
          interested: 5
        }, {
          name: 'Room B',
          attending: 5,
          interested: 15
        }]
      }, {
        date: 'Mar 2017',
        rooms: [{
          name: 'Room B',
          attending: 5
        }]
      }]
    }
  },
  computed: {
    rooms() {
      let rooms = {}
      this.tableData.forEach(row => {
        row.rooms.forEach(room => {
          rooms[room.name] = 1
        })
      })
      return Object.keys(rooms)
    }
  },
  methods: {
    cellFormatter(row, col) {
      let key = JSON.parse(col.property)
      let d = row.rooms.find(r => r.name === key.room)
      if (d && d[key.property]) {
        return d[key.property]
      }
      return '0 '
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("//unpkg.com/element-ui@2.0.5/lib/theme-chalk/index.css");
.container {
  display: flex;
}</code>```

  <template>

      <el-table :data="tableData">
        <el-table-column prop="date" label="Date" align="center"></el-table-column>
        <el-table-column label="Rooms" align="center">
          <el-table-column :label="room" prop="rooms" align="center" v-for="room in rooms" key="room">
            <el-table-column label="Attending" :prop="JSON.stringify({room, property:'attending'})" align="center" :formatter="cellFormatter">
            </el-table-column>
            <el-table-column label="Intereted" :prop="JSON.stringify({room, property:'interested'})" align="center" :formatter="cellFormatter">
            </el-table-column>
          </el-table-column>
        </el-table-column>
      </el-table>

  </template>

```

Body:
I'm using last version of vue-js and element-ui whose documentation can be found here.

Context

I want to display a table containing some information about  interested and attending people for a given date and room

Issue

I do not manage to display the attending and interested for each room and for each date.

The main problem is how to loop through each room

https://jsfiddle.net/k7Lzv38b/

Data

tableData: [{
        date: 'Jan 2017',
        rooms: [{
          name: 'Room A',
          attending: 10,
          interested: 5
        }, {
          name: 'Room B',
          attending: 10,
          interested: 0
        }]
      }, {
        date: 'Feb 2017',
        rooms: [{
          name: 'Room A',
          attending: 10,
          interested: 5
        }, {
          name: 'Room B',
          attending: 10,
          interested: 0
        }]
      }]

Body:
var Main = {
  data() {
    return {
      tableData: [{
        date: 'Jan 2017',
        rooms: [{
          name: 'Room A',
          attending: 10,
          interested: 5
        }, {
          name: 'Room B',
          attending: 5,
          interested: 10
        }]
      }, {
        date: 'Feb 2017',
        rooms: [{
          name: 'Room A',
          attending: 0,
          interested: 5
        }, {
          name: 'Room B',
          attending: 5,
          interested: 15
        }]
      }, {
        date: 'Mar 2017',
        rooms: [{
          name: 'Room B',
          attending: 5
        }]
      }]
    }
  },
  computed: {
    rooms() {
      let rooms = {}
      this.tableData.forEach(row => {
        row.rooms.forEach(room => {
          rooms[room.name] = 1
        })
      })
      return Object.keys(rooms)
    }
  },
  methods: {
    cellFormatter(row, col) {
      let key = JSON.parse(col.property)
      let d = row.rooms.find(r => r.name === key.room)
      if (d && d[key.property]) {
        return d[key.property]
      }
      return '0 '
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

@import url("//unpkg.com/element-ui@2.0.5/lib/theme-chalk/index.css");
.container {
  display: flex;
}

<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.0.5/lib/index.js"></script>
<div id="app">
  <template>
    <div class='container'>
      <el-table :data="tableData">
        <el-table-column prop="date" label="Date" align="center"></el-table-column>
        <el-table-column label="Rooms" align="center">
          <el-table-column :label="room" prop="rooms" align="center" v-for="room in rooms" key="room">
            <el-table-column label="Attending" :prop="JSON.stringify({room, property:'attending'})" align="center" :formatter="cellFormatter">
            </el-table-column>
            <el-table-column label="Intereted" :prop="JSON.stringify({room, property:'interested'})" align="center" :formatter="cellFormatter">
            </el-table-column>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </template>
</div>


问:
How would I make my scrollable buttons display what the user types in search bar?
Inside the onPostExecute() method inside GetNearbyPlacesData.java, List<HashMap<String, String>> nearbyPlacesList = null; is what will store all the searches that the user types in following by hitting SEARCH.

I would like to display what the user types into the search bar onto the scrollable buttons.  For example, if the user types in "pizza", then pizza should appear on those buttons.

How would I make this happen?  I'm guessing the line that says android:text="something"'s on all <Button's inside the activity_maps.xml file should have a dynamic approach.  But how would I go about doing that?

Here's GetNearbyPlacesData.java:

```<code>import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

    String googlePlacesData;
    GoogleMap mMap;
    String url;

    @Override
    protected void onPostExecute(String result) {

        Log.d("GooglePlacesReadTask", "onPostExecute Entered");

        // goes in here whatever you search

        List<HashMap<String, String>> nearbyPlacesList = null;

        DataParser dataParser = new DataParser();

        nearbyPlacesList =  dataParser.parse(result);

        saveNearbyPlaces(nearbyPlacesList);

        ShowNearbyPlaces(nearbyPlacesList);

        Log.d("GooglePlacesReadTask", "onPostExecute Exit");
    }

    private void saveNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList){

        DatabaseReference myRootDBref = FirebaseDatabase.getInstance().getReference();

        for (int i = 0; i < nearbyPlacesList.size(); i++){

            Log.d("onPostExecute","Saving location " + i );

            Map<String, String> values = new HashMap<>();

            Map<String, String> waittime = new HashMap<>();

            //dummy waittime
            waittime.put("Waittime" , "10" );

            values = nearbyPlacesList.get(i);

            //an if statement should encapsulate the creation of new entry store
            //if(values.get("vicinity") !=  myRootDBref.child(values.get("vicinity")).getKey() )
              //  if(values.get("place_name") != myRootDBref.child(values.get("vicinity")).child(values.get("place_name")).getKey())
                    myRootDBref.child(values.get("place_name")).child(values.get("vicinity")).child("10").child("waitime").push().setValue(waittime);
        }

    };

    private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {

        DatabaseReference myRootDBref = FirebaseDatabase.getInstance().getReference();

        for (int i = 0; i < nearbyPlacesList.size(); i++) {

            Log.d("onPostExecute","Entered into showing locations");

            final MarkerOptions markerOptions = new MarkerOptions();

            final HashMap<String, String> googlePlace = nearbyPlacesList.get(i);

            double lat = Double.parseDouble(googlePlace.get("lat"));

            double lng = Double.parseDouble(googlePlace.get("lng"));

            final String placeName = googlePlace.get("place_name");

            final String vicinity = googlePlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            markerOptions.position(latLng);

            //The wait time will need to go inside parenthesis
            markerOptions.title(placeName + " : " + vicinity
                    /* myRootDBref.child(googlePlace.get("vicinity")).child(googlePlace.get("place_name")).toString()*/ );

            mMap.addMarker(markerOptions);

            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

            //move map camera

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

            mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        }
    }
}
</code>```

Here's activity_maps.xml file:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.mancj.example.MapsActivity">
    </fragment>

    <LinearLayout
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        >

        <EditText
            android:hint="Search"
            android:id="@+id/searchBar"
            android:layout_width="289dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/searchButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:onClick="onSearch"
            android:text="SEARCH" />

    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="480dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="something"
                android:id="@+id/button2" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="something"
                android:id="@+id/button3" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="something"
                android:id="@+id/button4"/>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>
</code>```

答:
You should have a handle on the view somewhere in that class if you can access mMap, if not you would have to pass it through.

Once you have a handle on the layout, just find the parent LinearLayout (by giving it an ID) and write a for loop to produce a button:

```<code>layout = (LinearLayout) findViewById(R.id.searchHistory);

// see comment below
for (int i = 0; i < nearbyPlacesList.size(); i++) {
  Button history = new Button(context);
  history.setText("I am a variable");
  layout.addView(history);
}
</code>```

It also seems like an incredibly messy way to store data in a list of hashmaps. Consider a class. If you need more than this, then you should make your question more specific.

Body:
Inside the onPostExecute() method inside GetNearbyPlacesData.java, List<HashMap<String, String>> nearbyPlacesList = null; is what will store all the searches that the user types in following by hitting SEARCH.

I would like to display what the user types into the search bar onto the scrollable buttons.  For example, if the user types in "pizza", then pizza should appear on those buttons.

How would I make this happen?  I'm guessing the line that says android:text="something"'s on all <Button's inside the activity_maps.xml file should have a dynamic approach.  But how would I go about doing that?

Here's GetNearbyPlacesData.java:

import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

    String googlePlacesData;
    GoogleMap mMap;
    String url;

    @Override
    protected void onPostExecute(String result) {

        Log.d("GooglePlacesReadTask", "onPostExecute Entered");

        // goes in here whatever you search

        List<HashMap<String, String>> nearbyPlacesList = null;

        DataParser dataParser = new DataParser();

        nearbyPlacesList =  dataParser.parse(result);

        saveNearbyPlaces(nearbyPlacesList);

        ShowNearbyPlaces(nearbyPlacesList);

        Log.d("GooglePlacesReadTask", "onPostExecute Exit");
    }

    private void saveNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList){

        DatabaseReference myRootDBref = FirebaseDatabase.getInstance().getReference();

        for (int i = 0; i < nearbyPlacesList.size(); i++){

            Log.d("onPostExecute","Saving location " + i );

            Map<String, String> values = new HashMap<>();

            Map<String, String> waittime = new HashMap<>();

            //dummy waittime
            waittime.put("Waittime" , "10" );

            values = nearbyPlacesList.get(i);

            //an if statement should encapsulate the creation of new entry store
            //if(values.get("vicinity") !=  myRootDBref.child(values.get("vicinity")).getKey() )
              //  if(values.get("place_name") != myRootDBref.child(values.get("vicinity")).child(values.get("place_name")).getKey())
                    myRootDBref.child(values.get("place_name")).child(values.get("vicinity")).child("10").child("waitime").push().setValue(waittime);
        }

    };

    private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {

        DatabaseReference myRootDBref = FirebaseDatabase.getInstance().getReference();

        for (int i = 0; i < nearbyPlacesList.size(); i++) {

            Log.d("onPostExecute","Entered into showing locations");

            final MarkerOptions markerOptions = new MarkerOptions();

            final HashMap<String, String> googlePlace = nearbyPlacesList.get(i);

            double lat = Double.parseDouble(googlePlace.get("lat"));

            double lng = Double.parseDouble(googlePlace.get("lng"));

            final String placeName = googlePlace.get("place_name");

            final String vicinity = googlePlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            markerOptions.position(latLng);

            //The wait time will need to go inside parenthesis
            markerOptions.title(placeName + " : " + vicinity
                    /* myRootDBref.child(googlePlace.get("vicinity")).child(googlePlace.get("place_name")).toString()*/ );

            mMap.addMarker(markerOptions);

            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

            //move map camera

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

            mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        }
    }
}

Here's activity_maps.xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.mancj.example.MapsActivity">
    </fragment>

    <LinearLayout
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        >

        <EditText
            android:hint="Search"
            android:id="@+id/searchBar"
            android:layout_width="289dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/searchButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:onClick="onSearch"
            android:text="SEARCH" />

    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="480dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="something"
                android:id="@+id/button2" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="something"
                android:id="@+id/button3" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:text="something"
                android:id="@+id/button4"/>
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

Body:
You should have a handle on the view somewhere in that class if you can access mMap, if not you would have to pass it through.

Once you have a handle on the layout, just find the parent LinearLayout (by giving it an ID) and write a for loop to produce a button:

layout = (LinearLayout) findViewById(R.id.searchHistory);

// see comment below
for (int i = 0; i < nearbyPlacesList.size(); i++) {
  Button history = new Button(context);
  history.setText("I am a variable");
  layout.addView(history);
}

It also seems like an incredibly messy way to store data in a list of hashmaps. Consider a class. If you need more than this, then you should make your question more specific.


问:
New to Excel-VBA: Run Time Error "91": Object Variable or With block variable not set
I'm new to Excel-VBA so please excuse my ignorance. ;)

I'm actually trying to run a program on the selected sheet from a UserForm.
The program would then get a value from the selected sheet which would import it to a newly created sheet. Sheet18 is a sheet template it will be copied to the new sheet.

This are the codes:

```<code>Private Sub CommandButton1_Click()
UserForm1.Hide
  Dim wsUserSel As Worksheet
  Dim ws As Worksheet
  Dim ExFund As Variant

    On Error Resume Next
    Set wsUserSel = ListBox1.Value
    Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
    On Error GoTo 0
        With wsUserSel
            ExFund = .Cells(107, 4).Value
        End With
        Sheet18.Range("A1:K126").Copy
        ws.Name = InputBox("Please input the name of new worksheet.", ThisWorkbook.Name)
        ws.Activate
        Range("A1").Select
        ActiveSheet.Paste
        ActiveSheet.Cells(29, 2) = ExFund
        ActiveSheet.Cells.EntireColumn.AutoFit
        Application.CutCopyMode = False
End Sub
</code>```

This code returns an error

Run Time Error "91": Object Variable or With block variable not set

because of this part of the code:

```<code>    With wsUserSel
        ExFund = .Cells(107, 4).Value
    End With
</code>```

I have tried putting it inside With or using wsUserSel directly but I can't seem to get it working.

What am I doing wrong?

答:
Your On Error Resume Next statement is masking the error you are getting on the line saying

```<code>Set wsUserSel = ListBox1.Value
</code>```

That line will fail because ListBox1.Value will not be a Worksheet object.  I assume it is a String that specifies which worksheet you want to use.

So change the section saying:

```<code>On Error Resume Next
Set wsUserSel = ListBox1.Value
Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
On Error GoTo 0
</code>```

to be:

```<code>Set wsUserSel = Worksheets(ListBox1.Value)
Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
</code>```

Body:
I'm new to Excel-VBA so please excuse my ignorance. ;)

I'm actually trying to run a program on the selected sheet from a UserForm.
The program would then get a value from the selected sheet which would import it to a newly created sheet. Sheet18 is a sheet template it will be copied to the new sheet.

This are the codes:

Private Sub CommandButton1_Click()
UserForm1.Hide
  Dim wsUserSel As Worksheet
  Dim ws As Worksheet
  Dim ExFund As Variant

    On Error Resume Next
    Set wsUserSel = ListBox1.Value
    Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
    On Error GoTo 0
        With wsUserSel
            ExFund = .Cells(107, 4).Value
        End With
        Sheet18.Range("A1:K126").Copy
        ws.Name = InputBox("Please input the name of new worksheet.", ThisWorkbook.Name)
        ws.Activate
        Range("A1").Select
        ActiveSheet.Paste
        ActiveSheet.Cells(29, 2) = ExFund
        ActiveSheet.Cells.EntireColumn.AutoFit
        Application.CutCopyMode = False
End Sub

This code returns an error

Run Time Error "91": Object Variable or With block variable not set

because of this part of the code:

    With wsUserSel
        ExFund = .Cells(107, 4).Value
    End With

I have tried putting it inside With or using wsUserSel directly but I can't seem to get it working.

What am I doing wrong?

Body:
Your On Error Resume Next statement is masking the error you are getting on the line saying

Set wsUserSel = ListBox1.Value

That line will fail because ListBox1.Value will not be a Worksheet object.  I assume it is a String that specifies which worksheet you want to use.

So change the section saying:

On Error Resume Next
Set wsUserSel = ListBox1.Value
Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
On Error GoTo 0

to be:

Set wsUserSel = Worksheets(ListBox1.Value)
Set ws = Sheets.Add(after:=Sheets(Sheets.Count))


问:
Android Things doesn't grant permissions on boot, what gives?
Got this shiny manifest ready to be granted all ze permissions

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="exm.rand.lol">

  <uses-permission android:name="com.google.android.things.permission.MODIFY_SCREEN_SETTINGS" />
  <uses-permission android:name="com.google.android.things.permission.REBOOT"/>

  <application>
    <uses-library android:name="com.google.android.things" />

    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.IOT_LAUNCHER" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </activity>
  </application>

</manifest>
</code>```

and yet when I boot up the raspberry pi it fails with this in the logcat

```<code>12-01 15:23:19.349  2960  2960 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{exm.rand.lol/exm.rand.lol.MainActivity}: java.lang.SecurityException: Calling process requires permission com.google.android.things.permission.MODIFY_SCREEN_SETTINGS
</code>```

I searched high and low, stumbled upon multiple threads on StackOverflow

Android Things permission com.google.android.things.permission.MANAGE_INPUT_DRIVERS not found

How to request permission on Android Things?

but to no avail. Rebooting doesn't do anything, reinstalling doesn't do anything, the only way I found atm to give permissions is to manually grant them through adb like dis

```<code> adb shell pm grant exm.rand.lol com.google.android.things.permission.REBOOT
</code>```

Running latest Preiew 6 of Android Things.

答:
With Developer Preview 6, you should use the DeviceManager API. Reboot permission can only be granted to system apps if I'm not wrong, and the Android Things console will never package your APK as a system app.</p>

```<code>new DeviceManager().reboot()
</code>```

Body:
Got this shiny manifest ready to be granted all ze permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="exm.rand.lol">

  <uses-permission android:name="com.google.android.things.permission.MODIFY_SCREEN_SETTINGS" />
  <uses-permission android:name="com.google.android.things.permission.REBOOT"/>

  <application>
    <uses-library android:name="com.google.android.things" />

    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.IOT_LAUNCHER" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </activity>
  </application>

</manifest>

and yet when I boot up the raspberry pi it fails with this in the logcat

12-01 15:23:19.349  2960  2960 E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{exm.rand.lol/exm.rand.lol.MainActivity}: java.lang.SecurityException: Calling process requires permission com.google.android.things.permission.MODIFY_SCREEN_SETTINGS

I searched high and low, stumbled upon multiple threads on StackOverflow

Android Things permission com.google.android.things.permission.MANAGE_INPUT_DRIVERS not found

How to request permission on Android Things?

but to no avail. Rebooting doesn't do anything, reinstalling doesn't do anything, the only way I found atm to give permissions is to manually grant them through adb like dis

 adb shell pm grant exm.rand.lol com.google.android.things.permission.REBOOT

Running latest Preiew 6 of Android Things.

Body:
With Developer Preview 6, you should use the DeviceManager API. Reboot permission can only be granted to system apps if I'm not wrong, and the Android Things console will never package your APK as a system app.

new DeviceManager().reboot()


问:
RxJava: How can I start a task and when it has finished start another task?
I'm trying to create a chat applicaction in Android using RxJava. The sequence of events is something like this:

The user writes the message and push "send".

The message object containing (id, message, sender, ...) should be stored in local database first because I need to generate his id and return the message object with the id stablished.

Once the message object has been stored, the id has been set I have to send that message using the proper way.

The problem is that I'm not sure how to program that using RxJava, how can I start a task and when it has finished start another task? I've read about the operators zip, empty, and, when, skipuntil, flatmap, but I'm not sure which I need. I'm pretty new with RxJava.

I have this method:

```<code>public Observable<Boolean> sendMessage(Message message) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<Boolean>()     {
        @Override
        public void call(Subscriber<? super Boolean> subscriber) {
            MessageEntity messageEntity = messageToMessageEntityMapper.map(message);
            messageRepository.saveMessage(messageEntity);
            chatHelper.sendMessage(messageEntity);
            subscriber.onNext(true);
        }
    });
}
</code>```

And the implementations of saveMessage and sendMessage:

```<code>public Observable<MessageEntity> saveMessage(MessageEntity messageEntity) {
    return messageCache.saveMessage(messageEntity);
}

public void sendMessage(MessageEntity messageEntity) {
    chatConnection.sendMessage(message);
}
</code>```

I want that sendMessage execute once saveMessage has finished and returned the expected object.

答:
You can use observable.map to consume the result from first observable and execute the second observable.

```<code>public Observable<Boolean> sendMessage(Message message{
  MessageEntity messageEntity = messageToMessageEntityMapper.map(message);
  return messageRepository.saveMessage(messageEntity)
          .map( updatedMessage -> {
               chatHelper.sendMessage(updatedMessage );
               return Observable.just(true);
           });
 };
</code>```

You can also make sendMessage return a boolean Observable instead of explicitly returning true from the map method.

If there is no need to consume the emitted item from first observable, you can use Observable.merge instead and make sendMessage to return an observable.

Body:
I'm trying to create a chat applicaction in Android using RxJava. The sequence of events is something like this:

The user writes the message and push "send".

The message object containing (id, message, sender, ...) should be stored in local database first because I need to generate his id and return the message object with the id stablished.

Once the message object has been stored, the id has been set I have to send that message using the proper way.

The problem is that I'm not sure how to program that using RxJava, how can I start a task and when it has finished start another task? I've read about the operators zip, empty, and, when, skipuntil, flatmap, but I'm not sure which I need. I'm pretty new with RxJava.

I have this method:

public Observable<Boolean> sendMessage(Message message) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<Boolean>()     {
        @Override
        public void call(Subscriber<? super Boolean> subscriber) {
            MessageEntity messageEntity = messageToMessageEntityMapper.map(message);
            messageRepository.saveMessage(messageEntity);
            chatHelper.sendMessage(messageEntity);
            subscriber.onNext(true);
        }
    });
}

And the implementations of saveMessage and sendMessage:

public Observable<MessageEntity> saveMessage(MessageEntity messageEntity) {
    return messageCache.saveMessage(messageEntity);
}

public void sendMessage(MessageEntity messageEntity) {
    chatConnection.sendMessage(message);
}

I want that sendMessage execute once saveMessage has finished and returned the expected object.

Body:
You can use observable.map to consume the result from first observable and execute the second observable.

public Observable<Boolean> sendMessage(Message message{
  MessageEntity messageEntity = messageToMessageEntityMapper.map(message);
  return messageRepository.saveMessage(messageEntity)
          .map( updatedMessage -> {
               chatHelper.sendMessage(updatedMessage );
               return Observable.just(true);
           });
 };

You can also make sendMessage return a boolean Observable instead of explicitly returning true from the map method.

If there is no need to consume the emitted item from first observable, you can use Observable.merge instead and make sendMessage to return an observable.


问:
while(i) loop in JavaScript
I ran the below code in JavaScript

```<code>let i = 3;
while (i) {
    console.log(i--);
}
</code>```

since the while(i) is not like while(i>0) then I expected the result as 3,2,1,0,-1,-2,...

but the actual result is 3,2,1. Could anyone explain this case to me? I am confused.

答:
While loops run until its condition is set false. Note that all statements such as while, if and ternaries all handle conditions in the same way. To have a better understanding on how the simplest and quickest way is to test them with ternaries.

I usually run something such as the following on a js console such as chrome (ctrl + j)

```<code>1?2:3;
0?2:3;
5?2:3;
"Hello"?2:3;
""?2:3;
</code>```

And so on. These are conditional statements, the first number is taken as a condition, the second (2) is what will be returned if it were true, and the third (3) is what it will return if it were false. Note that 2 and 3 are just random numbers.

In the example you have shown, i is an integer. For an integer, only 0 is taken as a false.

Title: while(i) loop in JavaScript

Body:
I ran the below code in JavaScript

let i = 3;
while (i) {
    console.log(i--);
}

since the while(i) is not like while(i>0) then I expected the result as 3,2,1,0,-1,-2,...

but the actual result is 3,2,1. Could anyone explain this case to me? I am confused.

Body:
While loops run until its condition is set false. Note that all statements such as while, if and ternaries all handle conditions in the same way. To have a better understanding on how the simplest and quickest way is to test them with ternaries.

I usually run something such as the following on a js console such as chrome (ctrl + j)

1?2:3;
0?2:3;
5?2:3;
"Hello"?2:3;
""?2:3;

And so on. These are conditional statements, the first number is taken as a condition, the second (2) is what will be returned if it were true, and the third (3) is what it will return if it were false. Note that 2 and 3 are just random numbers.

In the example you have shown, i is an integer. For an integer, only 0 is taken as a false.


答:
What is happening is that functions only accept one return to fix this, return the full row without iterating</p>

```<code>def get_similar(author_list, author):
     return sorted(author_list[author])
</code>```

Title: Return a list of similar authors

Body:
I'm trying to write a function that will return a list of items from a key from a key (if that makes sense). For example, here's a dictionary of authors, and similar authors.

authors = {
    'Ray Bradbury': ['Harlan Ellison', 'Robert Heinlein', 'Isaac Asimov', 'Arthur Clarke'],
    'Harlan Ellison': ['Neil Stephenson', 'Kurt Vonnegut', 'Richard Morgan', 'Douglas Adams'],
    'Kurt Vonnegut': ['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson', 'Jeff Vandemeer'],
    'Thomas Pynchon': ['Isaac Asimov', 'Jorges Borges', 'Robert Heinlein'],
    'Isaac Asimov': ['Stephen Baxter', 'Ray Bradbury', 'Arthur Clarke', 'Kurt Vonnegut', 'Neil Stephenson'],
    'Douglas Adams': ['Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']
}

And the function I came up with is this:

def get_similar(author_list, author):
    for item in author_list[author]:
        return author_list[author]

Which only returns the items for the first key. I'd like it to return all of the similar authors, like this:

get_similar(authors, 'Harlan Ellison')

['Terry Pratchett', 'Tom Robbins', 'Douglas Adams', 'Neil Stephenson',
 'Jeff Vandemeer','Terry Pratchett', 'Chris Moore', 'Kurt Vonnegut']

Where it finds the key given (author), looks at the items listed for that key, and then returns those key's items. In this case Harlan Ellison has four authors listed - Neil Stephenson, Kurt Vonnegut, Richard Morgan, and Douglas Adams. The function then looks up those authors, and returns the items listed for them - Kurt Vonnegut returns Terry Pratchett, Tom Robbins, Douglas Adams, Neil Stephenson, and Jeff Vandemeer, and Douglas Adams returns Terry Pratchett, Chris Moore, and Kurt Vonnegut,

Duplicates are fine, and I'd like it in alphabetical order (I assume you could just use a sort command at the end) Any help would be much appreciated, I'm stumped!

Body:
What is happening is that functions only accept one return to fix this, return the full row without iterating

def get_similar(author_list, author):
     return sorted(author_list[author])


问:
how do we make user to enter the correct login of the website in android
How do we make a user to enter the correct login of the website in android

I am using shared preferences but it saves only when I enter the values locally.

I am making an app which signs up/ register me on the real website.

But I cannot do it.

Please help me on this

答:
Use FireBase, check this for more info: https://firebase.google.com/docs/auth/android/password-auth.

And here is a nice tutorial: https://www.androidhive.info/2016/06/android-getting-started-firebase-simple-login-registration-auth/


问:
Code golf: combining multiple sorted lists into a single sorted list
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

```<code>input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)
</code>```

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

```<code>sorted(sum(lists,[])) # cheating: out of bounds!
</code>```

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

答:
Python, 181 chars

```<code>from heapq import *
def m(l):
 r=[]
 h=[]
 for x in l:
  if x:
   heappush(h, (x[0], x[1:]))
 while h:
  e,f=heappop(h)
  r.append(e)
  if f:
   heappush(h, (f.pop(0),f))
 return r
</code>```

This runs in O(NlgM) time, where N is the total number of items and M is the number of lists.

OwnerDisplayName: jamesbrady

Body:
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

sorted(sum(lists,[])) # cheating: out of bounds!

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

LastEditorDisplayName: Alabaster Codify

Body:
Python, 181 chars

from heapq import *
def m(l):
 r=[]
 h=[]
 for x in l:
  if x:
   heappush(h, (x[0], x[1:]))
 while h:
  e,f=heappop(h)
  r.append(e)
  if f:
   heappush(h, (f.pop(0),f))
 return r

This runs in O(NlgM) time, where N is the total number of items and M is the number of lists.


问:
How do you use php to communicate with App Inventors TinyWebDB component?
Google App Inventor has some information in their documentation for setting up a sample TinyWebDB webservice using python or app engine, however, I'm trying to use php.  Is this possible?  I've followed directions posted here but all I get is the error:

Communication with the web service
  encountered a protocol exception

I display this error in a label component on the when TinyWebDB1.WebServiceError block.

So here is what I have in my php files:

getvalue.php

```<code>header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 2010 05:00:00 GMT');
header('Content-type: application/json');

$retval = array("VALUE", "tagged", '"'.time().'"');
echo json_encode($retval);
</code>```

Which returns:

["VALUE","tagged","\"1283093117\""]

setvalue.php

```<code>$tag = $_POST['tag'];
$value = $_POST['value'];
$retval = array("STORED", '"'.$tag.'"', '"'.$value.'"');
echo json_encode($retval);
</code>```

Which returns:

["STORED","\"tagged\"","\"testdata\""]

Thanks for any suggestions or answers.

答: Instead of "setvalue", you should use "storeavalue"</p>

Body:
Google App Inventor has some information in their documentation for setting up a sample TinyWebDB webservice using python or app engine, however, I'm trying to use php.  Is this possible?  I've followed directions posted here but all I get is the error:

Communication with the web service
  encountered a protocol exception

I display this error in a label component on the when TinyWebDB1.WebServiceError block.

So here is what I have in my php files:

getvalue.php

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 2010 05:00:00 GMT');
header('Content-type: application/json');

$retval = array("VALUE", "tagged", '"'.time().'"');
echo json_encode($retval);

Which returns:

["VALUE","tagged","\"1283093117\""]

setvalue.php

$tag = $_POST['tag'];
$value = $_POST['value'];
$retval = array("STORED", '"'.$tag.'"', '"'.$value.'"');
echo json_encode($retval);

Which returns:

["STORED","\"tagged\"","\"testdata\""]

Thanks for any suggestions or answers.