问:
Adding intellisense on custom NLog targets
I'm looking to add a thirdparty target type to NLog.xsd. You would normally create a nlog.config file like this:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      ...>
  ...
  <targets>
    <target name="file" xsi:type="File" />
  </targets>
  ...
</nlog>
```

<p>Now I want to add a new target:</p>

<pre class="lang-xml prettyprint-override"><code><targets>
  <target name="file" xsi:type="File" />
  <target name="file" xsi:type="MyTarget" />
</targets>
</code>```

XSD validation warns inside Visual Studio, since MyTarget isn't defined anywhere. I have tried adding MyTarget to NLog.xsd and reference the updated NLog.xsd, but then I get no intellisense what so ever:

<nlog xmlns="http://my-project.com/NLog.xsd" ...>
```

Any ideas how to implement this?

答:
The custom Syslog target (NLog.Targets.Syslog) has created a custom XSD that extends the XSD of NLog.

Content:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="NLog.Targets.Syslog"
           elementFormDefault="qualified"
           targetNamespace="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:sl="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd"
           xmlns:nlog="http://www.nlog-project.org/schemas/NLog.xsd">
    <xs:import namespace="http://www.nlog-project.org/schemas/NLog.xsd" />
    <xs:complexType name="Syslog">
        <xs:complexContent>
            <xs:extension base="nlog:Target">
                <xs:choice minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="name" type="xs:string" minOccurs="0" maxOccurs="1" />
                    <xs:element name="layout" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                    <xs:element name="enforcement" minOccurs="0" maxOccurs="1">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="throttling" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="limit" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="strategy" type="xs:string" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="delay" type="xs:decimal" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="limit" type="xs:integer" />
                                        <xs:attribute name="strategy" type="xs:string" />
                                        <xs:attribute name="delay" type="xs:decimal" />
                                    </xs:complexType>
                                </xs:element>
                                <xs:element name="messageProcessors" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                <xs:element name="splitOnNewLine" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="transliterate" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="replaceInvalidCharacters" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="truncateFieldsToMaxLength" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="truncateMessageTo" type="xs:integer" minOccurs="0" maxOccurs="1" />
                            </xs:choice>
                            <xs:attribute name="messageProcessors" type="xs:integer" />
                            <xs:attribute name="splitOnNewLine" type="xs:boolean" />
                            <xs:attribute name="transliterate" type="xs:boolean" />
                            <xs:attribute name="replaceInvalidCharacters" type="xs:boolean" />
                            <xs:attribute name="truncateFieldsToMaxLength" type="xs:boolean" />
                            <xs:attribute name="truncateMessageTo" type="xs:integer" />
                        </xs:complexType>
                    </xs:element>
                    <xs:element name="messageCreation" minOccurs="0" maxOccurs="1">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="facility" type="xs:string" minOccurs="0" maxOccurs="1" />
                                <xs:element name="rfc" type="xs:string" minOccurs="0" maxOccurs="1" />
                                <xs:element name="rfc3164" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="hostname" type="xs:string" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="tag" type="xs:string" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="hostname" type="xs:string" />
                                        <xs:attribute name="tag" type="xs:string" />
                                    </xs:complexType>
                                </xs:element>
                                <xs:element name="rfc5424" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="hostname" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="appName" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="procId" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="msgId" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="structuredData" minOccurs="0" maxOccurs="1">
                                                <xs:complexType>
                                                    <xs:choice minOccurs="0" maxOccurs="1">
                                                        <xs:element name="fromEventProperties" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                                        <xs:element name="sdElement" minOccurs="1" maxOccurs="unbounded">
                                                            <xs:complexType>
                                                                <xs:sequence>
                                                                    <xs:element name="sdParam" minOccurs="1" maxOccurs="unbounded">
                                                                        <xs:complexType>
                                                                            <xs:simpleContent>
                                                                                <xs:extension base="xs:string">
                                                                                <xs:attribute name="name" type="xs:string" use="required" />
                                                                                <xs:attribute name="value" type="xs:string" use="required" />
                                                                                </xs:extension>
                                                                            </xs:simpleContent>
                                                                        </xs:complexType>
                                                                    </xs:element>
                                                                </xs:sequence>
                                                                <xs:attribute name="sdId" type="xs:string" use="required" />
                                                            </xs:complexType>
                                                        </xs:element>
                                                    </xs:choice>
                                                </xs:complexType>
                                            </xs:element>
                                            <xs:element name="disableBom" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="hostname" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="appName" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="procId" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="msgId" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="disableBom" type="xs:boolean" />
                                    </xs:complexType>
                                </xs:element>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                    <xs:element name="messageSend" minOccurs="0" maxOccurs="1">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="protocol" type="xs:string" minOccurs="0" maxOccurs="1" />
                                <xs:element name="udp" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="server" type="xs:string" minOccurs="1" maxOccurs="1" />
                                            <xs:element name="port" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="server" type="xs:string" />
                                        <xs:attribute name="port" type="xs:integer" />
                                    </xs:complexType>
                                </xs:element>
                                <xs:element name="tcp" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="server" type="xs:string" minOccurs="1" maxOccurs="1" />
                                            <xs:element name="port" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="keepAlive" minOccurs="0" maxOccurs="1">
                                                <xs:complexType>
                                                    <xs:choice minOccurs="0" maxOccurs="unbounded">
                                                        <xs:element name="enabled" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                                        <xs:element name="timeout" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                                        <xs:element name="interval" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                                    </xs:choice>
                                                    <xs:attribute name="enabled" type="xs:boolean" />
                                                    <xs:attribute name="timeout" type="xs:integer" />
                                                    <xs:attribute name="interval" type="xs:integer" />
                                                </xs:complexType>
                                            </xs:element>
                                            <xs:element name="reconnectInterval" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="useTls" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="framing" type="xs:string" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="dataChunkSize" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="server" type="xs:string" />
                                        <xs:attribute name="port" type="xs:integer" />
                                        <xs:attribute name="reconnectInterval" type="xs:integer" />
                                        <xs:attribute name="useTls" type="xs:boolean" />
                                        <xs:attribute name="framing" type="xs:string" />
                                        <xs:attribute name="dataChunkSize" type="xs:integer" />
                                    </xs:complexType>
                                </xs:element>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                </xs:choice>
                <xs:attribute name="name" type="xs:string" />
                <xs:attribute name="layout" type="nlog:SimpleLayoutAttribute" />
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
</xs:schema>
```

