问:
Validating XML documents against schemas nested inside wsdl:types
I have XML files that I need to validate against XSDs that are nested inside a <wsdl:types></wsdl:types> in a WSDL file retrieved from a web service.

Inside the <wsdl:types></wsdl:types> there are several <xs:schema>s. I am using the ruby gem nokogiri to load the XML files and validate them against said XSDs, however, I am getting following error when I run the program:

```<code>Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope': No
matching global declaration available for the validation root.
</code>```

So far I have extracted out the <xs:schema>s (all 4 of them) and copied them into a schema.xsd file.

Code:

```<code>require 'rubygems'
require 'nokogiri'

def validate(document_path, schema_path)
  schema = Nokogiri::XML::Schema(File.read(schema_path))
  document = Nokogiri::XML(File.read(document_path))
  schema.validate(document)
end

validate('data.xml', 'schema.xsd').each do |error|
  puts error.message
end
</code>```

So basically my schema.xsd has multiple <xs:schema>s in there, which I do not think in and of itself is a problem because nokogiri didn't throw errors when I instantiated the schema object.

schema.xsd

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/">
  <xs:element name="anyType" nillable="true" type="xs:anyType"/>
  <xs:element name="anyURI" nillable="true" type="xs:anyURI"/>
  <!-- data in here -->
</xs:schema>

<!-- three more xs:schema tags removed for brevity -->
</code>```

data.xml

```<code><?xml version='1.0' ?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Header />
  <env:Body>
    <CreatePerson xmlns="https://person.example.com/">
      <oMessageType xmlns:epa="http://schemas.datacontract.org/2004/07/whatever" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:array="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <person:bodyField>
            <!-- data in here -->
        </person:bodyField>
        <!-- more data in here -->
      </oMessageType>
    </CreatePerson>
  </env:Body>
</env:Envelope>
</code>```

答:
Yes, WSDL not the XSD scheam so you need to extract the schema partial manually or automatic by programming.

Here is the sample code, you need to refactor it and using in your codes.

```<code>str = <<EOF
    <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl">
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/">
          <element name="anyType" nillable="true" type="anyType"/>
          <element name="anyURI" nillable="true" type="anyURI"/>
          <!-- data in here -->
        </schema>
    </types>
    <message name="SayHelloRequest">
        <part name="firstName" type="xsd:string"/>
    </message>
    <message name="SayHelloResponse">
        <part name="greeting" type="xsd:string"/>
    </message>
    <portType name="Hello_PortType">
        <operation name="sayHello">
            <input message="tns:SayHelloRequest"/>
            <output message="tns:SayHelloResponse"/>
        </operation>
    </portType>
    <binding name="Hello_Binding" type="tns:Hello_PortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="sayHello">
            <soap:operation soapAction="sayHello"/>
            <input>
                <soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice"/>
            </input>
            <output>
                <soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice"/>
            </output>
        </operation>
    </binding>
    <service name="Hello_Service">
        <documentation>WSDL File for HelloService</documentation>
        <port name="Hello_Port" binding="tns:Hello_Binding">
            <soap:address location="http://www.examples.com/SayHello/"/>
        </port>
    </service>
</definitions>

EOF

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::XML(str)

doc.root.children.each do |child|
    if child.node_name == 'types'
        types = child
        # p types.inner_html
        xsd_doc = Nokogiri::XML(types.inner_html)

        # p xsd_doc.root

        xsd = Nokogiri::XML::Schema.from_document xsd_doc.root
    end
end
</code>```

Body:
I have XML files that I need to validate against XSDs that are nested inside a <wsdl:types></wsdl:types> in a WSDL file retrieved from a web service.

Inside the <wsdl:types></wsdl:types> there are several <xs:schema>s. I am using the ruby gem nokogiri to load the XML files and validate them against said XSDs, however, I am getting following error when I run the program:

Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope': No
matching global declaration available for the validation root.

So far I have extracted out the <xs:schema>s (all 4 of them) and copied them into a schema.xsd file.

Code:

require 'rubygems'
require 'nokogiri'

def validate(document_path, schema_path)
  schema = Nokogiri::XML::Schema(File.read(schema_path))
  document = Nokogiri::XML(File.read(document_path))
  schema.validate(document)
end

validate('data.xml', 'schema.xsd').each do |error|
  puts error.message
end

So basically my schema.xsd has multiple <xs:schema>s in there, which I do not think in and of itself is a problem because nokogiri didn't throw errors when I instantiated the schema object.

schema.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/">
  <xs:element name="anyType" nillable="true" type="xs:anyType"/>
  <xs:element name="anyURI" nillable="true" type="xs:anyURI"/>

</xs:schema>

data.xml

<?xml version='1.0' ?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Header />
  <env:Body>
    <CreatePerson xmlns="https://person.example.com/">
      <oMessageType xmlns:epa="http://schemas.datacontract.org/2004/07/whatever" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:array="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <person:bodyField>

        </person:bodyField>

      </oMessageType>
    </CreatePerson>
  </env:Body>
</env:Envelope>

Body:
Yes, WSDL not the XSD scheam so you need to extract the schema partial manually or automatic by programming.

Here is the sample code, you need to refactor it and using in your codes.

str = <<EOF
    <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl">
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.microsoft.com/2003/10/Serialization/" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/2003/10/Serialization/">
          <element name="anyType" nillable="true" type="anyType"/>
          <element name="anyURI" nillable="true" type="anyURI"/>
          <!-- data in here -->
        </schema>
    </types>
    <message name="SayHelloRequest">
        <part name="firstName" type="xsd:string"/>
    </message>
    <message name="SayHelloResponse">
        <part name="greeting" type="xsd:string"/>
    </message>
    <portType name="Hello_PortType">
        <operation name="sayHello">
            <input message="tns:SayHelloRequest"/>
            <output message="tns:SayHelloResponse"/>
        </operation>
    </portType>
    <binding name="Hello_Binding" type="tns:Hello_PortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="sayHello">
            <soap:operation soapAction="sayHello"/>
            <input>
                <soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice"/>
            </input>
            <output>
                <soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice"/>
            </output>
        </operation>
    </binding>
    <service name="Hello_Service">
        <documentation>WSDL File for HelloService</documentation>
        <port name="Hello_Port" binding="tns:Hello_Binding">
            <soap:address location="http://www.examples.com/SayHello/"/>
        </port>
    </service>
</definitions>

EOF

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::XML(str)

doc.root.children.each do |child|
    if child.node_name == 'types'
        types = child
        # p types.inner_html
        xsd_doc = Nokogiri::XML(types.inner_html)

        # p xsd_doc.root

        xsd = Nokogiri::XML::Schema.from_document xsd_doc.root
    end
end


来源: stackexchange

问:
TFS 2015 - Task board and kanban board state names
Based on requirements, for user story kanban board, we added following columns

TODO

Development

System Test

Done

In Task dashboard, for given user story, all tasks are in swim lanes accordingly to its state.

States which are shown in task board for user story is not what we have added as customized columns and it shows as

New

Active

Resolved

Remove

Closed

This is confusing for the team, is there any way i can customized this?.

答:
You are customizing the current Kanban board column assignment of the work item, which Reference name=System.BoardColumn. For example the default value is: New, Active,Resolved, Closed in a Agile process.

However states which are shown in task board for user story is using to track the progress of user stories. It's a workflow progression. More details about this, you could refer this tutorial. There are totally different concepts for each other. So, which you got is the expect phenomenon.

ContentLicense: CC BY-SA 3.0


问:
Javascript form automatic calculation
I am trying to create form which automatically alters a text box when the user uses keystrokes .

This fiddle illustrates what I am attempting however I have had no success.

Essentially I want the 3rd text box to show the "Number of People" multiplied by the "Price", how can I do this?

HTML

```<code><form action="postenquiry.php" method="post" name="myform">
    <label>Num of People</label>
    <input type="text" name="qty" />
    <br/>
    <label>Price</label>
    <input type="text" name="Cost" onkeyup="calculate()" />
    <br/>
    <input type="text" name="textbox5" />
</form>
</code>```

Javascript

```<code>function calculate() {
    if (isNaN(document.forms["myform"]["qty"].value) || document.forms["myform"]["qty"].value == "") {
        var text1 = 0;
    } else {
        var text1 = parseInt(document.forms["myform"]["qty"].value);
    }
    if (isNaN(document.forms["myform"]["Cost"].value) || document.forms["myform"]["Cost"].value == "") {
        var text2 = 0;
    } else {
        var text2 = parseFloat(document.forms["myform"]["Cost"].value);
    }
    document.forms["myform"]["textbox5"].value = (text1 * text2);
}
</code>```

http://jsfiddle.net/b87s5hou/

答:
Hai  cool this type of problem i also faced so..i develop a some peace of code which is
used to calculate automatically using text fields .... in this code ..

<form oninput="x.value=parseFloat(a.value)*parseFloat(b.value)">
<input type="number" id="a" value="0">
<input type="number" id="b" value="50"readonly>
<output name="x" for="a b"></output>
</form>

```

Title: Javascript form automatic calculation

Body:
I am trying to create form which automatically alters a text box when the user uses keystrokes .

This fiddle illustrates what I am attempting however I have had no success.

Essentially I want the 3rd text box to show the "Number of People" multiplied by the "Price", how can I do this?

HTML

<form action="postenquiry.php" method="post" name="myform">
    Num of People
    <input type="text" name="qty" />

    Price
    <input type="text" name="Cost" onkeyup="calculate()" />

    <input type="text" name="textbox5" />
</form>

Javascript

function calculate() {
    if (isNaN(document.forms["myform"]["qty"].value) || document.forms["myform"]["qty"].value == "") {
        var text1 = 0;
    } else {
        var text1 = parseInt(document.forms["myform"]["qty"].value);
    }
    if (isNaN(document.forms["myform"]["Cost"].value) || document.forms["myform"]["Cost"].value == "") {
        var text2 = 0;
    } else {
        var text2 = parseFloat(document.forms["myform"]["Cost"].value);
    }
    document.forms["myform"]["textbox5"].value = (text1 * text2);
}

http://jsfiddle.net/b87s5hou/

Body:
Hai  cool this type of problem i also faced so..i develop a some peace of code which is
used to calculate automatically using text fields .... in this code ..

 <html>
<body>
<form oninput="x.value=parseFloat(a.value)*parseFloat(b.value)">
<input type="number" id="a" value="0">
<input type="number" id="b" value="50"readonly>
<output name="x" for="a b"></output>
</form>
</body>
</html>


问:
Is Firebase now mandatory for use of Google Analytics Mobile Properties?
Is Firebase now required for setting up Google Analytics for Mobile?  In the past, when I've setup Google Analytics for Mobile, I've selected "Mobile" from the Create New Property view and gotten the standard Analytics key (e.g., "UA-BLAHBLAH-BL").  However, when I went to setup a new property today, that is not what is happening.  Instead, I am seeing this:

It appears that there is now no way to use the traditional Google Analytics SDK for new properties using the analytics key of olde.

Am I correct in this deduction?  Or is there some other way to setup a new Mobile property with an analytics key of the past that I have missed?

答:
Google have published instructions on how to set up a new mobile property using the Google Analytics Services SDK.

You can find them in Google Support, Analytics Help as Analytics for mobile apps.

ContentLicense: CC BY-SA 4.0


问:
Using insert() on empty std::vector when sorting
I know ideally to add to a std::vector without worry I should use push_back(). However my problem set is that I need a clean code to check if the value I am entering is already in the std::vector and if not, I have to put in sequential, ascending order. To do that I am doing:

```<code>vector<Book>::iterator it;
it = std::find(books.begin(), books.end(), b);
if (it != books.end()) {
    *it = b; // if b exists in books, overwrite the iterator
}
else {
    vector<Book>::iterator _it;
    _it = lower_bound(books.begin(), books.end(), b);
    books.insert(_it, b); // here on an empty vector, _it has no values
}
</code>```

The else will only run if the value b doesnt already exist in the std::vector. If this is the first value being checked against it, the else runs (since its empty) and the std::iterator is at books[0](?).

What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to. Now the program functions and yields anticipated results, but is it erroneously?

答:
It is all well defined behavior.

lower_bound will return the end iterator (books.end() in your case) for an empty range or if b should come after the last element.  insert will add the new element before the iterator passed to it, so this will be before end.  In an empty vector, this will have the effect of adding the element to the vector.

Body:
I know ideally to add to a std::vector without worry I should use push_back(). However my problem set is that I need a clean code to check if the value I am entering is already in the std::vector and if not, I have to put in sequential, ascending order. To do that I am doing:

vector<Book>::iterator it;
it = std::find(books.begin(), books.end(), b);
if (it != books.end()) {
    *it = b; // if b exists in books, overwrite the iterator
}
else {
    vector<Book>::iterator _it;
    _it = lower_bound(books.begin(), books.end(), b);
    books.insert(_it, b); // here on an empty vector, _it has no values
}

The else will only run if the value b doesnt already exist in the std::vector. If this is the first value being checked against it, the else runs (since its empty) and the std::iterator is at books[0](?).

What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to. Now the program functions and yields anticipated results, but is it erroneously?


问:
Javascript in HTML not calling correctly
I'm trying to create a simple website using basic java script but I think i'm not able to call to the file correctly have tried multiple sources online but to no success. Can you have a look at my code and tell me what's wrong ?

html:

```<code><html>
<head>
<script src="js/js1.js" type="text/javascript"></script>
</head>
The total number of square feet in your house is:<br>
<script src="js/js1.js">test()</script>square feet.
</code>```

js:

```<code>function test() {
    var test = 15;
    document.write(test);
    return test;
}
</code>```

答:
I think you have put an > after test() for which there is an Uncaught SyntaxError: Unexpected end of input

square feet.

The total number of square feet in your house is:

 square feet.```

Body:
I'm trying to create a simple website using basic java script but I think i'm not able to call to the file correctly have tried multiple sources online but to no success. Can you have a look at my code and tell me what's wrong ?

html:

The total number of square feet in your house is:

square feet.

js:

function test() {
    var test = 15;
    document.write(test);
    return test;
}

Body:
I think you have put an > after test() for which there is an Uncaught SyntaxError: Unexpected end of input

<script src="js/js1.js">test()></script>square feet.

<head>
<script>
function test() {
    var test = 15;
    document.write(test);
    return test;
}
</script>
</head>
<body>
The total number of square feet in your house is:<br>
<script>test()</script> square feet.


问:
Install Java 8 in debian Jessie
I've tried to install Java 8 into a ARM embedded linux in several ways but none of them worked:

First:
http://www.webupd8.org/2014/03/how-to-install-oracle-java-8-in-debian.html

(from the repositories of webupd8)

W: Failed to fetch
  http://ppa.launchpad.net/webupd8team/java/ubuntu/dists/trusty/InRelease
  Unable to find expected entry 'main/binary-armel/Packages' in Release
  file (Wrong sources.list entry or malformed file)

W: Failed to fetch
  http://ppa.launchpad.net/webupd8team/java/ubuntu/dists/jessie/main/binary-armel/Packages
  404  Not Found

E: Some index files failed to download. They have been ignored, or old
  ones used instead.

It seems that this repo does not have the source for my architecture:

Architectures: amd64 arm64 armhf i386 powerpc ppc64el

And i need armel ( at least this is working for java 7 )

I also tried this way:
http://www.rpiblog.com/2014/03/installing-oracle-jdk-8-on-raspberry-pi.html

Downloading the jdk from Oracle and then following the instructions.

But i cannot execute the file :

root@arietta:~# java -version
  -bash: /usr/bin/java: No such file or directory

and neither:

root@arietta:~# /opt/jdk1.8.0_71/bin/java -version
  -bash: /usr/bin/java: No such file or directory

While the file exists and has the correct permissions... i'm going crazy..

Any idea or alternative method?

答:
I ran the following commands from the webupd8 team and it worked for me:
http://www.webupd8.org/2014/03/how-to-install-oracle-java-8-in-debian.html</p>

```<code>su -
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java8-installer
exit
</code>```

Title: Install Java 8 in debian Jessie

Body:
I ran the following commands from the webupd8 team and it worked for me:
http://www.webupd8.org/2014/03/how-to-install-oracle-java-8-in-debian.html

su -
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java8-installer
exit


问:
Is there a way to select on a value attached by .data()?
Background: I'm performing an upgrade on an existing photo gallery plug-in which displays a large image in the center and progressively smaller images off to either side.

So my question is this:  I'm setting some data on each image that gives the image's index, the index of the next image, and the index of the previous image, like so:

```<code>$(this).data('index', i).data('prev', i - 1).data('next', i + 1);
</code>```

Later on, I'd like to be able to select an image based on its index.  I've tried the following, but it doesn't seem to work:

```<code>$('[data-index=' + index + ']');
</code>```

Is there a way to select an element based on a piece of data attached with .data()?

答:
You can use .filter(), like this:

```<code>$('*').filter(function() { return $.data(this, 'index') == index; })
</code>```

However, * is very expensive, as it runs this filter on all elements, please use a more specific selector to start with.

ContentLicense: CC BY-SA 2.5

Body:
Background: I'm performing an upgrade on an existing photo gallery plug-in which displays a large image in the center and progressively smaller images off to either side.

So my question is this:  I'm setting some data on each image that gives the image's index, the index of the next image, and the index of the previous image, like so:

$(this).data('index', i).data('prev', i - 1).data('next', i + 1);

Later on, I'd like to be able to select an image based on its index.  I've tried the following, but it doesn't seem to work:

$('[data-index=' + index + ']');

Is there a way to select an element based on a piece of data attached with .data()?

Body:
You can use .filter(), like this:

$('*').filter(function() { return $.data(this, 'index') == index; })

However, * is very expensive, as it runs this filter on all elements, please use a more specific selector to start with.


问:
Can you customize the auth0 login screen in xamarin app
I have a xamarin app that is utilizing auth0 for auth purposes. But I see for web version you can pass different options for theming the login page appearance. Is that also possible in a xamarin app.</p>

```<code> client = new Auth0Client(new Auth0ClientOptions
 {
     Domain = Resources.GetString(Resource.String.auth0_domain),
     ClientId = Resources.GetString(Resource.String.auth0_client_id),
     Activity = this
 });
</code>```

答:
This is a list of configuration options for Lock for Android from Auth0 https://auth0.com/docs/libraries/lock-android/configuration

I don't see there much of UI-related options.
Everything you see there you can do in Xamarin as well.

Body:
I have a xamarin app that is utilizing auth0 for auth purposes. But I see for web version you can pass different options for theming the login page appearance. Is that also possible in a xamarin app.

 client = new Auth0Client(new Auth0ClientOptions
 {
     Domain = Resources.GetString(Resource.String.auth0_domain),
     ClientId = Resources.GetString(Resource.String.auth0_client_id),
     Activity = this
 });


答:
The code is pretty fine. For an empty vector lower_bound(books.begin(), books.end(), b) will return end() iterator. Passing it to std::vector::insert will work fine.

pos -   iterator before which the content will be inserted. pos may be the end() iterator

and about your worry:

What makes me cautious about using this is that when debugging, on the insert() line, the value of _it reads "Error Reading...." for each of the members for which the std::iterator is pointing to.

That's because the end() iterator points to the position following the last element, so it's invalid to deference on it (to get a nonexistent element).

Title: Using insert() on empty std::vector when sorting


问:
Equilibrium Index in Python 2.7
I was given a demo task to do in Codility, and I am having some trouble trying to figure out what I'm doing wrong. The task:

Working in Python 2.7 Environment

A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e.

A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].

Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1.

For example, consider the following array A consisting of N = 8 elements:

```<code>A[0] = -1
A[1] =  3
A[2] = -4
A[3] =  5
A[4] =  1
A[5] = -6
A[6] =  2
A[7] =  1
</code>```

P = 1 is an equilibrium index of this array, because:

```<code>A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]
</code>```

P = 3 is an equilibrium index of this array, because:

```<code>A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]
</code>```

P = 7 is also an equilibrium index, because:

```<code>A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0
</code>```

and there are no elements with indices greater than 7.

P = 8 is not an equilibrium index, because it does not fulfill the condition 0 ≤ P < N.

Write a function:

def solution(A)

that, given a zero-indexed array A consisting of N integers, returns any of its equilibrium indices. The function should return −1 if no equilibrium index exists.

In response I wrote the following:

```<code>def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        while x < length:
            for i in A:
                rightSum = A[1:i-1]
                leftSum = A[i+1:length-2]
                if sum(rightSum) == sum(leftSum):
                    equi.append(i)
                    return equi
                else:
                    return -1
            x += 1
    pass