<p>Usage: (this one is published on http://nlog-project.org/)</p>

<pre class="lang-xml prettyprint-override"><code><nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:sl="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd">
</code>```

and

<target xsi:type="sl:Syslog" name="syslog3164-tgt">
```

<p>instead of
</p>

```<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
```

<p>See also https://github.com/NLog/NLog.github.io/pull/56</p>

<p>Update: Visual Studio also needed this:</p>

<pre class="lang-xml prettyprint-override"><code><nlog xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd"  .. >
</code>```

Body:
I'm looking to add a thirdparty target type to NLog.xsd. You would normally create a nlog.config file like this:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      ...>
  ...
  <targets>
    <target name="file" xsi:type="File" />
  </targets>
  ...
</nlog>

Now I want to add a new target:

<targets>
  <target name="file" xsi:type="File" />
  <target name="file" xsi:type="MyTarget" />
</targets>

XSD validation warns inside Visual Studio, since MyTarget isn't defined anywhere. I have tried adding MyTarget to NLog.xsd and reference the updated NLog.xsd, but then I get no intellisense what so ever:

<nlog xmlns="http://my-project.com/NLog.xsd" ...>

Any ideas how to implement this?

Body:
The custom Syslog target (NLog.Targets.Syslog) has created a custom XSD that extends the XSD of NLog.

Content:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="NLog.Targets.Syslog"
           elementFormDefault="qualified"
           targetNamespace="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:sl="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd"
           xmlns:nlog="http://www.nlog-project.org/schemas/NLog.xsd">
    <xs:import namespace="http://www.nlog-project.org/schemas/NLog.xsd" />
    <xs:complexType name="Syslog">
        <xs:complexContent>
            <xs:extension base="nlog:Target">
                <xs:choice minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="name" type="xs:string" minOccurs="0" maxOccurs="1" />
                    <xs:element name="layout" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                    <xs:element name="enforcement" minOccurs="0" maxOccurs="1">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="throttling" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="limit" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="strategy" type="xs:string" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="delay" type="xs:decimal" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="limit" type="xs:integer" />
                                        <xs:attribute name="strategy" type="xs:string" />
                                        <xs:attribute name="delay" type="xs:decimal" />
                                    </xs:complexType>
                                </xs:element>
                                <xs:element name="messageProcessors" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                <xs:element name="splitOnNewLine" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="transliterate" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="replaceInvalidCharacters" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="truncateFieldsToMaxLength" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                <xs:element name="truncateMessageTo" type="xs:integer" minOccurs="0" maxOccurs="1" />
                            </xs:choice>
                            <xs:attribute name="messageProcessors" type="xs:integer" />
                            <xs:attribute name="splitOnNewLine" type="xs:boolean" />
                            <xs:attribute name="transliterate" type="xs:boolean" />
                            <xs:attribute name="replaceInvalidCharacters" type="xs:boolean" />
                            <xs:attribute name="truncateFieldsToMaxLength" type="xs:boolean" />
                            <xs:attribute name="truncateMessageTo" type="xs:integer" />
                        </xs:complexType>
                    </xs:element>
                    <xs:element name="messageCreation" minOccurs="0" maxOccurs="1">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="facility" type="xs:string" minOccurs="0" maxOccurs="1" />
                                <xs:element name="rfc" type="xs:string" minOccurs="0" maxOccurs="1" />
                                <xs:element name="rfc3164" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="hostname" type="xs:string" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="tag" type="xs:string" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="hostname" type="xs:string" />
                                        <xs:attribute name="tag" type="xs:string" />
                                    </xs:complexType>
                                </xs:element>
                                <xs:element name="rfc5424" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="hostname" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="appName" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="procId" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="msgId" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="structuredData" minOccurs="0" maxOccurs="1">
                                                <xs:complexType>
                                                    <xs:choice minOccurs="0" maxOccurs="1">
                                                        <xs:element name="fromEventProperties" type="nlog:Layout" minOccurs="0" maxOccurs="1" />
                                                        <xs:element name="sdElement" minOccurs="1" maxOccurs="unbounded">
                                                            <xs:complexType>
                                                                <xs:sequence>
                                                                    <xs:element name="sdParam" minOccurs="1" maxOccurs="unbounded">
                                                                        <xs:complexType>
                                                                            <xs:simpleContent>
                                                                                <xs:extension base="xs:string">
                                                                                <xs:attribute name="name" type="xs:string" use="required" />
                                                                                <xs:attribute name="value" type="xs:string" use="required" />
                                                                                </xs:extension>
                                                                            </xs:simpleContent>
                                                                        </xs:complexType>
                                                                    </xs:element>
                                                                </xs:sequence>
                                                                <xs:attribute name="sdId" type="xs:string" use="required" />
                                                            </xs:complexType>
                                                        </xs:element>
                                                    </xs:choice>
                                                </xs:complexType>
                                            </xs:element>
                                            <xs:element name="disableBom" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="hostname" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="appName" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="procId" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="msgId" type="nlog:SimpleLayoutAttribute" />
                                        <xs:attribute name="disableBom" type="xs:boolean" />
                                    </xs:complexType>
                                </xs:element>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                    <xs:element name="messageSend" minOccurs="0" maxOccurs="1">
                        <xs:complexType>
                            <xs:choice minOccurs="0" maxOccurs="unbounded">
                                <xs:element name="protocol" type="xs:string" minOccurs="0" maxOccurs="1" />
                                <xs:element name="udp" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="server" type="xs:string" minOccurs="1" maxOccurs="1" />
                                            <xs:element name="port" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="server" type="xs:string" />
                                        <xs:attribute name="port" type="xs:integer" />
                                    </xs:complexType>
                                </xs:element>
                                <xs:element name="tcp" minOccurs="0" maxOccurs="1">
                                    <xs:complexType>
                                        <xs:choice minOccurs="0" maxOccurs="unbounded">
                                            <xs:element name="server" type="xs:string" minOccurs="1" maxOccurs="1" />
                                            <xs:element name="port" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="keepAlive" minOccurs="0" maxOccurs="1">
                                                <xs:complexType>
                                                    <xs:choice minOccurs="0" maxOccurs="unbounded">
                                                        <xs:element name="enabled" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                                        <xs:element name="timeout" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                                        <xs:element name="interval" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                                    </xs:choice>
                                                    <xs:attribute name="enabled" type="xs:boolean" />
                                                    <xs:attribute name="timeout" type="xs:integer" />
                                                    <xs:attribute name="interval" type="xs:integer" />
                                                </xs:complexType>
                                            </xs:element>
                                            <xs:element name="reconnectInterval" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="useTls" type="xs:boolean" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="framing" type="xs:string" minOccurs="0" maxOccurs="1" />
                                            <xs:element name="dataChunkSize" type="xs:integer" minOccurs="0" maxOccurs="1" />
                                        </xs:choice>
                                        <xs:attribute name="server" type="xs:string" />
                                        <xs:attribute name="port" type="xs:integer" />
                                        <xs:attribute name="reconnectInterval" type="xs:integer" />
                                        <xs:attribute name="useTls" type="xs:boolean" />
                                        <xs:attribute name="framing" type="xs:string" />
                                        <xs:attribute name="dataChunkSize" type="xs:integer" />
                                    </xs:complexType>
                                </xs:element>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                </xs:choice>
                <xs:attribute name="name" type="xs:string" />
                <xs:attribute name="layout" type="nlog:SimpleLayoutAttribute" />
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
</xs:schema>

Usage: (this one is published on http://nlog-project.org/)

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:sl="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd">

and

<target xsi:type="sl:Syslog" name="syslog3164-tgt">

instead of

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

See also https://github.com/NLog/NLog.github.io/pull/56

Update: Visual Studio also needed this:

<nlog xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd http://www.nlog-project.org/schemas/NLog.Targets.Syslog.xsd"  .. >


来源: stackexchange

问:
Sum up every N elements of a list?
I have a list of numbers like this:

```<code>[ 0, 1, 2, 3, 4, 5, 6, 7 ]
</code>```

How to sum up every N (let's assume 2) elements in an elegant way and transform the list into:

```<code>[ 1, 5, 9, 13 ]
</code>```

edit:
I came up with the following solution:

```<code>    List<Double> input = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
    List<Double> output = new ArrayList<>();

    int N = 2;
    IntStream.range(0, (input.size() + N - 1) / N)
            .mapToObj(i -> input.subList(i * N, Math.min(N * (i + 1), input.size())))
            .mapToDouble(l -> l.stream().mapToDouble(Double::doubleValue).sum())
            .forEach(output::add);

    System.out.println(output);
</code>```

It works, but I'm still looking for a more readable and simple one.

答:
Given:

```<code>List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7);
int nth = 2;
</code>```

How about:

```<code>IntStream.iterate(0, idx -> idx + nth)
         .limit(numbers.size() / nth)
         .map(idx -> IntStream.range(idx, idx + nth)
                              .reduce((sum, index) -> sum + numbers.get(index))
                              .orElse(0))
         .forEach(System.out::println);
</code>```

Or alternatively:

```<code>IntStream.range(0, numbers.size() / nth)
         .map(idx -> IntStream.range(idx * nth, (idx + 1) * nth)
                              .map(index -> numbers.get(index))
                              .sum())
         .forEach(System.out::println);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sum up every N elements of a list?

Body:
I have a list of numbers like this:

[ 0, 1, 2, 3, 4, 5, 6, 7 ]

How to sum up every N (let's assume 2) elements in an elegant way and transform the list into:

[ 1, 5, 9, 13 ]

edit:
I came up with the following solution:

    List<Double> input = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
    List<Double> output = new ArrayList<>();

    int N = 2;
    IntStream.range(0, (input.size() + N - 1) / N)
            .mapToObj(i -> input.subList(i * N, Math.min(N * (i + 1), input.size())))
            .mapToDouble(l -> l.stream().mapToDouble(Double::doubleValue).sum())
            .forEach(output::add);

    System.out.println(output);

It works, but I'm still looking for a more readable and simple one.

Body:
Given:

List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7);
int nth = 2;