solution([-1,3,-4,5,1,-6,2,1])
</code>```

When I complied the code, I kept getting -1 for the test list, even though I should be getting equi[1,3,7].

Another question, why do I need the 'pass' keyword at the end of the method?

I should add, I am extremely new to Python coding and coding in general. Any help y'all can provide would be appreciated.

答:
Think of the type of the data your function must return. It is a list of equilibrium indexes.

This means that every return statement in your function must return a list. Never a number, never a string.

For an empty list, there are no possible equilibrium indexes; return [].

When you find an equilibrium index, you append it to your equi list, as you correctly do, and go on. Do not return from within the while loop. The first return statement ends the function execution.

When your loop ends because you've looked through all the indexes, the equi list will contain all equilibrium indices the loop has found. Now, after the loop, it's time to return equi, instead of the useless pass.

(For bonus points, you can calculate the sum of the list once, and notice that moving an index to the right adds one element to the left sum and subtracts the same element from the right sum. This way, you won't have to sum each sub-list every time; the performance of the algorithm will be linear instead of quadratic.)

Title: Equilibrium Index in Python 2.7

Body:
I was given a demo task to do in Codility, and I am having some trouble trying to figure out what I'm doing wrong. The task:

Working in Python 2.7 Environment

A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e.

A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].

Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1.

For example, consider the following array A consisting of N = 8 elements:

A[0] = -1
A[1] =  3
A[2] = -4
A[3] =  5
A[4] =  1
A[5] = -6
A[6] =  2
A[7] =  1

P = 1 is an equilibrium index of this array, because:

A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]

P = 3 is an equilibrium index of this array, because:

A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]

P = 7 is also an equilibrium index, because:

A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0

and there are no elements with indices greater than 7.

P = 8 is not an equilibrium index, because it does not fulfill the condition 0 ≤ P < N.

Write a function:

def solution(A)

that, given a zero-indexed array A consisting of N integers, returns any of its equilibrium indices. The function should return −1 if no equilibrium index exists.

In response I wrote the following:

def solution(A):
    if len(A) == 0: #If we're working with an empty list, the method should give us an empty list message and terminate there
        return "Empty list, no integers to work with"
    else:
        equi = []
        x = 0
        length = len(A)
        rightSum = []
        leftSum = []
        while x < length:
            for i in A:
                rightSum = A[1:i-1]
                leftSum = A[i+1:length-2]
                if sum(rightSum) == sum(leftSum):
                    equi.append(i)
                    return equi
                else:
                    return -1
            x += 1
    pass

solution([-1,3,-4,5,1,-6,2,1])

When I complied the code, I kept getting -1 for the test list, even though I should be getting equi[1,3,7].

Another question, why do I need the 'pass' keyword at the end of the method?

I should add, I am extremely new to Python coding and coding in general. Any help y'all can provide would be appreciated.


问:
Convert ASCII to Int
I'm using an Arduino for a project that involves controlling a servo via the serial monitor. The Arduino was receiving different values than what I entered. I'm sure that this is because serial data is read as ASCII. Is there any way that I could convert it to Int? Thanks!</p>

答:
I assume by Arduino you mean "Arduino IDE (C++)".

Arduino has a toInt() function.

```<code>int asciiVal = 97;
String mystr = (char)asciiVal;
Serial.println(mystr);             //prints a
Serial.println(mystr.toInt());     //prints 97
</code>```

Explained here:  https://www.arduino.cc/en/Tutorial/StringToIntExample

Title: Convert ASCII to Int

Body:
I assume by Arduino you mean "Arduino IDE (C++)".

Arduino has a toInt() function.

int asciiVal = 97;
String mystr = (char)asciiVal;
Serial.println(mystr);             //prints a
Serial.println(mystr.toInt());     //prints 97

Explained here:  https://www.arduino.cc/en/Tutorial/StringToIntExample


问:
How do I add a border to a Collection View in Swift?
Not a collection view cell, I figured that out by applying specific border functions such as borderColor and cornerRadius methods in my ViewController. I'm talking about encapsulating the whole view of cells with one border, kind of like this:

Much appreciated.

答:
You need to add a border to collectionView view itself. That is what encapsulates the cells. You can do this either in the viewDidLayoutSubviews: or viewDidLoad:

Like this:

```<code>collectionView.layer.borderWidth = 2.0
collectionView.layer.cornerRadius = 5.0
</code>```

Body:
You need to add a border to collectionView view itself. That is what encapsulates the cells. You can do this either in the viewDidLayoutSubviews: or viewDidLoad:

Like this:

collectionView.layer.borderWidth = 2.0
collectionView.layer.cornerRadius = 5.0


问:
How to create an "X" pattern?
I want to know how to create the following pattern using * and _ using nested loops.

```<code>*_______*
__*___*
____*
__*___*
*_______*
</code>```

I am currently trying to do this in Java, but an answer in C will do as well, I can extrapolate the answer.
Here is a pic to better understand the pattern required.

I understand that I need to have some code to start with , but I cant manage to work out the logic.

Is there any algo/technique that anyone can guide me towards in order to be able to attempt this, some Karnaugh map like technique.

答:
```<code>for(int i =0; i < 5; i++){
    for(int j = 0; j < 9; j++){
       if(j==2*i || 8-2*i == j)
          System.out.print("*");
       else if(8-2*i < j && j > 2*i)
           break;
       else
          System.out.print("_");
    }
  System.out.println();
}
</code>```

Title: How to create an "X" pattern?

Body:
I want to know how to create the following pattern using * and _ using nested loops.

*_______*
__*___*
____*
__*___*
*_______*

I am currently trying to do this in Java, but an answer in C will do as well, I can extrapolate the answer.
Here is a pic to better understand the pattern required.

I understand that I need to have some code to start with , but I cant manage to work out the logic.

Is there any algo/technique that anyone can guide me towards in order to be able to attempt this, some Karnaugh map like technique.


问:
Can read_csv parse m/d/Y H:M:S AM/PM vector?
I'm working through learning tidyverse principles and was wondering if there was an easier/better way to bring in my data that includes a datetime vector in a m/d/Y H:M:S AM/PM format. Currently I import with read_csv, which recognizes the column in character format, and then I use ludridate to create a new column using mdy_hms to parse the datetime column:

```<code>> test <- read_csv("data.csv")
Parsed with column specification:
cols(
  ActivityMinute = col_character(),
  Steps = col_integer()
)
> head(test)
# A tibble: 6 x 2
     ActivityMinute Steps
              <chr> <int>
1 5/12/2016 12:00:00 AM     0
2 5/12/2016 12:01:00 AM     0
3 5/12/2016 12:02:00 AM     0
4 5/12/2016 12:03:00 AM     0
5 5/12/2016 12:04:00 AM     0
6 5/12/2016 12:05:00 AM     0

> test$datetime <- mdy_hms(test$ActivityMinute)
> head(test)
# A tibble: 6 x 3
     ActivityMinute Steps            datetime
              <chr> <int>              <dttm>
1 5/12/2016 12:00:00 AM     0 2016-05-12 00:00:00
2 5/12/2016 12:01:00 AM     0 2016-05-12 00:01:00
3 5/12/2016 12:02:00 AM     0 2016-05-12 00:02:00
4 5/12/2016 12:03:00 AM     0 2016-05-12 00:03:00
5 5/12/2016 12:04:00 AM     0 2016-05-12 00:04:00
6 5/12/2016 12:05:00 AM     0 2016-05-12 00:05:00
</code>```

Is there a better way to do this, perhaps using cols()? I tried specifying the ActivityMinute as col_datetime, but that didn't work. Any tips for better code/process are appreciated.

答:
You have to set the datetime format in the col_datetime call:

```<code>test <-
 read_csv(
  "data.csv",
   col_types = cols(
    ActivityMinute = col_datetime("%m/%d/%Y %I:%M:%S %p"),
    Steps = col_integer()
   )
  )
</code>```

Body:
I'm working through learning tidyverse principles and was wondering if there was an easier/better way to bring in my data that includes a datetime vector in a m/d/Y H:M:S AM/PM format. Currently I import with read_csv, which recognizes the column in character format, and then I use ludridate to create a new column using mdy_hms to parse the datetime column:

> test <- read_csv("data.csv")
Parsed with column specification:
cols(
  ActivityMinute = col_character(),
  Steps = col_integer()
)
> head(test)
# A tibble: 6 x 2
     ActivityMinute Steps
              <chr> <int>
1 5/12/2016 12:00:00 AM     0
2 5/12/2016 12:01:00 AM     0
3 5/12/2016 12:02:00 AM     0
4 5/12/2016 12:03:00 AM     0
5 5/12/2016 12:04:00 AM     0
6 5/12/2016 12:05:00 AM     0

> test$datetime <- mdy_hms(test$ActivityMinute)
> head(test)
# A tibble: 6 x 3
     ActivityMinute Steps            datetime
              <chr> <int>              <dttm>
1 5/12/2016 12:00:00 AM     0 2016-05-12 00:00:00
2 5/12/2016 12:01:00 AM     0 2016-05-12 00:01:00
3 5/12/2016 12:02:00 AM     0 2016-05-12 00:02:00
4 5/12/2016 12:03:00 AM     0 2016-05-12 00:03:00
5 5/12/2016 12:04:00 AM     0 2016-05-12 00:04:00
6 5/12/2016 12:05:00 AM     0 2016-05-12 00:05:00

Is there a better way to do this, perhaps using cols()? I tried specifying the ActivityMinute as col_datetime, but that didn't work. Any tips for better code/process are appreciated.

Body:
You have to set the datetime format in the col_datetime call:

test <-
 read_csv(
  "data.csv",
   col_types = cols(
    ActivityMinute = col_datetime("%m/%d/%Y %I:%M:%S %p"),
    Steps = col_integer()
   )
  )


问:
VM1052:19 Error: (SystemJS) TypeScript transpilation failed

I am new to angular, I am trying to change color for each li when I click it.

but I am getting an error VM1052:19 Error: (SystemJS) TypeScript transpilation failed

can you guys tell me how to fix it.

providng code below

http://plnkr.co/edit/npNw39aRZVgpqEjI6uLH?open=app%2Fapp.component.ts&p=preview

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  styles: [`
    li {
      color: red;
    }
  `],
  template: `

 {{student}}

`
})
export class AppComponent {
  name = 'Angular';
  liArraycontent = ["testing 1", "testing 2", "testing3"]

  liClicked = function(e1) {
    console.log(e1.target);
    e1.addCss(color: green);
  }

}
```

答:
Writing random code and seeing if it works is probably not the best way to learn Angular. Instead, you should read the tutorials and guides. The easiest way in your specific case is to add a style property to the template:

```<code>// template
<ul class= "master">
  <li
    *ngFor ="let student of liArraycontent; let i = index"
    (click)="liClicked(i)"
    [style.color]="colors[i]">
    {{student}}
   </li>
 </ul>

// component
color: 'blue';

liClicked(index) { this.colors[index] = 'green'; }
</code>```

Here is a plunkr.

In terms of your original code:

The event handler will be passed an event, not an element. If you really wanted to get the element from the event, you need event.target.

I'm not aware of any setCss method on elements.

The syntax setCss(color: green) is invalid. key: value pairs occur within object literals. If there were a setCss method, which there is not, it would likely be called as setCss({color: 'green'}), where green is a string and therefore needs to be quoted; otherwise it would be interpreted as a variable.

In correct Angular style, you do not manipulate DOM elements yourself, whether to set styles on them or for anything else. Instead, you write your templates so that component properties, such as color in the above code, are used to drive element behavior, using attributes such as [style.color].

Body:
Writing random code and seeing if it works is probably not the best way to learn Angular. Instead, you should read the tutorials and guides. The easiest way in your specific case is to add a style property to the template:

// template
<ul class= "master">
  <li
    *ngFor ="let student of liArraycontent; let i = index"
    (click)="liClicked(i)"
    [style.color]="colors[i]">
    {{student}}
   </li>
 </ul>

// component
color: 'blue';

liClicked(index) { this.colors[index] = 'green'; }

Here is a plunkr.

In terms of your original code:

The event handler will be passed an event, not an element. If you really wanted to get the element from the event, you need event.target.

I'm not aware of any setCss method on elements.

The syntax setCss(color: green) is invalid. key: value pairs occur within object literals. If there were a setCss method, which there is not, it would likely be called as setCss({color: 'green'}), where green is a string and therefore needs to be quoted; otherwise it would be interpreted as a variable.

In correct Angular style, you do not manipulate DOM elements yourself, whether to set styles on them or for anything else. Instead, you write your templates so that component properties, such as color in the above code, are used to drive element behavior, using attributes such as [style.color].


问:
How to solve loading issue of the Select.Async component from react-select?
I am using the Select.Async component from react-select along with redux-form. I pass a load options function to the Select.Async and that function makes a request only once. The first time it is called, it makes a get request with axios and returns all the options. The problem I've got is that the first time it loads the options (fetches them), it first shows it is Loading as it is in the picture, but then it erases what the user input and shows no options. The second time a user types it works because no request is made but the options are taken from the state.

Thanks for your help in advance!

答: The problem was I was using a stateless component instead of a class. </p>


问:
Help with Regex on Parameter delimiter
I have to match the following text:

```<code>var html = '<td align="right" width="26%">

            <span class="text2-mbna" style="position:relative; left:10px;">
            $0.00</span>

    </td>'
</code>```

I have this regex

```<code>/<span class="text2-mbna" style="position:relative; left:10px;">(?:\s+)((?:\$)((\d|,)+)\.(\d+))<\/span>/.exec(html)
</code>```

I can actually just replace it in javascript, but I want to know how to NOT capture the dollar($) sign.

答:
Just move (?:\$) before the open paren to its left, giving:

```<code>/<span class="text2-mbna" style="position:relative; left:10px;">(?:\s+)(?:\$)(((\d|,)+)\.(\d+))<\/span>/
</code>```

You don't need (?:) there anyway; it can just be

```<code>/<span class="text2-mbna" style="position:relative; left:10px;">\s+\$(((\d|,)+)\.(\d+))<\/span>/
</code>```

Title: Help with Regex on Parameter delimiter

Body:
I have to match the following text:

var html = '

            $0.00

    	'

I have this regex

/(?:\s+)((?:\$)((\d|,)+)\.(\d+))<\/span>/.exec(html)

I can actually just replace it in javascript, but I want to know how to NOT capture the dollar($) sign.

Body:
Just move (?:\$) before the open paren to its left, giving:

/<span class="text2-mbna" style="position:relative; left:10px;">(?:\s+)(?:\$)(((\d|,)+)\.(\d+))<\/span>/

You don't need (?:) there anyway; it can just be

/<span class="text2-mbna" style="position:relative; left:10px;">\s+\$(((\d|,)+)\.(\d+))<\/span>/


问:
android.widget.imageview cannot be cast to android.view.viewgroup (only in android, ios is OK)
I developed a project in react native 0.43.3

I made a mistake developing and testing all project only in iOS. (Works fine there)

The problem was when I tried to generate the APK to upload to PlayStore, and testing in a device I found the error:

android.widget.imageview cannot be cast to android.view.viewgroup

My main problem is about how the error is displayed. Is in the red screen of dead, and I have no idea how to find the line and component in react native where is the error happening. I think maybe I cannot realized that because the javascript code is already compiled.

Anyway, I don't know how to solve the problem.

I think maybe is because I using spinners inside of images (to show the image is being loaded), something like:

```<code>  <View style={[styles.resourceActions]}>
      <Image
        style={{width: imgWidth, height: imgHeight}}
        source={{uri: this.props.imageUrl}}
        onLoad = {() => this.setState({ loading: false })}
      >
      <ActivityIndicator
          animating={this.state.loading}
          style={[styles.spinner, styles.centering, {marginTop: this.state.loadingMarginTop}]}
          size="large"
        />
        </Image>
    </View>
</code>```

But I have no idea because I use imageview (and fastimage component) in a lot of parts and views

my dependencies:

```<code>"@remobile/react-native-refresh-infinite-listview": "^1.0.6",
"react": "16.0.0-alpha.6",
"react-native": "0.43.3",
"react-native-camera": "git+https://github.com/lwansbrough/react-native-camera.git",
"react-native-device-info": "^0.10.2",
"react-native-fast-image": "0.0.9",
"react-native-google-analytics-bridge": "^5.0.1",
"react-native-htmlview": "^0.9.0",
"react-native-loading-spinner-overlay": "^0.4.4",
"react-native-material-design": "^0.3.7",
"react-native-modalbox": "^1.3.9",
"react-native-photo-view": "^1.2.0",
"react-native-qrcode-scanner": "0.0.11",
"react-native-qrcode-svg": "^5.0.0",
"react-native-radio-buttons": "^0.14.0",
"react-native-router-flux": "3.38.0",
"react-native-share": "^1.0.20",
"react-native-side-menu": "^0.20.1",
"react-native-svg": "^5.1.7",
"react-native-vector-icons": "^4.0.1"
</code>```

thanks for any orientation in my problem

答: In Native Android also, we cannot cast an ImageView to ViewGroup as the ImageView does not extend the class ViewGroup. Actually, this casting is not possible.

Body:
I developed a project in react native 0.43.3

I made a mistake developing and testing all project only in iOS. (Works fine there)

The problem was when I tried to generate the APK to upload to PlayStore, and testing in a device I found the error:

android.widget.imageview cannot be cast to android.view.viewgroup

My main problem is about how the error is displayed. Is in the red screen of dead, and I have no idea how to find the line and component in react native where is the error happening. I think maybe I cannot realized that because the javascript code is already compiled.

Anyway, I don't know how to solve the problem.

I think maybe is because I using spinners inside of images (to show the image is being loaded), something like:

  <View style={[styles.resourceActions]}>
      <Image
        style={{width: imgWidth, height: imgHeight}}
        source={{uri: this.props.imageUrl}}
        onLoad = {() => this.setState({ loading: false })}
      >
      <ActivityIndicator
          animating={this.state.loading}
          style={[styles.spinner, styles.centering, {marginTop: this.state.loadingMarginTop}]}
          size="large"
        />
        </Image>
    </View>

But I have no idea because I use imageview (and fastimage component) in a lot of parts and views

my dependencies:

"@remobile/react-native-refresh-infinite-listview": "^1.0.6",
"react": "16.0.0-alpha.6",
"react-native": "0.43.3",
"react-native-camera": "git+https://github.com/lwansbrough/react-native-camera.git",
"react-native-device-info": "^0.10.2",
"react-native-fast-image": "0.0.9",
"react-native-google-analytics-bridge": "^5.0.1",
"react-native-htmlview": "^0.9.0",
"react-native-loading-spinner-overlay": "^0.4.4",
"react-native-material-design": "^0.3.7",
"react-native-modalbox": "^1.3.9",
"react-native-photo-view": "^1.2.0",
"react-native-qrcode-scanner": "0.0.11",
"react-native-qrcode-svg": "^5.0.0",
"react-native-radio-buttons": "^0.14.0",
"react-native-router-flux": "3.38.0",
"react-native-share": "^1.0.20",
"react-native-side-menu": "^0.20.1",
"react-native-svg": "^5.1.7",
"react-native-vector-icons": "^4.0.1"

thanks for any orientation in my problem


问:
How can I get included objects in a contentful getEntry call using javascript sdk?
I see that I can pass a query object with include:2 in the getEntries method using the node.js javascript api.  How can I do that with the getEntry call that returns a single object.