How about:

IntStream.iterate(0, idx -> idx + nth)
         .limit(numbers.size() / nth)
         .map(idx -> IntStream.range(idx, idx + nth)
                              .reduce((sum, index) -> sum + numbers.get(index))
                              .orElse(0))
         .forEach(System.out::println);

Or alternatively:

IntStream.range(0, numbers.size() / nth)
         .map(idx -> IntStream.range(idx * nth, (idx + 1) * nth)
                              .map(index -> numbers.get(index))
                              .sum())
         .forEach(System.out::println);


问:
Wordpress - Condition with parent term
I created a Custom Post Type "Produit" with a taxonomy "Produits".
Inside of it i created three parent term ("Securite", "Confort", "Fermeture") this three parents terms have child term and all child term have posts.

In my Home page i display all my child term

When i clicked on a item i'm redirect in child term page (exemple url: 'produits/securite/alarme/'). My problem is the three parents terms have three differents colors to display on the child term page.

```<code>"SECURITE" -> orange
"CONFORT" -> pink
"FERMETURE" -> blue
</code>```

So i need to know what is the parent term of the child term to add the good colors in the page.

I searched in the wordpress conditions but i don't find the solution.
I don't know if my explains is clear but anyone know how can i make it ? Thank you

答:
You can retrieve the parent taxonomy by using the follow:

```<code>// Get the child term
$child = get_term($id, 'produits');

// get_term returns an object with "parent" as a variable.
// the "parent" variable will return the parent term ID, or 0 if there is no parent.
$parent = ($child->parent == 0) ? $child : get_term($child->parent, 'produits');
</code>```

You can also use wp_get_post_terms( $post_id, $taxonomy, $args ); to retrieve the terms of the post. From there you can loop through the returned terms and find the parents using the method noted above.

WP Codex get_term()

WP Codex wp_get_post_terms()

Title: Wordpress - Condition with parent term

Body:
I created a Custom Post Type "Produit" with a taxonomy "Produits".
Inside of it i created three parent term ("Securite", "Confort", "Fermeture") this three parents terms have child term and all child term have posts.

In my Home page i display all my child term

When i clicked on a item i'm redirect in child term page (exemple url: 'produits/securite/alarme/'). My problem is the three parents terms have three differents colors to display on the child term page.

"SECURITE" -> orange
"CONFORT" -> pink
"FERMETURE" -> blue

So i need to know what is the parent term of the child term to add the good colors in the page.

I searched in the wordpress conditions but i don't find the solution.
I don't know if my explains is clear but anyone know how can i make it ? Thank you

Body:
You can retrieve the parent taxonomy by using the follow:

// Get the child term
$child = get_term($id, 'produits');

// get_term returns an object with "parent" as a variable.
// the "parent" variable will return the parent term ID, or 0 if there is no parent.
$parent = ($child->parent == 0) ? $child : get_term($child->parent, 'produits');

You can also use wp_get_post_terms( $post_id, $taxonomy, $args ); to retrieve the terms of the post. From there you can loop through the returned terms and find the parents using the method noted above.

WP Codex get_term()

WP Codex wp_get_post_terms()


问:
Incorrect syntax near '/'. in SQL Server 2012
I am trying to apply divide operator in this statement, but it throws an error

Incorrect syntax near '/'

I am using SQL Server 2012

```<code>(select count(distinct emploc) as test from location) /
(select count(emploc) from location)
</code>```

答:
you can use it in single query</p>

```<code>SELECT count(distinct emploc)/convert(float,count(emploc)) as Test from location
</code>```

Body:
I am trying to apply divide operator in this statement, but it throws an error

Incorrect syntax near '/'

I am using SQL Server 2012

(select count(distinct emploc) as test from location) /
(select count(emploc) from location)

Body:
you can use it in single query

SELECT count(distinct emploc)/convert(float,count(emploc)) as Test from location


问:
Hide div element when screen size is smaller than a specific size
I have a div element that I want to hide when the width of the browser is less than or equal to 1026px. Is this possible to do with the css:    @media only screen and (min-width: 1140px) {}    If it isn't possible with css, Is there any alternative?

Extra info:
When the div element is hidden, I don't want a blank white gap. I'd like the page to flow as it would if I deleted the div element entirely from the code.

The div I am hiding is

.

HTML5 Doctype.

I used javascript to place a gallery into that div.

I want it to look like this when it is bigger than 1026px width:

I want it to look like this when it is less than 1026px width:

答:
if you are using bootstrap u can just use the hidden-sm ( lg or md or xs) depending on what u want. u can then go into the css file and specify the percentages u want it to show on. in the sample below it will be hiding on large screens, medium ones and extra small ones but show on small screens by taking half of the screen.</p>

```<code><div class="col-sm-12 hidden-lg hidden-md hidden-xs">what ever you want</div>
</code>```

Body:
if you are using bootstrap u can just use the hidden-sm ( lg or md or xs) depending on what u want. u can then go into the css file and specify the percentages u want it to show on. in the sample below it will be hiding on large screens, medium ones and extra small ones but show on small screens by taking half of the screen.

<div class="col-sm-12 hidden-lg hidden-md hidden-xs">what ever you want</div>


答:
You need select before the expression:

```<code>select ((select count(distinct emploc) as test from location) /
        (select count(emploc) from location)
       )
</code>```