```<code>// how do I get the nested objects by passing the parameter include:1
client.getEntry('<entry_id>', {<what goes here?>})
.then(function (entry) {
  // logs the entry metadata

})
</code>```

答:
getEntry returns 1 and only 1 entry. If you want to include the linked entries of 1 parent entry (aka more than one entry), you have to use the getEntries method and specify the sys.id of the parent entry you want to retrieve. Like so:

```<code>client.getEntries({'sys.id': '<entry_id>'})
.then(entries => {
  ...
})
</code>```

Body:
I see that I can pass a query object with include:2 in the getEntries method using the node.js javascript api.  How can I do that with the getEntry call that returns a single object.

// how do I get the nested objects by passing the parameter include:1
client.getEntry('<entry_id>', {<what goes here?>})
.then(function (entry) {
  // logs the entry metadata

})

Body:
getEntry returns 1 and only 1 entry. If you want to include the linked entries of 1 parent entry (aka more than one entry), you have to use the getEntries method and specify the sys.id of the parent entry you want to retrieve. Like so:

client.getEntries({'sys.id': '<entry_id>'})
.then(entries => {
  ...
})


问:
How do I join an unknown number of rows to another row?
I have this scenario:

Table A:

```<code>---------------
ID| SOME_VALUE|
---------------
1 | 123223    |
2 | 1232ff    |
---------------
</code>```

Table B:

```<code>------------------
ID | KEY | VALUE |
------------------
23 | 1   | 435   |
24 | 1   | 436   |
------------------
</code>```

KEY is a reference to to Table A's ID. Can I somehow join these tables so that I get the following result:

Table C

```<code>-------------------------
ID| SOME_VALUE|    |    |
-------------------------
1 | 123223    |435 |436 |
2 | 1232ff    |    |    |
-------------------------
</code>```

Table C should be able to have any given number of columns depending on how many matching values that are found in Table B.

I hope this enough to explain what I'm after here.

Thanks.

答:
As Barry has amply illustrated, it's possible to get multiple columns using a dynamic pivot.

I've got a solution that might get you what you need, except that it puts all of the values into a single VARCHAR column. If you can split those results, then you can get what you need.

This method is a trick in SQL Server 2005 that you can use to form a string out of a column of values.

```<code>CREATE TABLE #TableA (
   ID INT,
   SomeValue VARCHAR(50)
);
CREATE TABLE #TableB (
   ID INT,
   TableAKEY INT,
   BValue VARCHAR(50)
);

INSERT INTO #TableA VALUES (1, '123223');
INSERT INTO #TableA VALUES (2, '1232ff');
INSERT INTO #TableA VALUES (3, '222222');

INSERT INTO #TableB VALUES (23, 1, 435);
INSERT INTO #TableB VALUES (24, 1, 436);
INSERT INTO #TableB VALUES (25, 3,  45);
INSERT INTO #TableB VALUES (26, 3,  46);
INSERT INTO #TableB VALUES (27, 3, 435);
INSERT INTO #TableB VALUES (28, 3, 437);

SELECT
   a.ID
   ,a.SomeValue
   ,RTRIM(bvals.BValues) AS ValueList
FROM #TableA AS a
OUTER APPLY (
   -- This has the effect of concatenating all of
   -- the BValues for the given value of a.ID.
   SELECT b.BValue + ' ' AS [text()]
   FROM #TableB AS b
   WHERE a.ID = b.TableAKEY
   ORDER BY b.ID
   FOR XML PATH('')
) AS bvals (BValues)
ORDER BY a.ID
;
</code>```

You'll get this as a result:

```<code>ID  SomeValue  ValueList
--- ---------- --------------
1   123223     435 436
2   1232ff     NULL
3   222222     45 46 435 437
</code>```

Body:
I have this scenario:

Table A:

---------------
ID| SOME_VALUE|
---------------
1 | 123223    |
2 | 1232ff    |
---------------

Table B:

------------------
ID | KEY | VALUE |
------------------
23 | 1   | 435   |
24 | 1   | 436   |
------------------

KEY is a reference to to Table A's ID. Can I somehow join these tables so that I get the following result:

Table C

-------------------------
ID| SOME_VALUE|    |    |
-------------------------
1 | 123223    |435 |436 |
2 | 1232ff    |    |    |
-------------------------

Table C should be able to have any given number of columns depending on how many matching values that are found in Table B.

I hope this enough to explain what I'm after here.

Thanks.

Body:
As Barry has amply illustrated, it's possible to get multiple columns using a dynamic pivot.

I've got a solution that might get you what you need, except that it puts all of the values into a single VARCHAR column. If you can split those results, then you can get what you need.

This method is a trick in SQL Server 2005 that you can use to form a string out of a column of values.

CREATE TABLE #TableA (
   ID INT,
   SomeValue VARCHAR(50)
);
CREATE TABLE #TableB (
   ID INT,
   TableAKEY INT,
   BValue VARCHAR(50)
);

INSERT INTO #TableA VALUES (1, '123223');
INSERT INTO #TableA VALUES (2, '1232ff');
INSERT INTO #TableA VALUES (3, '222222');

INSERT INTO #TableB VALUES (23, 1, 435);
INSERT INTO #TableB VALUES (24, 1, 436);
INSERT INTO #TableB VALUES (25, 3,  45);
INSERT INTO #TableB VALUES (26, 3,  46);
INSERT INTO #TableB VALUES (27, 3, 435);
INSERT INTO #TableB VALUES (28, 3, 437);

SELECT
   a.ID
   ,a.SomeValue
   ,RTRIM(bvals.BValues) AS ValueList
FROM #TableA AS a
OUTER APPLY (
   -- This has the effect of concatenating all of
   -- the BValues for the given value of a.ID.
   SELECT b.BValue + ' ' AS [text()]
   FROM #TableB AS b
   WHERE a.ID = b.TableAKEY
   ORDER BY b.ID
   FOR XML PATH('')
) AS bvals (BValues)
ORDER BY a.ID
;

You'll get this as a result:

ID  SomeValue  ValueList
--- ---------- --------------
1   123223     435 436
2   1232ff     NULL
3   222222     45 46 435 437


问:
Can't figure out how to get basic ruby 'encryptor' to work
Basically want to make 'abc' into 'bcd'. I was thinking if I add the letter the follows the first to the end of the phrase and dropped the original first letter, eventually I'd get the final solution. Got kinda stuck and was hoping someone could shed some light on it for me. Thanks</p>

```<code>def encrypt(str)
  index = 0
  encrypted_str = ""
  duration = str.length
  until index == str.length
    encrypted_str = str + str[0].next
    encrypted_str = encrypted_str + encrypted_str.delete(str[index])
    index += 1
  end
  puts encrypted_str
end

#puts "What would you like to encrypt?"
message = "abc"
puts encrypt(message)
</code>```

答:
Your code analysis..
Since you already initializing encrypted_str with empty string, there's no need to append it to original string and then slice it again..that's where it is getting messed up..just do the following..

```<code>until index == duration #you are not using duration too if assigned it to a variable
  encrypted_str += str[index].next[0]
  index += 1
end
</code>```

Taking the index 0 for next string because 'z'.next returns aa

An alternative one liner approach would be..

```<code>message.each_char.map { |s| s.next[0] }.join
</code>```

chars will split the message into individual characters

map collects the manipulated characters into an array

join will join individual characters from mapped array to a string again

To Decrypt

```<code>encrypted_str.each_char.map { |s| s.eql?('a') ? 'z' : (s.ord-1).chr }.join
</code>```

Body:
Basically want to make 'abc' into 'bcd'. I was thinking if I add the letter the follows the first to the end of the phrase and dropped the original first letter, eventually I'd get the final solution. Got kinda stuck and was hoping someone could shed some light on it for me. Thanks

def encrypt(str)
  index = 0
  encrypted_str = ""
  duration = str.length
  until index == str.length
    encrypted_str = str + str[0].next
    encrypted_str = encrypted_str + encrypted_str.delete(str[index])
    index += 1
  end
  puts encrypted_str
end

#puts "What would you like to encrypt?"
message = "abc"
puts encrypt(message)

Body:
Your code analysis..
Since you already initializing encrypted_str with empty string, there's no need to append it to original string and then slice it again..that's where it is getting messed up..just do the following..

until index == duration #you are not using duration too if assigned it to a variable
  encrypted_str += str[index].next[0]
  index += 1
end

Taking the index 0 for next string because 'z'.next returns aa

An alternative one liner approach would be..

message.each_char.map { |s| s.next[0] }.join

chars will split the message into individual characters

map collects the manipulated characters into an array

join will join individual characters from mapped array to a string again

To Decrypt

encrypted_str.each_char.map { |s| s.eql?('a') ? 'z' : (s.ord-1).chr }.join


问:
How can I list urlpatterns (endpoints) on Django?
How can I see the current urlpatterns that "reverse" is looking in?

I'm calling reverse in a view with an argument that I think should work, but doesn't. Any way I can check what's there and why my pattern isn't?

答:
Django 1.11, Python 2.7.6

cd to_your_django_project

python manage.py shell

Then paste following code.

```<code>from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers
urls = urlresolvers.get_resolver()

def if_none(value):
    if value:
        return value
    return ''

def print_urls(urls, parent_pattern=None):
    for url in urls.url_patterns:
        if isinstance(url, RegexURLResolver):
            print_urls(url, if_none(parent_pattern) + url.regex.pattern)
        elif isinstance(url, RegexURLPattern):
            print(if_none(parent_pattern) + url.regex.pattern)

print_urls(urls)
</code>```

Sample output:

```<code>^django-admin/^$
^django-admin/^login/$
^django-admin/^logout/$
^django-admin/^password_change/$
^django-admin/^password_change/done/$
^django-admin/^jsi18n/$
^django-admin/^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$
^django-admin/^wagtailimages/image/^$
^django-admin/^wagtailimages/image/^add/$
^django-admin/^wagtailimages/image/^(.+)/history/$
^django-admin/^wagtailimages/image/^(.+)/delete/$
^django-admin/^wagtailimages/image/^(.+)/change/$
^django-admin/^wagtailimages/image/^(.+)/$
...
</code>```