A SQL query begins with select.  In a few cases, you can start with (select . . . (such as when using union all).  The SQL parser is not a generic expression parser for arithmetic expressions, so select 2/1 works, but not 2/1.

Title: Incorrect syntax near '/'. in SQL Server 2012

Body:
You need select before the expression:

select ((select count(distinct emploc) as test from location) /
        (select count(emploc) from location)
       )

A SQL query begins with select.  In a few cases, you can start with (select . . . (such as when using union all).  The SQL parser is not a generic expression parser for arithmetic expressions, so select 2/1 works, but not 2/1.


问:
Go web crawler gets stuck
I'm new to Go and trying to implement a web crawler. It should asynchronously parse web pages and save their contents to files, one file per new page. But it gets stuck after I've added

```<code>u, _ := url.Parse(uri)
fileName := u.Host + u.RawQuery + ".html"
body, err := ioutil.ReadAll(resp.Body)
writes <- writer{fileName: fileName, body: body}
</code>```

Can anyone help me fix this problem? Basically I want to get data from the response body, push it to the channel, and then get data from the channel and put it into a file.
It looks like the writes channel was not initialized, and sending on a nil channel blocks forever.

```<code>package main

import (
    "crypto/tls"
    "flag"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
    "runtime"

    "./linksCollector"
)

type writer struct {
    fileName string
    body     []byte
}

var writes = make(chan writer)

func usage() {
    fmt.Fprintf(os.Stderr, "usage: crawl http://example.com/")
    flag.PrintDefaults()
    os.Exit(2)
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    runtime.GOMAXPROCS(8)
    flag.Usage = usage
    flag.Parse()

    args := flag.Args()
    fmt.Println(args)
    if len(args) < 1 {
        usage()
        fmt.Println("Please specify start page")
        os.Exit(1)
    }

    queue := make(chan string)
    filteredQueue := make(chan string)

    go func() { queue <- args[0] }()
    go filterQueue(queue, filteredQueue)

    for uri := range filteredQueue {
        go enqueue(uri, queue)
    }

    for {
        select {
        case data := <-writes:
            f, err := os.Create(data.fileName)
            check(err)
            defer f.Close()
            _, err = f.Write(data.body)
            check(err)
        }
    }
}

func filterQueue(in chan string, out chan string) {
    var seen = make(map[string]bool)
    for val := range in {
        if !seen[val] {
            seen[val] = true
            out <- val
        }
    }
}

func enqueue(uri string, queue chan string) {
    fmt.Println("fetching", uri)
    transport := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }
    client := http.Client{Transport: transport}
    resp, err := client.Get(uri)
    check(err)

    defer resp.Body.Close()

    u, _ := url.Parse(uri)
    fileName := u.Host + u.RawQuery + ".html"
    body, err := ioutil.ReadAll(resp.Body)
    writes <- writer{fileName: fileName, body: body}

    links := collectlinks.All(resp.Body)

    for _, link := range links {
        absolute := fixURL(link, uri)
        if uri != "" {
            go func() { queue <- absolute }()
        }
    }
}

func fixURL(href, base string) string {
    uri, err := url.Parse(href)
    if err != nil {
        return ""
    }
    baseURL, err := url.Parse(base)
    if err != nil {
        return ""
    }
    uri = baseURL.ResolveReference(uri)
    return uri.String()
}
</code>```

答:
Your for loop ends up calling go enqueue more than once before the select receives the data causing the send to writes to crash the program, I think, I'm not really that familiar with Go's concurrency.

Update: I'm sorry for the previous answer, it was a poorly informed attempt at explaining something I have only limited knowledge about. After taking a closer look I am almost certain of two things. 1. Your writes channel is not nil, you can rely on make to initilize your channels. 2. A range loop over a channel will block until that channel is closed. So your

```<code>for uri := range filteredQueue {
    go enqueue(uri, queue)
}
</code>```

is blocking, therefore your program never reaches the select and so is unable to receive from the writes channel. You can avoid this by executing the range loop in a new goroutine.

```<code>go func() {
    for uri := range filteredQueue {
        go enqueue(uri, queue)
    }
}()
</code>```

Your program, as is, will still break for other reasons but you should be able to fix that with a little synchronization using a sync.WaitGroup.
Here's a simplified example: https://play.golang.org/p/o2Oj4g8c2y.

Title: Go web crawler gets stuck

Body:
I'm new to Go and trying to implement a web crawler. It should asynchronously parse web pages and save their contents to files, one file per new page. But it gets stuck after I've added

u, _ := url.Parse(uri)
fileName := u.Host + u.RawQuery + ".html"
body, err := ioutil.ReadAll(resp.Body)
writes <- writer{fileName: fileName, body: body}

Can anyone help me fix this problem? Basically I want to get data from the response body, push it to the channel, and then get data from the channel and put it into a file.
It looks like the writes channel was not initialized, and sending on a nil channel blocks forever.

package main

import (
    "crypto/tls"
    "flag"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
    "runtime"

    "./linksCollector"
)

type writer struct {
    fileName string
    body     []byte
}

var writes = make(chan writer)

func usage() {
    fmt.Fprintf(os.Stderr, "usage: crawl http://example.com/")
    flag.PrintDefaults()
    os.Exit(2)
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {
    runtime.GOMAXPROCS(8)
    flag.Usage = usage
    flag.Parse()

    args := flag.Args()
    fmt.Println(args)
    if len(args) < 1 {
        usage()
        fmt.Println("Please specify start page")
        os.Exit(1)
    }

    queue := make(chan string)
    filteredQueue := make(chan string)

    go func() { queue <- args[0] }()
    go filterQueue(queue, filteredQueue)

    for uri := range filteredQueue {
        go enqueue(uri, queue)
    }

    for {
        select {
        case data := <-writes:
            f, err := os.Create(data.fileName)
            check(err)
            defer f.Close()
            _, err = f.Write(data.body)
            check(err)
        }
    }
}

func filterQueue(in chan string, out chan string) {
    var seen = make(map[string]bool)
    for val := range in {
        if !seen[val] {
            seen[val] = true
            out <- val
        }
    }
}

func enqueue(uri string, queue chan string) {
    fmt.Println("fetching", uri)
    transport := &http.Transport{
        TLSClientConfig: &tls.Config{
            InsecureSkipVerify: true,
        },
    }
    client := http.Client{Transport: transport}
    resp, err := client.Get(uri)
    check(err)

    defer resp.Body.Close()

    u, _ := url.Parse(uri)
    fileName := u.Host + u.RawQuery + ".html"
    body, err := ioutil.ReadAll(resp.Body)
    writes <- writer{fileName: fileName, body: body}

    links := collectlinks.All(resp.Body)

    for _, link := range links {
        absolute := fixURL(link, uri)
        if uri != "" {
            go func() { queue <- absolute }()
        }
    }
}

func fixURL(href, base string) string {
    uri, err := url.Parse(href)
    if err != nil {
        return ""
    }
    baseURL, err := url.Parse(base)
    if err != nil {
        return ""
    }
    uri = baseURL.ResolveReference(uri)
    return uri.String()
}

Body:
Your for loop ends up calling go enqueue more than once before the select receives the data causing the send to writes to crash the program, I think, I'm not really that familiar with Go's concurrency.

Update: I'm sorry for the previous answer, it was a poorly informed attempt at explaining something I have only limited knowledge about. After taking a closer look I am almost certain of two things. 1. Your writes channel is not nil, you can rely on make to initilize your channels. 2. A range loop over a channel will block until that channel is closed. So your

for uri := range filteredQueue {
    go enqueue(uri, queue)
}

is blocking, therefore your program never reaches the select and so is unable to receive from the writes channel. You can avoid this by executing the range loop in a new goroutine.

go func() {
    for uri := range filteredQueue {
        go enqueue(uri, queue)
    }
}()

Your program, as is, will still break for other reasons but you should be able to fix that with a little synchronization using a sync.WaitGroup.
Here's a simplified example: https://play.golang.org/p/o2Oj4g8c2y.


问:
Root Cannot Open a PDF Ubuntu while users can
I'm using Ubuntu 16.04 and I tried to open a pdf using evince.

It worked well when I'm logged in the normal user but not when I'm using sudo or switch to root user.

答:
It's all about the permission to access the display server.

Generally, depending on your setup, you may need to allow root to access the xserver. https://askubuntu.com/a/175615/668478

If you run on mir, you should use gksudo to allow root to access mir.


问:
How to pass data from an activity to a fragment in TabHost?
I have a page divided like this: there is the "Main" layout which holds a fragment

```<code><fragment
    android:name="com.x.x.FirstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/firstFragment"
    tools:layout="@layout/first_fragment" />
</code>```

Inside that fragment in an external layout I've created a TabHost like this:

```<code><TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost">

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

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/first"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.First"
                tools:layout="@layout/first" />

            <fragment
                android:id="@+id/second"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.Second"
                tools:layout="@layout/second" />

        </FrameLayout>
    </LinearLayout>
</TabHost>
</code>```

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.

答:
You should define a public method inside First fragment and invoke when push button on MainACtivity. Be aware of that fragment is currently shown if you want to update some fragment's UI element.

Take a look at Fragments developer guide.

Likewise, your activity can call methods in the fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById() or findFragmentByTag().

Body:
I have a page divided like this: there is the "Main" layout which holds a fragment

<fragment
    android:name="com.x.x.FirstFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/firstFragment"
    tools:layout="@layout/first_fragment" />

Inside that fragment in an external layout I've created a TabHost like this:

<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost">

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

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/first"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.First"
                tools:layout="@layout/first" />

            <fragment
                android:id="@+id/second"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:name="com.x.x.Second"
                tools:layout="@layout/second" />

        </FrameLayout>
    </LinearLayout>
</TabHost>

The problem is that I need to run a method inside the "First" class when a button inside the "Main" class has been clicked.

I've been struggling with this problem since yesterday, is there any solution?

Thank you.


问:
How to scan a column for a certain word and when triggered, remove the first 4 characters
Hey everyone so here is my setup

My issue is regarding the "C" column and how to remove the "2nd|" and "3rd|" portions so it ONLY shows "Mikes Auto Shop" "Carls Auto Repair" etc

Like this

答:
If there is only sometimes a prefix or if it can be larger than 9, you can use:</p>

```<code>=RIGHT(C2,LEN(C2)-IFERROR(FIND("|",C2),0))
</code>```

Body:
If there is only sometimes a prefix or if it can be larger than 9, you can use:

=RIGHT(C2,LEN(C2)-IFERROR(FIND("|",C2),0))


问:
ImportError: No module named boto3
Installed the boto3 and upgraded it to the latest release. I tried the easy install pip for installation. I have multiple versions of python installed so I even tried installing in virtualenv venv. But I get the same error: "No module named boto3".

```<code>pip install boto3

python
Python 2.7.11 (default, Mar 10 2016, 14:12:44)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named boto3
>>>
</code>```

I tried with / without sudo:

```<code>sudo pip install boto3
</code>```

I`m trying to install AWS SDK on Raspberry Pi.

```<code>pip freeze
</code>```

shows "boto3==1.3.0" installed.

```<code>sudo pip install boto3

Requirement already satisfied (use --upgrade to upgrade): boto3 in    /usr/local/lib/python2.7/dist-packages
Requirement already satisfied (use --upgrade to upgrade): botocore>=1.4.1, <1.5.0 in /usr/local/lib/python2.7/dist-packages (from boto3)
Requirement already satisfied (use --upgrade to upgrade): jmespath>=0.7.1,<1.0.0 in /usr/local/lib/python2.7/dist-packages (from boto3)
Requirement already satisfied (use --upgrade to upgrade): futures>=2.2.0,<4.0.0 in /usr/local/lib/python2.7/dist-packages (from boto3)
Requirement already satisfied (use --upgrade to upgrade): python-dateutil>=2.1,<3.0.0 in /usr/local/lib/python2.7/dist-packages (from botocore>=1.4.1,<1.5.0->boto3)
Requirement already satisfied (use --upgrade to upgrade): docutils>=0.10 in /usr/local/lib/python2.7/dist-packages (from botocore>=1.4.1,<1.5.0->boto3)
Requirement already satisfied (use --upgrade to upgrade): six>=1.5 in /usr/local/lib/python2.7/dist-packages (from python-dateutil>=2.1,<3.0.0->botocore>=1.4.1,<1.5.0->boto3)
Cleaning up...
</code>```

答:
Globally for my mac, this worked</p>

```<code>sudo pip install --ignore-installed six boto3
</code>```

Title: ImportError: No module named boto3

Body:
Installed the boto3 and upgraded it to the latest release. I tried the easy install pip for installation. I have multiple versions of python installed so I even tried installing in virtualenv venv. But I get the same error: "No module named boto3".

pip install boto3

python
Python 2.7.11 (default, Mar 10 2016, 14:12:44)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named boto3
>>>

I tried with / without sudo:

sudo pip install boto3

I`m trying to install AWS SDK on Raspberry Pi.

pip freeze

shows "boto3==1.3.0" installed.

sudo pip install boto3

Requirement already satisfied (use --upgrade to upgrade): boto3 in    /usr/local/lib/python2.7/dist-packages
Requirement already satisfied (use --upgrade to upgrade): botocore>=1.4.1, <1.5.0 in /usr/local/lib/python2.7/dist-packages (from boto3)
Requirement already satisfied (use --upgrade to upgrade): jmespath>=0.7.1,<1.0.0 in /usr/local/lib/python2.7/dist-packages (from boto3)
Requirement already satisfied (use --upgrade to upgrade): futures>=2.2.0,<4.0.0 in /usr/local/lib/python2.7/dist-packages (from boto3)
Requirement already satisfied (use --upgrade to upgrade): python-dateutil>=2.1,<3.0.0 in /usr/local/lib/python2.7/dist-packages (from botocore>=1.4.1,<1.5.0->boto3)
Requirement already satisfied (use --upgrade to upgrade): docutils>=0.10 in /usr/local/lib/python2.7/dist-packages (from botocore>=1.4.1,<1.5.0->boto3)
Requirement already satisfied (use --upgrade to upgrade): six>=1.5 in /usr/local/lib/python2.7/dist-packages (from python-dateutil>=2.1,<3.0.0->botocore>=1.4.1,<1.5.0->boto3)
Cleaning up...

Body:
Globally for my mac, this worked

sudo pip install --ignore-installed six boto3


问:
Excel IFS formula - range of number
I have a value in cell AB8 and I want to conditionally return a status depending on which value it takes between 1 and 30.

I want to save time and rather than type the scores 1-9 indivdually to turn into "EMERGING" (etc) is there a way I can put a range in?

```<code>IFS(AB8=1,"EMERGING",AB8=2,"EMERGING",AB8=3,"EMERGING",AB8=4,"EMERGING",AB8=5,"EMERGING",AB8=6,"EMERGING",AB8=7,"EMERGING",AB8=8,"EMERGING",AB8=9,"DEVELOPING",AB8=10,"DEVELOPING",AB8=11,"DEVELOPING",AB8=12,"DEVELOPING",AB8=13,"DEVELOPING",AB8=14,"DEVELOPING",AB8=15,"DEVELOPING",AB8=16,"DEVELOPING",AB8=17,"SECURING",AB8=18,"SECURING",AB8=19,"SECURING",AB8=20,"SECURING",AB8=21,"SECURING",AB8=22,"SECURING",AB8=23,"SECURING",AB8=24,"SECURING",AB8=25,"READY",AB8=26,"READY",AB8=27,"READY",AB8=28,"READY",AB8=29,"READY",AB8=30,"READY")
</code>```

答:
CallumDA's answer is more clean.

But this can be accomplished with nested IF formulas.

```<code>=IF(AB8>=1,IF(AB8<=8,"EMERGING",IF(AB8<=16,"DEVELOPING",IF(AB8<=24,"SECURING",IF(AB8<=30,"READY")))))
</code>```

Title: Excel IFS formula - range of number

Body:
I have a value in cell AB8 and I want to conditionally return a status depending on which value it takes between 1 and 30.

I want to save time and rather than type the scores 1-9 indivdually to turn into "EMERGING" (etc) is there a way I can put a range in?

IFS(AB8=1,"EMERGING",AB8=2,"EMERGING",AB8=3,"EMERGING",AB8=4,"EMERGING",AB8=5,"EMERGING",AB8=6,"EMERGING",AB8=7,"EMERGING",AB8=8,"EMERGING",AB8=9,"DEVELOPING",AB8=10,"DEVELOPING",AB8=11,"DEVELOPING",AB8=12,"DEVELOPING",AB8=13,"DEVELOPING",AB8=14,"DEVELOPING",AB8=15,"DEVELOPING",AB8=16,"DEVELOPING",AB8=17,"SECURING",AB8=18,"SECURING",AB8=19,"SECURING",AB8=20,"SECURING",AB8=21,"SECURING",AB8=22,"SECURING",AB8=23,"SECURING",AB8=24,"SECURING",AB8=25,"READY",AB8=26,"READY",AB8=27,"READY",AB8=28,"READY",AB8=29,"READY",AB8=30,"READY")

Body:
CallumDA's answer is more clean.

But this can be accomplished with nested IF formulas.

=IF(AB8>=1,IF(AB8<=8,"EMERGING",IF(AB8<=16,"DEVELOPING",IF(AB8<=24,"SECURING",IF(AB8<=30,"READY")))))


问:
How to test javascript code that calls window objects
I have the following JavaScript code:

```<code>if (Notification.permission !== 'granted') {
    return Notification.permission
}
</code>```

When I run Mocha tests on some code that uses this, the test fails:

ReferenceError: Notification is not defined

I thought I could make this work, by doing this:

```<code>sinon.stub(Notification, 'permission')
</code>```

However, I still get the same error.

How do I prevent this error?

答:
You should first test if Notification exists before you run Notification.permission.

One way to do that, would be to replace...

```<code>if (Notification.permission !== 'granted') {
    return Notification.permission
}
</code>```

... with this:

```<code>if (typeof Notification !== typeof undefined && Notification.permission !== 'granted') {
    return Notification.permission
}
</code>```

Body:
I have the following JavaScript code:

if (Notification.permission !== 'granted') {
    return Notification.permission
}

When I run Mocha tests on some code that uses this, the test fails:

ReferenceError: Notification is not defined

I thought I could make this work, by doing this:

sinon.stub(Notification, 'permission')

However, I still get the same error.

How do I prevent this error?

Body:
You should first test if Notification exists before you run Notification.permission.

One way to do that, would be to replace...

if (Notification.permission !== 'granted') {
    return Notification.permission
}

... with this:

if (typeof Notification !== typeof undefined && Notification.permission !== 'granted') {
    return Notification.permission
}


问:
High level data structures in html data attribute
I am happy that the html5 data attribute exists.

I can write a simple string into html attributes and access them via jquery.

But .... wouldn't it be nice to have more than a simple string?

Is there no way to encode JSON into these data attributes.

In my current use case I need to store a list of strings in a html5 data attribute.

答:
```<code>   <div id ="test" data-something='{"something":"something"}'></div>
</code>```

string in the data-attribute is automatically converted to a JavaScript object.

you can access this in javascript like this.

```<code>var somethingObject = $("#test").data("something");

var jsonSomethingObject = JSON.stringify(somethingObject);

console.log(somethingObject); //this will print the main javascript object
console.log(jsonSomethingObject);// this will print stringify javascript object
</code>```

you can refer the snippet for same

var someObject = $("#test").data("student");

var jsonData = JSON.stringify(someObject);

 $('#display').text("id:"+someObject.id +" name:"+someObject.name)
console.log(someObject);
console.log(jsonData);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" data-student='{"name": "Dhiraj", "id": 1}' />

<div id="display"></div></code>```

Body:
   <div id ="test" data-something='{"something":"something"}'></div>

string in the data-attribute is automatically converted to a JavaScript object.

you can access this in javascript like this.

var somethingObject = $("#test").data("something");

var jsonSomethingObject = JSON.stringify(somethingObject);

console.log(somethingObject); //this will print the main javascript object
console.log(jsonSomethingObject);// this will print stringify javascript object

you can refer the snippet for same

var someObject = $("#test").data("student");

var jsonData = JSON.stringify(someObject);

 $('#display').text("id:"+someObject.id +" name:"+someObject.name)
console.log(someObject);
console.log(jsonData);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" data-student='{"name": "Dhiraj", "id": 1}' />

<div id="display"></div>


问:
Snap Recyclerview item to Center when loaded
I am using an infinite scroll for recyclerview with X items which repeats.
Also i want am using PagerSnapHelper() to snap the scroll like viewpager.

So initially when the list is loaded the display is like -

As soon as i start scrolling on either side left or right the PageSnapHelper() come in work an snap it like viewpager with center alignment like this -

I want to show recyclerview as like 2nd image when initially loaded. Please tell what to do next to acheive that.

here is the code snipet -

```<code>linearLayoutManager = new LinearLayoutManager(mContext,   LinearLayoutManager.HORIZONTAL, false);
this.recyclerView.setLayoutManager(linearLayoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
adapterCarousel = new AdapterCarousel(mContext, glideRequestManager);
adapterCarousel.setViewType(RECYCLER_VIEW_TYPE_NORMAL);
adapterCarousel.setCarousel(carousel);
this.recyclerView.setAdapter(adapterCarousel);
snapHelper.attachToRecyclerView(recyclerView);
linearLayoutManager.scrollToPosition(Integer.MAX_VALUE / 2);
</code>```

答: for me using recyclerView.smoothScrollToPosition(x); instead of linearLayoutManager.scrollToPosition(x); did the trick

Body:
I am using an infinite scroll for recyclerview with X items which repeats.
Also i want am using PagerSnapHelper() to snap the scroll like viewpager.

So initially when the list is loaded the display is like -

As soon as i start scrolling on either side left or right the PageSnapHelper() come in work an snap it like viewpager with center alignment like this -

I want to show recyclerview as like 2nd image when initially loaded. Please tell what to do next to acheive that.

here is the code snipet -

linearLayoutManager = new LinearLayoutManager(mContext,   LinearLayoutManager.HORIZONTAL, false);
this.recyclerView.setLayoutManager(linearLayoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
adapterCarousel = new AdapterCarousel(mContext, glideRequestManager);
adapterCarousel.setViewType(RECYCLER_VIEW_TYPE_NORMAL);
adapterCarousel.setCarousel(carousel);
this.recyclerView.setAdapter(adapterCarousel);
snapHelper.attachToRecyclerView(recyclerView);
linearLayoutManager.scrollToPosition(Integer.MAX_VALUE / 2);


问:
Matplotlib Scatter plot change color based on value on list
I'm quite new to matplotlib and i would like to know how we can change color of points on a scatter plot based on the value in a list.

In fact, I have a 2-D array that I want to plot and a list with the same number of rows containing, for each point, the color we want to use.

```<code>#Example
data = np.array([4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582])
colors = ['red','red','red','blue','red','blue']
ax1.plot(data[:,0],data[:,1],'o',picker=True)
</code>```

How to set the color parameter to fit my list of colors ?

答:
Using a line plot plt.plot()

plt.plot() does only allow for a single color. So you may simply loop over the data and colors and plot each point individually.

```<code>import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
data = np.array([[4.29488806,-5.34487081],
                [3.63116248,-2.48616998],
                [-0.56023222,-5.89586997],
                [-0.51538502,-2.62569576],
                [-4.08561754,-4.2870525 ],
                [-0.80869722,10.12529582]])
colors = ['red','red','red','blue','red','blue']
for xy, color in zip(data, colors):
    ax.plot(xy[0],xy[1],'o',color=color, picker=True)

plt.show()
</code>```

Using scatter plot plt.scatter()

In order to produce a scatter plot, use scatter. This has an argument c, which allows numerous ways of setting the colors of the scatter points.

(a) One easy way is to supply a list of colors.

```<code>colors = ['red','red','red','blue','red','blue']
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", picker=True)
</code>```

(b) Another option is to supply a list of data and map the data to color using a colormap

```<code>colors = [0,0,0,1,0,1] #red is 0, blue is 1
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", cmap="bwr_r")
</code>```

Body:
I'm quite new to matplotlib and i would like to know how we can change color of points on a scatter plot based on the value in a list.

In fact, I have a 2-D array that I want to plot and a list with the same number of rows containing, for each point, the color we want to use.

#Example
data = np.array([4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582])
colors = ['red','red','red','blue','red','blue']
ax1.plot(data[:,0],data[:,1],'o',picker=True)

How to set the color parameter to fit my list of colors ?

Body:
Using a line plot plt.plot()

plt.plot() does only allow for a single color. So you may simply loop over the data and colors and plot each point individually.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
data = np.array([[4.29488806,-5.34487081],
                [3.63116248,-2.48616998],
                [-0.56023222,-5.89586997],
                [-0.51538502,-2.62569576],
                [-4.08561754,-4.2870525 ],
                [-0.80869722,10.12529582]])
colors = ['red','red','red','blue','red','blue']
for xy, color in zip(data, colors):
    ax.plot(xy[0],xy[1],'o',color=color, picker=True)

plt.show()

Using scatter plot plt.scatter()

In order to produce a scatter plot, use scatter. This has an argument c, which allows numerous ways of setting the colors of the scatter points.

(a) One easy way is to supply a list of colors.

colors = ['red','red','red','blue','red','blue']
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", picker=True)

(b) Another option is to supply a list of data and map the data to color using a colormap

colors = [0,0,0,1,0,1] #red is 0, blue is 1
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", cmap="bwr_r")

ContentLicense: CC BY-SA 4.0


问:
batch script for ip:port test
I have hundreds of IPs in excel file like this

```<code>System name:    Server name:    Server IP   Target Port:    Environment:
AddressWash  - Crontab jobs/Scripts hostname.com     123.456.789    22  PROD
</code>```

I want to take from this excel only port and IP with enviroment like and test it. Result should show me if I can reach the IP or not. Result should be in one txt file somehow formated.

Is that even possible? Thank you.

答:
First use this script (save it like toCSV.bat for example).It will save an excel file as csv (though the arguments needs to be full paths):

```<code>@if (@X)==(@Y) @end /* JScript comment
    @echo off

    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

var ARGS = WScript.Arguments;

var xlCSV = 6;

var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;

var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);

objExcel.Quit();
</code>```

Then check this. And here's the final script (you can alter the result and redirect it to a file).Probably you'll have to change the name of the excel book and the sheet:

```<code>@echo off
setlocal enableDelayedExpansion
call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csvIP.csv"

for /f "usebackq skip=1 tokens=3,4 delims=,"  %%a in ("csvIP.csv") do (
    for /f %%# in ('powershell "$t = New-Object Net.Sockets.TcpClient;try{$t.Connect("""%%~a""", %%~b)}catch{};$t.Connected"') do set "open=%%#"
    echo %%a %%b !open!
)
</code>```

Title: batch script for ip:port test

Body:
I have hundreds of IPs in excel file like this

System name:    Server name:    Server IP   Target Port:    Environment:
AddressWash  - Crontab jobs/Scripts hostname.com     123.456.789    22  PROD

I want to take from this excel only port and IP with enviroment like and test it. Result should show me if I can reach the IP or not. Result should be in one txt file somehow formated.

Is that even possible? Thank you.

Body:
First use this script (save it like toCSV.bat for example).It will save an excel file as csv (though the arguments needs to be full paths):

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */

var ARGS = WScript.Arguments;

var xlCSV = 6;

var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;

var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);

objExcel.Quit();

Then check this. And here's the final script (you can alter the result and redirect it to a file).Probably you'll have to change the name of the excel book and the sheet:

@echo off
setlocal enableDelayedExpansion
call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csvIP.csv"

for /f "usebackq skip=1 tokens=3,4 delims=,"  %%a in ("csvIP.csv") do (
    for /f %%# in ('powershell "$t = New-Object Net.Sockets.TcpClient;try{$t.Connect("""%%~a""", %%~b)}catch{};$t.Connected"') do set "open=%%#"
    echo %%a %%b !open!
)


答:
It should be like below

```<code>SELECT
(select count(distinct emploc) as test from location)/(select count(emploc) from location)
</code>```

Though you cam make it in a single query like

```<code>select count(distinct emploc) / count(emploc) from location
</code>```

Body:
I am trying to apply divide operator in this statement, but it throws an error

Incorrect syntax near '/'

I am using SQL Server 2012

(select count(distinct emploc) as test from location) /
(select count(emploc) from location)

Body:
It should be like below

SELECT
(select count(distinct emploc) as test from location)/(select count(emploc) from location)

Though you cam make it in a single query like

select count(distinct emploc) / count(emploc) from location


问:
Android FCM sending message to the user
I use FCM to send message to client (android), but I will have many client android and I want to send message to only one device not to everyone. How can I do this? Now when I send a message I send to everyone</p>

答: If you have "FCM registration token" of all user you can send message to Single Device or user using that user FCM registration token </p>

Title: Android FCM sending message to the user


问:
Cufon Loading But Not Displaying
Test case:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="/cufon.js"></script>
<script type="text/javascript" src="/font.font.js"></script>
</head>
<body>
<h1>Text</h1>
<script type="text/javascript">
    Cufon.replace('h1');
</script>
</body>
</html>
</code>```

where "cufon.js" is the latest version (same result with minimized version from the main site and non-minimized version from GitHub), and "font.font.js" is a generated font from cufon's website subset to Latin.

There are no HTTP, HTML, CSS, or JS errors reported by the browser, and yet no VML is generated in IE 8, FF 3.6, or Safari 5. Generated output does have  and Cufon inline styles, but that's it.

I've also tried, to no avail:

Switching where the scripts appear (before  and before )

Calling jQuery before Cufon

Manually declaring the font-family specified in font.font.js using inline CSS

Changing the DOCTYPE from HTML5 to  XHTML 1.1 or HTML 4.01 Strict

答: I hadn't listed localhost as an authorized domain. Silly me.</p>

ContentLicense: CC BY-SA 2.5

Title: Cufon Loading But Not Displaying

Body:
Test case:

<!DOCTYPE html>

<meta charset="UTF-8" />

Text

where "cufon.js" is the latest version (same result with minimized version from the main site and non-minimized version from GitHub), and "font.font.js" is a generated font from cufon's website subset to Latin.

There are no HTTP, HTML, CSS, or JS errors reported by the browser, and yet no VML is generated in IE 8, FF 3.6, or Safari 5. Generated output does have  and Cufon inline styles, but that's it.

I've also tried, to no avail:

Switching where the scripts appear (before  and before )

Calling jQuery before Cufon

Manually declaring the font-family specified in font.font.js using inline CSS

Changing the DOCTYPE from HTML5 to  XHTML 1.1 or HTML 4.01 Strict


问:
how can I access List type of data in django
client side, I sent a JSON data including list type data like this.

```<code> $.ajax({
     url: '/man/manual',
     type: 'POST',
     data: {'id':'','title':'ttt','description':'desc','steps':[{'title':'1'},{'title':'2'}]},
     dataType : 'JSON',
     success : function(data) {
         console.log(data);
     }
 });
</code>```

I tried to access these data.

```<code>title = request.POST['title']
description = request.POST['description']
steps = request.POST['steps']

for step in steps:
    print(step.title)
</code>```

but I got an error.

```<code>Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response

132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in view

71. return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in post
77. self.createManual(request)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in createManual
27. steps = request.POST['steps']
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/datastructures.py" in __getitem__
322. raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /man/manual
Exception Value: "'steps'"
Request information:
GET: No GET data

POST:
description = 'desc'
steps[1][title] = '2'
steps[0][title] = '1'
title = 'ttt'
id = ''
</code>```

How can I change my to code for correct data from client side.

答:
if you want to get the list with the requested key, use getlist method.

```<code>steps = request.POST.getlist('steps')
</code>```

doc is here

Body:
client side, I sent a JSON data including list type data like this.

 $.ajax({
     url: '/man/manual',
     type: 'POST',
     data: {'id':'','title':'ttt','description':'desc','steps':[{'title':'1'},{'title':'2'}]},
     dataType : 'JSON',
     success : function(data) {
         console.log(data);
     }
 });

I tried to access these data.

title = request.POST['title']
description = request.POST['description']
steps = request.POST['steps']

for step in steps:
    print(step.title)

but I got an error.

Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response

132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in view

71. return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in post
77. self.createManual(request)
File "/Users/sangwonlee/Makewith/trunk/MW_Service/mw_manual/views.py" in createManual
27. steps = request.POST['steps']
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/utils/datastructures.py" in __getitem__
322. raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /man/manual
Exception Value: "'steps'"
Request information:
GET: No GET data

POST:
description = 'desc'
steps[1][title] = '2'
steps[0][title] = '1'
title = 'ttt'
id = ''

How can I change my to code for correct data from client side.

Body:
if you want to get the list with the requested key, use getlist method.

steps = request.POST.getlist('steps')

doc is here


问:
Laravel Ajax cannot update database when click on a link
I have an audio file on public folder like this-

```<code>@foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach
</code>```

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

```<code>$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });
</code>```

My Route:

```<code>Route::post('/update_download_count', 'PagesController@updateDownloadCount');
</code>```

Controller:

```<code>public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}
</code>```

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

答:
Please declare object for your song modal.</p>

```<code>public function updateDownloadCount() {
     $song = Song::findOrFail($_POST['song_id']);
     $song->download += 1;
     $song->save();
}
</code>```

Body:
I have an audio file on public folder like this-

@foreach ($songs as $song)
     song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           Download
        </button>

 @endforeach

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });

My Route:

Route::post('/update_download_count', 'PagesController@updateDownloadCount');

Controller:

public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

Body:
Please declare object for your song modal.

public function updateDownloadCount() {
     $song = Song::findOrFail($_POST['song_id']);
     $song->download += 1;
     $song->save();
}


问:
Angular 2: Add elements to dom programmatically with viewencaptulation
I am working on a context menu where I need to get the size of the menu and every sub menu before rendering. The way I have done this in the past is to append a element structure to the dom, compute bbox, line height, etc. And then remove it, so it will never be visible for the user.

From this operation I get everything I need to check if the menu goes outside screen, etc. Then maybe make changes to it.

In angular 2 I am able to do this if ViewEncaptulation is set to None. But I get an error in my current build setup if I use it, so I am stuck to the default value.

Does anyone know how I can make an element programmatically and make it get the same classes from inside the ViewEncaptulation?

答:
After some thinking I solved it like this.

```<code>private elementRef: ElementRef

getEncapsulationId(): string {
    if (!this.elementRef) {
        return '';
    }

    var attr = this.elementRef.nativeElement.attributes;
    for(let i = 0; i < attr.length; i++){
        let s = attr[i].name;
        if(s.includes('_nghost')){
            return '_ngcontent' + s.substring(7);
        }
    }

    return '';
}
</code>```

When creating the element I add the encapsulation id as an attribute.

```<code>var element = document.createElement('div');
element.setAttribute(this.getEncapsulationId, '');
element.classList.add('some-class');
</code>```

Let me know if someone has a better solution for this problem.

Body:
After some thinking I solved it like this.

private elementRef: ElementRef

getEncapsulationId(): string {
    if (!this.elementRef) {
        return '';
    }

    var attr = this.elementRef.nativeElement.attributes;
    for(let i = 0; i < attr.length; i++){
        let s = attr[i].name;
        if(s.includes('_nghost')){
            return '_ngcontent' + s.substring(7);
        }
    }

    return '';
}

When creating the element I add the encapsulation id as an attribute.

var element = document.createElement('div');
element.setAttribute(this.getEncapsulationId, '');
element.classList.add('some-class');

Let me know if someone has a better solution for this problem.


问:
Android Form as an Activity
I have an application with multiple activities. In the main class I open a database and create a list of the content like so:

```<code>public class MyApplication extends Activity
{
    private List<PhoneNumber> numberList;

    public void onCreate(Bundle savedInstanceState)
    {
        ...
        numberList = new ArrayList<PhoneNumber>();
        ...
        loadDatabase()
        ...
    }

    private void loadDatabase()
    {
        // File IO and parsing stuff
        addNumber(thisNumber);   // executes for each entry
    }

    public void addNumber(PhoneNumber thisNumber)
    {
        numberList.add(thisNumber);
    }
}
</code>```

This works fine and I have a ListView in the main activity that is populated with this data. Now, moving on to the next step. I am trying to launch a form as a new activity that will add an entry to this list. The activity launches fine, and I was able to build a form easily. The problem is accessing the list to add to it.

```<code>public class AddNumber extends Activity
{
    ...
    // This function is called from the done button
    // <Button android:text="Done" android:onClick="formDone"/>
    public void formDone(View v)
    {
        // findViewByIds here to get data from form.
        // This is done correctly and I can see my data in memory

        MyApplication access = new MyApplication();
        PhoneNumber newNumber = new PhoneNumber();

        // Fill newNumber object with data from form. Done correctly. Verified

        access.addNumber(newNumber);
    }
</code>```

The last line of formDone() executes correctly. Through debugging I can step through to the Application class and it executes addNumber(). Before executing numberList.add(thisNumber); I can look at the contents of memory for the thisNumber object it is trying to add to the list and that data is correct. Attempting to execute that line though crashes the application in standard Android format. (Loads View.class with 'Source not found' followed by ZygoteInit$MethodBlahBlah).

So I'm a little confused because it looks like the data being fed to addNumber() is correct, and the function works perfectly fine when the application first launches by building the list from the data in the database. Fundamentally, am I thinking about this correct? Should a form like this be it's own activity or is there a better way to do it? If it can be it's own activity, what am I doing wrong?

Thanks,

Nate

答:
As Falmarri pointed out, it is not valid to instantiate an Application or Activity class directly.

Instead, you have two primary options for communicating between Activities.

Pass information via the Intent.  Add the phone number list as an extra to the intent that starts AddNumber, and return the altered list when you finish.

Store information in a custom Application.  Extend the Application class, (select it as your Application class in the manifest).  Store your number list there.  You can access the Application class from any Activity via getApplication().  Just cast it to your Application class, and access the method.

Title: Android Form as an Activity

Body:
I have an application with multiple activities. In the main class I open a database and create a list of the content like so:

public class MyApplication extends Activity
{
    private List<PhoneNumber> numberList;

    public void onCreate(Bundle savedInstanceState)
    {
        ...
        numberList = new ArrayList<PhoneNumber>();
        ...
        loadDatabase()
        ...
    }

    private void loadDatabase()
    {
        // File IO and parsing stuff
        addNumber(thisNumber);   // executes for each entry
    }

    public void addNumber(PhoneNumber thisNumber)
    {
        numberList.add(thisNumber);
    }
}

This works fine and I have a ListView in the main activity that is populated with this data. Now, moving on to the next step. I am trying to launch a form as a new activity that will add an entry to this list. The activity launches fine, and I was able to build a form easily. The problem is accessing the list to add to it.

public class AddNumber extends Activity
{
    ...
    // This function is called from the done button
    // <Button android:text="Done" android:onClick="formDone"/>
    public void formDone(View v)
    {
        // findViewByIds here to get data from form.
        // This is done correctly and I can see my data in memory

        MyApplication access = new MyApplication();
        PhoneNumber newNumber = new PhoneNumber();

        // Fill newNumber object with data from form. Done correctly. Verified

        access.addNumber(newNumber);
    }

The last line of formDone() executes correctly. Through debugging I can step through to the Application class and it executes addNumber(). Before executing numberList.add(thisNumber); I can look at the contents of memory for the thisNumber object it is trying to add to the list and that data is correct. Attempting to execute that line though crashes the application in standard Android format. (Loads View.class with 'Source not found' followed by ZygoteInit$MethodBlahBlah).

So I'm a little confused because it looks like the data being fed to addNumber() is correct, and the function works perfectly fine when the application first launches by building the list from the data in the database. Fundamentally, am I thinking about this correct? Should a form like this be it's own activity or is there a better way to do it? If it can be it's own activity, what am I doing wrong?

Thanks,

Nate


问:
Toggle visibility of sibling element of $(this) element | No unique ID [jQuery]
I need div.edit-button to toggle its sibling div.additionalFieldForm.

Note that there's more than one div.edit-button and div.additionalFieldForm on the page, but I would like to target the div.additionalFieldForm that is in the same "family" as the div.edit-button that was clicked.

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm">Content</div>
    <div class="edit-button">Edit</div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

I've tried other selectors but I couldn't specifically target just the div.additionalFieldForm sibling of the edit button being clicked.

EDIT: I realize that there must be an underlying problem because the selector works on jsFiddle (http://jsfiddle.net/wf7jjoq7/), but not on my site, without any console errors.

答:
Try using siblings()

```<code>$(".edit-button").click(function () {
  $(this).siblings(".additionalFieldForm").toggle();
});
</code>```

Body:
I need div.edit-button to toggle its sibling div.additionalFieldForm.

Note that there's more than one div.edit-button and div.additionalFieldForm on the page, but I would like to target the div.additionalFieldForm that is in the same "family" as the div.edit-button that was clicked.

$(".edit-button").click(function () {

  // PROBLEMATIC SELECTOR BELOW:
  $(this).closest("div").prev().toggle();

});

    Additional Field

Content

Edit

Remove

    Additional Field

Content

Edit

Remove

I've tried other selectors but I couldn't specifically target just the div.additionalFieldForm sibling of the edit button being clicked.

EDIT: I realize that there must be an underlying problem because the selector works on jsFiddle (http://jsfiddle.net/wf7jjoq7/), but not on my site, without any console errors.

Body:
Try using siblings()

$(".edit-button").click(function () {
  $(this).siblings(".additionalFieldForm").toggle();
});


答:
Seems like you can use JSON.stringify

$("#ele").attr('data-example', JSON.stringify(new Array('1', '2')));

console.log($("#ele").attr('data-example'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='ele' data-example="nothing"></div></code>```

Title: High level data structures in html data attribute

Body:
I am happy that the html5 data attribute exists.

I can write a simple string into html attributes and access them via jquery.

But .... wouldn't it be nice to have more than a simple string?

Is there no way to encode JSON into these data attributes.

In my current use case I need to store a list of strings in a html5 data attribute.

Body:
Seems like you can use JSON.stringify

$("#ele").attr('data-example', JSON.stringify(new Array('1', '2')));

console.log($("#ele").attr('data-example'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='ele' data-example="nothing"></div>