Body:
Django 1.11, Python 2.7.6

cd to_your_django_project

python manage.py shell

Then paste following code.

from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers
urls = urlresolvers.get_resolver()

def if_none(value):
    if value:
        return value
    return ''

def print_urls(urls, parent_pattern=None):
    for url in urls.url_patterns:
        if isinstance(url, RegexURLResolver):
            print_urls(url, if_none(parent_pattern) + url.regex.pattern)
        elif isinstance(url, RegexURLPattern):
            print(if_none(parent_pattern) + url.regex.pattern)

print_urls(urls)

Sample output:

^django-admin/^$
^django-admin/^login/$
^django-admin/^logout/$
^django-admin/^password_change/$
^django-admin/^password_change/done/$
^django-admin/^jsi18n/$
^django-admin/^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$
^django-admin/^wagtailimages/image/^$
^django-admin/^wagtailimages/image/^add/$
^django-admin/^wagtailimages/image/^(.+)/history/$
^django-admin/^wagtailimages/image/^(.+)/delete/$
^django-admin/^wagtailimages/image/^(.+)/change/$
^django-admin/^wagtailimages/image/^(.+)/$
...


问:
How to distinguish two regular expressions, with one being the substring of the other?
I have two types of patterns, as below:

Type I: ${<varName>}

Type II: $${<varName>}

The patterns can be found standing alone, or contained multiple matches in a string. I need to find the occurrences of these patterns, so I wrote a query to search by matching regex. However, the problem is that for any Type II pattern, they themselves contain a match for Type I pattern. For example, $${newVar} will be detected twice as $${newVar} and ${newVar}. I only want the former to be returned. The regular expressions I used are:

Type I: \$\{[a-zA-Z0-9]+\}

Type II: \$\$\{[a-zA-Z0-9]+\}

You can see an example of the detected string here (below)

Note that the second detection is correct, whereas the first detection is unwanted.

Is there anyway too modify these regular expressions to meet my need? Or is there any alternatives? Please feel free to suggest. All answers are welcome!! Thank you all.

答:
For variables of type ${varname} you can use this pattern:

```<code>(^|[^$])\$\{.*?\}
</code>```

And for variables of type $${varname} you can use what you already had in mind:

```<code>\$\$\{.*?\\}
</code>```

Sample Code:

```<code>String input = "${beef} is a great thing to $${eat}.  It has many ${health} benefits ";
       input + "and is low in fat ${too}";

// single dollar sign variables
System.out.println("single dollar sign variables:");
String pattern = "(?:^|[^$])(\\$\\{.*?\\})";
Pattern r = Pattern.compile(pattern);

Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("Found value: " + m.group(1));
}

// two dollar sign variables
System.out.println("two dollar sign variables:");
pattern = "(\\$\\$\\{.*?\\})";
r = Pattern.compile(pattern);

m = r.matcher(input);
while (m.find()) {
    System.out.println("Found value: " + m.group(1));
}
</code>```

Output:

```<code>single dollar sign variables:
Found value: ${beef}
Found value: ${health}
Found value: ${too}
two dollar sign variables:
Found value: $${eat}
</code>```

Demo here:

Rextester

Body:
For variables of type ${varname} you can use this pattern:

(^|[^$])\$\{.*?\}

And for variables of type $${varname} you can use what you already had in mind:

\$\$\{.*?\\}

Sample Code:

String input = "${beef} is a great thing to $${eat}.  It has many ${health} benefits ";
       input + "and is low in fat ${too}";

// single dollar sign variables
System.out.println("single dollar sign variables:");
String pattern = "(?:^|[^$])(\\$\\{.*?\\})";
Pattern r = Pattern.compile(pattern);

Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("Found value: " + m.group(1));
}

// two dollar sign variables
System.out.println("two dollar sign variables:");
pattern = "(\\$\\$\\{.*?\\})";
r = Pattern.compile(pattern);

m = r.matcher(input);
while (m.find()) {
    System.out.println("Found value: " + m.group(1));
}

Output:

single dollar sign variables:
Found value: ${beef}
Found value: ${health}
Found value: ${too}
two dollar sign variables:
Found value: $${eat}

Demo here:

Rextester


问:
cannot run docker image with mounted folder
I'm trying to run a docker image with a folder from the host mounted to the docker image. I have a mac running on sierra. I want to mount '/Users/' folder form the host to the container path of 'code'. This is what I put in:

```<code>docker run -it -v /Users:code 7b9b13f7b9c0 latest
</code>```

I got this error.

```<code>docker: Error response from daemon: Invalid bind mount spec "/Users:code": Invalid volume destination path: 'code' mount path must be absolute..
</code>```

What am I doing wrong?

Appreciate your help.

答:
The error message says it all.  You must specify a full path for the code directory like this:

-v /Users:/path/to/code

Body:
I'm trying to run a docker image with a folder from the host mounted to the docker image. I have a mac running on sierra. I want to mount '/Users/' folder form the host to the container path of 'code'. This is what I put in:

docker run -it -v /Users:code 7b9b13f7b9c0 latest

I got this error.

docker: Error response from daemon: Invalid bind mount spec "/Users:code": Invalid volume destination path: 'code' mount path must be absolute..

What am I doing wrong?

Appreciate your help.


问:
Why Symbols not convert string implicitly
Why Symbol('test').toString() works well, but I can't use '' + Symbol('test')?

It will throw Error:

cannot convert a Symbol value to a string

Why does the implicit type conversion not work? Why is the code not equal to '' + Symbol('test').toString()?

答:
your type not string

```<code>'' + Symbol('test').toString()
</code>```

you can check, Symbol is a new type in ES6

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol

```<code>The Symbol() function returns a value of type symbol, .....
</code>```

Body:
your type not string

'' + Symbol('test').toString()

you can check, Symbol is a new type in ES6

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol

The Symbol() function returns a value of type symbol, .....


问:
Why does databinding not work?
I have a car-class like this:

```<code>public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}
</code>```

I also have a userControl:

```<code>public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}
</code>```

With xaml:

```<code><Grid>
     <Label Content="{Binding Path=car.Name}" Name="lblCarName"/>
</Grid>
</code>```

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

答:
Your binding binds to the datacontext's car.Name. In your case, the DataContext is NULL.

You have several options:

Set the data context to the CarListItem instance

Specify binding source.

The first option is usually better.

Even better idea would be to define a DataTemplate for your Car, and use a list of Cars instead of explicit CarListItems:

```<code><DataTemplate DataType="{x:Type local:Car}">
    <Grid>
        <Label Content="{Binding Path=Name}"/>
    </Grid>
</DataTemplate>
</code>```

Now, you can use this template as ItemTemplate in the list.

Title: Why does databinding not work?

Body:
I have a car-class like this:

public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}

I also have a userControl:

public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}

With xaml:

<Grid>

</Grid>

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

Body:
Your binding binds to the datacontext's car.Name. In your case, the DataContext is NULL.

You have several options:

Set the data context to the CarListItem instance

Specify binding source.

The first option is usually better.

Even better idea would be to define a DataTemplate for your Car, and use a list of Cars instead of explicit CarListItems:

<DataTemplate DataType="{x:Type local:Car}">
    <Grid>
        <Label Content="{Binding Path=Name}"/>
    </Grid>
</DataTemplate>

Now, you can use this template as ItemTemplate in the list.


问:
Opencv c++. Draw a circle on different pixel of image in a for loop, (the image should be open new at each loop run)
I want to plot circles on a image where each previous circle is deleted on the image before the next circle is drawn.

I have to following configuration:

I have several picture (let says 10)

For each picture I test several pixel for some condition (let say 50 pixels).

For each pixel I'm testing (or working on) I want to draw a circle at that pixel for visualization purpose (for me to visualize that pixel).

To summarize I have 2 for loop, one looping over the 10 images and the other looping over the 50 pixels.

I done the following (see code above). The circles are correctly drawn but when the next circle is drawn, the previous circle is still visible (at the end all circle are drawn on the same image) but what I want to have is (after a circle was drawn) to close the picture (or window) somehow and reopen a new one and plot the next circle on it and so on

```<code>for(int imgID=0; imgID < numbImgs; imgID++)
{
cv::Mat colorImg = imgVector[imgID];
for(int pixelID=0; pixelID < numPixelsToBeTested; pixelID++)
{
some_pixel = ... //some pixel
x = some_pixel(0); y = some_pixel(1);
cv::Mat colorImg2 = colorImg; //redefine the image for each pixel
cv::circle(colorImg2, cv::Point(x,y),5, cv::Scalar(0,0,255),1, cv::LINE_8, 0);
// creating a new window each time
cv::namedWindow("Display", CV_WINDOW_AUTOSIZE );
cv::imshow("Display", colorImg2);
cv::waitKey(0);
cv::destroyWindow("Display");
}
}
</code>```

What is wrong in my code?
Thanks guys

答:
cv::circle() manipulates the input image within the API call, so what you need to do is to create a clone of the original image, draw circles on the cloned image and at each iteration swap the cloned image with original image.

It is also a good idea to break your program into smaller methods, making the code more readable and easy to understand, Following code may give you a starting point.

```<code>void visualizePoints(cv::Mat mat) {
    cv::Mat debugMat = mat.clone();

    // Dummy set of points, to be replace with the 50 points youo are using.
    std::vector<cv::Point> points = {cv::Point(30, 30), cv::Point(30, 100), cv::Point(100, 30), cv::Point(100, 100)};
    for (cv::Point p:points) {
        cv::circle(debugMat, p, 5, cv::Scalar(0, 0, 255), 1, cv::LINE_8, 0);

        cv::imshow("Display", debugMat);
        cv::waitKey(800);
        debugMat = mat.clone();
    }
}

int main() {
    std::vector<std::string> imagePaths = {"path/img1.png", "path/img2.png", "path/img3.png"};
    cv::namedWindow("Display", CV_WINDOW_AUTOSIZE );

    for (std::string path:imagePaths) {
        cv::Mat img = cv::imread(path);
        visualizePoints(img);
    }
}
</code>```

Body:
I want to plot circles on a image where each previous circle is deleted on the image before the next circle is drawn.

I have to following configuration:

I have several picture (let says 10)

For each picture I test several pixel for some condition (let say 50 pixels).

For each pixel I'm testing (or working on) I want to draw a circle at that pixel for visualization purpose (for me to visualize that pixel).

To summarize I have 2 for loop, one looping over the 10 images and the other looping over the 50 pixels.

I done the following (see code above). The circles are correctly drawn but when the next circle is drawn, the previous circle is still visible (at the end all circle are drawn on the same image) but what I want to have is (after a circle was drawn) to close the picture (or window) somehow and reopen a new one and plot the next circle on it and so on

for(int imgID=0; imgID < numbImgs; imgID++)
{
cv::Mat colorImg = imgVector[imgID];
for(int pixelID=0; pixelID < numPixelsToBeTested; pixelID++)
{
some_pixel = ... //some pixel
x = some_pixel(0); y = some_pixel(1);
cv::Mat colorImg2 = colorImg; //redefine the image for each pixel
cv::circle(colorImg2, cv::Point(x,y),5, cv::Scalar(0,0,255),1, cv::LINE_8, 0);
// creating a new window each time
cv::namedWindow("Display", CV_WINDOW_AUTOSIZE );
cv::imshow("Display", colorImg2);
cv::waitKey(0);
cv::destroyWindow("Display");
}
}

What is wrong in my code?
Thanks guys

Body:
cv::circle() manipulates the input image within the API call, so what you need to do is to create a clone of the original image, draw circles on the cloned image and at each iteration swap the cloned image with original image.

It is also a good idea to break your program into smaller methods, making the code more readable and easy to understand, Following code may give you a starting point.

void visualizePoints(cv::Mat mat) {
    cv::Mat debugMat = mat.clone();

    // Dummy set of points, to be replace with the 50 points youo are using.
    std::vector<cv::Point> points = {cv::Point(30, 30), cv::Point(30, 100), cv::Point(100, 30), cv::Point(100, 100)};
    for (cv::Point p:points) {
        cv::circle(debugMat, p, 5, cv::Scalar(0, 0, 255), 1, cv::LINE_8, 0);

        cv::imshow("Display", debugMat);
        cv::waitKey(800);
        debugMat = mat.clone();
    }
}

int main() {
    std::vector<std::string> imagePaths = {"path/img1.png", "path/img2.png", "path/img3.png"};
    cv::namedWindow("Display", CV_WINDOW_AUTOSIZE );

    for (std::string path:imagePaths) {
        cv::Mat img = cv::imread(path);
        visualizePoints(img);
    }
}


问:
Can AD Distribution Group be used for authorizing users?
All the users I want to let into the admin section of my app are in a distribution group but not a security group.  Can I use a distribution group in the Usre.IsInRole() method and in the Authorize(Role="Domain\DistribGroup")] ?</p>

答: No, rather you can use Email enabled Security group - this will allow both controlling security access & sending emails.</p>


问:
JavaScript Crashing Chrome (Infinite Recursion )
When I run this my browser freezes and crashes but I can't figure out how to fix it. I am new to JavaScript and I need some help.</p>

```<code>function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
    Start()
}

}
</code>```

答:
In case Key1 and Key2 are both false, the code executes the last block, i.e. calls itself and it goes on infinitely resulting in the browser freeze.
If either Key1 or Key2 is true before you invoke the function for the first time, then you will not get into this recursive call.</p>

Body:
When I run this my browser freezes and crashes but I can't figure out how to fix it. I am new to JavaScript and I need some help.

function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
    Start()
}

}


问:
Why does installing one npm package remove many others?
I'm having difficulty installing a package using npm. The package installs successfully, however, it removes a whole bunch of other packages.

I'm not able to reproduce this on another machine. Here's the output of the package install:

```<code>[masterwok@crunchbox Caster]$  npm install react-native-google-cast --save
npm notice created a lockfile as package-lock.json. You should commit this file.
+ react-native-google-cast@1.3.0
added 1 package and removed 638 packages in 7.967s
[masterwok@crunchbox Caster]$
</code>```

As you can see, it completely destroys my application dependencies. What could cause this? If I had to guess, I'd say some dependency is failing to be met which cascades down. I have no idea hah

答:
I'm not entirely sure why npm is doing what it's doing, but from the look of the output, package-lock, I surmise that you're using npm5.

Try downgrading to npm 4.

Body:
I'm having difficulty installing a package using npm. The package installs successfully, however, it removes a whole bunch of other packages.

I'm not able to reproduce this on another machine. Here's the output of the package install:

[masterwok@crunchbox Caster]$  npm install react-native-google-cast --save
npm notice created a lockfile as package-lock.json. You should commit this file.
+ react-native-google-cast@1.3.0
added 1 package and removed 638 packages in 7.967s
[masterwok@crunchbox Caster]$

As you can see, it completely destroys my application dependencies. What could cause this? If I had to guess, I'd say some dependency is failing to be met which cascades down. I have no idea hah


问:
stackoverflow error on updatechildren() firebase android
Im getting a strange problem when updating the firebase database at an existing node.
it comes back with InvocationTargetException and further below a stackoverflow error(is that where the site gets its name from).
Ive tried everything i could think of and searched SO and still cant fix it. The problem doesnt seem to be in the build file. I recently changed my app package name and added it to the firebase console.
Ive also just noticed that the log debug section is still refering to my apps previous package name com.example.shopper. could this be causing it.
Or is it the two lines pointed out below.

```<code> else {
        InventoryItem updatedItem = items.get(position).getInventoryItem();
        updatedItem.setPrice(price);
        updatedItem.setQuantity(quantity);
        updatedItem.setUnitName(unitType);
        Map<String, Object> databaseUpdate = new HashMap<>();
        databaseUpdate.put(updatedItem.getName(), updatedItem);
        Log.d(TAG, "done: updatedItem: "+updatedItem.toString());
        inventoryDatabaseReference=inventoryDatabaseReference.child(updatedItem.getCategory());
        Log.d(TAG, "done: updateNotWorking:  "+inventoryDatabaseReference.toString());
        inventoryDatabaseReference.updateChildren(databaseUpdate).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "onFailure: "+e.toString());
            }
        });
    }
</code>```

Its the line with the failure listener that the trace points me to. I added the listener to see what was going wrong but found as soon as the line is called i get the error as in the log above is the final successful operation
To get the values to change the item by I use a dialog fragment. This fragment is used for multiple similar purposes such as the initial placement of that data and works for that purpose.
The trace below it points to the first line calling donelistener.done

```<code>   builder.setTitle(title).setPositiveButton("Done", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (setPrice || isUpdating)
                doneListener.done(quantity, unitSelected, position, priceSet);
            else {
                priceInBasket = priceSet * quantityToBuy;
                Log.d("n", "onClick: TotalPrice toBasket " + priceInBasket + "individiual price" + priceSet);
                doneListener.done(quantityToBuy, buyerItemUnitName, position, priceInBasket);
            }
        }
    })
</code>```

Sorry if this is a simple error and a waste of time but Ive spent all last night on this and can not see the solution.
Anything else you may need just let me know
The trace is as below

```<code>06-07 14:13:21.434 14585-14585/com.example.testing.shopper     D/CurrentInventory: done: updatedItem: InventoryItem{quantity=6, price=0.5, unitName='/100g'}
06-07 14:13:21.435 14585-14585/com.example.testing.shopper D/CurrentInventory: done: updateNotWorking:  https://shopper-a34fb.firebaseio.com/ShopInventory/-KkgxqStvYBMm1fz0lOZ/Energy%20Drinks
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm: threadid=1: stack overflow on call to Ljava/lang/AbstractStringBuilder;.enlargeBuffer:VI
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm:   method requires 28+20+20=68 bytes, fp is 0x419a2334 (52 left)
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm:   expanding stack end (0x419a2300 to 0x419a2000)
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm: Shrank stack (to 0x419a2300, curFrame is 0x419a248c)
06-07 14:13:21.765 14585-14585/com.example.testing.shopper D/AndroidRuntime: Shutting down VM
06-07 14:13:21.765 14585-14585/com.example.testing.shopper D/dalvikvm: threadid=1: detach (group=0x41aa3ce0)
06-07 14:13:21.765 14585-14585/com.example.testing.shopper W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41aa3ce0)
06-07 14:13:21.765 14585-14585/com.example.testing.shopper W/dalvikvm: threadid=1: uncaught exception occurred
06-07 14:13:21.765 14585-14585/com.example.testing.shopper W/System.err: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
06-07 14:13:21.772 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
</code>```

a bunch of these

```<code>06-07 14:13:21.859 14585-14585/com.example.testing.shopper D/dalvikvm: GC_FOR_ALLOC freed 5052K (46469), 38% free 8607K/13700K, paused 34ms, total 35ms
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzaE(Unknown Source)
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzaE(Unknown Source)
</code>```

It then shows the lines where my code is above is

```<code>06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzaF(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.firebase.database.DatabaseReference.updateChildren(Unknown Source)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at com.aihsoftware.shopper.CurrentInventoryFragment.done(CurrentInventoryFragment.java:288)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at com.aihsoftware.shopper.DialogFragments.AddItemToInventoryDialogFragment$2.onClick(AddItemToInventoryDialogFragment.java:145)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:110)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at android.os.Looper.loop(Looper.java:193)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     rr:     at java.lang.reflect.Method.invoke(Method.java:515)
06-07 14:13:21.894 14585-14585/com.example.testing.shopper W/System.err:    ... 557 more
06-07 14:13:21.895 14585-14585/com.example.testing.shopper W/System.err: Caused by: java.lang.StackOverflowError
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:163)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at java.lang.StringBuilder.append(StringBuilder.java:311)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri.encode(Uri.java:1864)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$PathPart.getEncoded(Uri.java:2112)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.appendSspTo(Uri.java:1216)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.makeSchemeSpecificPart(Uri.java:1205)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.getSsp(Uri.java:1188)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.getSchemeSpecificPart(Uri.java:1197)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:    ... 559 more
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
</code>```

finally a bunch of this in red

```<code>06-07 14:13:21.927 14585-14585/com.example.testing.shopper E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.example.testing.shopper, PID: 14585
                                                                         java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
                                                                             at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
</code>```

Thanks in advance everybody

EDIT: done some more digging and the invocation target is a wrapper around the stackoverflow error. forgot about pointing that out.
This means that there is a problem with URI's and the stringbuilder. does firebase database .updateChildren() not work with URI's

答:
I found a work around. Im happy it works but not that I still dont know why the stackoverflow error is occurring.
I changed the updateChildren() to point to each individual data member of the object instead of the object itself. This worked but first there was an error which when updating an item more than once led to another tree.
For example i have
category:{
item:{
price:1
quantity:1
}
}
and it would result in
category:{
 category:{
price:2(updated)
quantity:2(updated)
}
 item:{
price:1
quantity:1
}
}
This keeps repeating for as many updates as required and I believe that is where the issue came from. However I cannot understand what the error in my code is. I always use updateChildren() as best practice.
All i can think is these lines are the problem causing multiple subcategories.I placed category in both of these as variations

```<code>databaseUpdate.put(updatedItem.getName(), updatedItem);
    inventoryDatabaseReference=inventoryDatabaseReference.child(updatedItem.getCategory());
</code>```

This is what worked

```<code>databaseUpdate.put(updatedItem.getCategory()+"/"+updatedItem.getName()+"/price",price);
        databaseUpdate.put(updatedItem.getCategory()+"/"+updatedItem.getName()+"/quantity",quantity);
        databaseUpdate.put(updatedItem.getCategory()+"/"+updatedItem.getName()+"/unitName",unitType);
inventoryDatabaseReference.updateChildren(databaseUpdate)
</code>```

Body:
Im getting a strange problem when updating the firebase database at an existing node.
it comes back with InvocationTargetException and further below a stackoverflow error(is that where the site gets its name from).
Ive tried everything i could think of and searched SO and still cant fix it. The problem doesnt seem to be in the build file. I recently changed my app package name and added it to the firebase console.
Ive also just noticed that the log debug section is still refering to my apps previous package name com.example.shopper. could this be causing it.
Or is it the two lines pointed out below.

 else {
        InventoryItem updatedItem = items.get(position).getInventoryItem();
        updatedItem.setPrice(price);
        updatedItem.setQuantity(quantity);
        updatedItem.setUnitName(unitType);
        Map<String, Object> databaseUpdate = new HashMap<>();
        databaseUpdate.put(updatedItem.getName(), updatedItem);
        Log.d(TAG, "done: updatedItem: "+updatedItem.toString());
        inventoryDatabaseReference=inventoryDatabaseReference.child(updatedItem.getCategory());
        Log.d(TAG, "done: updateNotWorking:  "+inventoryDatabaseReference.toString());
        inventoryDatabaseReference.updateChildren(databaseUpdate).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "onFailure: "+e.toString());
            }
        });
    }

Its the line with the failure listener that the trace points me to. I added the listener to see what was going wrong but found as soon as the line is called i get the error as in the log above is the final successful operation
To get the values to change the item by I use a dialog fragment. This fragment is used for multiple similar purposes such as the initial placement of that data and works for that purpose.
The trace below it points to the first line calling donelistener.done

   builder.setTitle(title).setPositiveButton("Done", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (setPrice || isUpdating)
                doneListener.done(quantity, unitSelected, position, priceSet);
            else {
                priceInBasket = priceSet * quantityToBuy;
                Log.d("n", "onClick: TotalPrice toBasket " + priceInBasket + "individiual price" + priceSet);
                doneListener.done(quantityToBuy, buyerItemUnitName, position, priceInBasket);
            }
        }
    })

Sorry if this is a simple error and a waste of time but Ive spent all last night on this and can not see the solution.
Anything else you may need just let me know
The trace is as below

06-07 14:13:21.434 14585-14585/com.example.testing.shopper     D/CurrentInventory: done: updatedItem: InventoryItem{quantity=6, price=0.5, unitName='/100g'}
06-07 14:13:21.435 14585-14585/com.example.testing.shopper D/CurrentInventory: done: updateNotWorking:  https://shopper-a34fb.firebaseio.com/ShopInventory/-KkgxqStvYBMm1fz0lOZ/Energy%20Drinks
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm: threadid=1: stack overflow on call to Ljava/lang/AbstractStringBuilder;.enlargeBuffer:VI
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm:   method requires 28+20+20=68 bytes, fp is 0x419a2334 (52 left)
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm:   expanding stack end (0x419a2300 to 0x419a2000)
06-07 14:13:21.764 14585-14585/com.example.testing.shopper I/dalvikvm: Shrank stack (to 0x419a2300, curFrame is 0x419a248c)
06-07 14:13:21.765 14585-14585/com.example.testing.shopper D/AndroidRuntime: Shutting down VM
06-07 14:13:21.765 14585-14585/com.example.testing.shopper D/dalvikvm: threadid=1: detach (group=0x41aa3ce0)
06-07 14:13:21.765 14585-14585/com.example.testing.shopper W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41aa3ce0)
06-07 14:13:21.765 14585-14585/com.example.testing.shopper W/dalvikvm: threadid=1: uncaught exception occurred
06-07 14:13:21.765 14585-14585/com.example.testing.shopper W/System.err: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
06-07 14:13:21.772 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)

a bunch of these

06-07 14:13:21.859 14585-14585/com.example.testing.shopper D/dalvikvm: GC_FOR_ALLOC freed 5052K (46469), 38% free 8607K/13700K, paused 34ms, total 35ms
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzaE(Unknown Source)
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
06-07 14:13:21.860 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzaE(Unknown Source)

It then shows the lines where my code is above is

06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.android.gms.internal.zzbqi.zzaF(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
06-07 14:13:21.877 14585-14585/com.example.testing.shopper W/System.err:     at com.google.firebase.database.DatabaseReference.updateChildren(Unknown Source)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at com.aihsoftware.shopper.CurrentInventoryFragment.done(CurrentInventoryFragment.java:288)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at com.aihsoftware.shopper.DialogFragments.AddItemToInventoryDialogFragment$2.onClick(AddItemToInventoryDialogFragment.java:145)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:110)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     at android.os.Looper.loop(Looper.java:193)
06-07 14:13:21.878 14585-14585/com.example.testing.shopper W/System.err:     rr:     at java.lang.reflect.Method.invoke(Method.java:515)
06-07 14:13:21.894 14585-14585/com.example.testing.shopper W/System.err:    ... 557 more
06-07 14:13:21.895 14585-14585/com.example.testing.shopper W/System.err: Caused by: java.lang.StackOverflowError
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:163)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at java.lang.StringBuilder.append(StringBuilder.java:311)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri.encode(Uri.java:1864)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$PathPart.getEncoded(Uri.java:2112)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.appendSspTo(Uri.java:1216)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.makeSchemeSpecificPart(Uri.java:1205)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.getSsp(Uri.java:1188)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:     at android.net.Uri$HierarchicalUri.getSchemeSpecificPart(Uri.java:1197)
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/System.err:    ... 559 more
06-07 14:13:21.906 14585-14585/com.example.testing.shopper W/dalvikvm: threadid=1: calling UncaughtExceptionHandler

finally a bunch of this in red

06-07 14:13:21.927 14585-14585/com.example.testing.shopper E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.example.testing.shopper, PID: 14585
                                                                         java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
                                                                             at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzaE(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi$zza.zzaF(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzax(Unknown Source)

Thanks in advance everybody

EDIT: done some more digging and the invocation target is a wrapper around the stackoverflow error. forgot about pointing that out.
This means that there is a problem with URI's and the stringbuilder. does firebase database .updateChildren() not work with URI's

Body:
I found a work around. Im happy it works but not that I still dont know why the stackoverflow error is occurring.
I changed the updateChildren() to point to each individual data member of the object instead of the object itself. This worked but first there was an error which when updating an item more than once led to another tree.
For example i have
category:{
item:{
price:1
quantity:1
}
}
and it would result in
category:{
 category:{
price:2(updated)
quantity:2(updated)
}
 item:{
price:1
quantity:1
}
}
This keeps repeating for as many updates as required and I believe that is where the issue came from. However I cannot understand what the error in my code is. I always use updateChildren() as best practice.
All i can think is these lines are the problem causing multiple subcategories.I placed category in both of these as variations

databaseUpdate.put(updatedItem.getName(), updatedItem);
    inventoryDatabaseReference=inventoryDatabaseReference.child(updatedItem.getCategory());

This is what worked

databaseUpdate.put(updatedItem.getCategory()+"/"+updatedItem.getName()+"/price",price);
        databaseUpdate.put(updatedItem.getCategory()+"/"+updatedItem.getName()+"/quantity",quantity);
        databaseUpdate.put(updatedItem.getCategory()+"/"+updatedItem.getName()+"/unitName",unitType);
inventoryDatabaseReference.updateChildren(databaseUpdate)


问:
Why isn't this statement marked as completely covered by eclemma?
I am using EclEmma in Eclipse (more specifically, RSA 8).  I have the following statement in my code:

```<code>public static boolean isEmpty(Collection collection) {
    return (collection == null) || collection.isEmpty();
}
</code>```

and I have the following tests:

```<code>@Test public void isEmpty_nullCase() {
    assertTrue(CollectionUtil.isEmpty(null));
}
@Test public void isEmpty_listCase() {
    assertTrue(CollectionUtil.isEmpty(new ArrayList()));
}
</code>```

but for some reason, the statement is showing up as yellow.  What part of it am I not testing?

Thanks,
Peter

答: How about an ArrayList that has a value, and is therefore not empty?</p>

Body:
I am using EclEmma in Eclipse (more specifically, RSA 8).  I have the following statement in my code:

public static boolean isEmpty(Collection collection) {
    return (collection == null) || collection.isEmpty();
}

and I have the following tests:

@Test public void isEmpty_nullCase() {
    assertTrue(CollectionUtil.isEmpty(null));
}
@Test public void isEmpty_listCase() {
    assertTrue(CollectionUtil.isEmpty(new ArrayList()));
}

but for some reason, the statement is showing up as yellow.  What part of it am I not testing?

Thanks,
Peter