问:
converting string to numeric matrix in r
i am a beginner in R. I have a data set called data_mat. it has only binary variables i.e. all variables have 0 or 1 as values. It look like this:

```<code>      Elderflower high low medium
 [1,]           0    1   0      0
 [2,]           0    1   0      0
 [3,]           0    1   0      0
 [4,]           0    1   0      0
</code>```

it is a numeric matrix. on adding 3 more columns (which are again binary in nature) into it using following code, it no more remains numeric:

```<code>data_mat<-cbind(data_mat,datam[,c(5:6,9)])
</code>```

post executing above code, data now looks like this:

```<code>      Elderflower high low medium Sugar Chewy Content
 [1,] "0"         "1"  "0" "0"    "1"   "1"   "1"
 [2,] "0"         "1"  "0" "0"    "0"   "0"   "1"
 [3,] "0"         "1"  "0" "0"    "1"   "1"   "1"
 [4,] "0"         "1"  "0" "0"    "0"   "0"   "1"
</code>```

in order to convert this matrix into numeric i ran following code:

```<code>data11<-matrix(as.numeric(unlist(data_mat,use.names =
TRUE)),nrow=nrow(data_mat))
</code>```

with this my data remains a numeric matrix but column names are gone. it now looks like this:

```<code>      [,59] [,60]
 [1,]     1     1
 [2,]     0     1
 [3,]     1     1
 [4,]     0     1
</code>```

Kindly suggest how do i tackle this problem? Motive is to get numeric matrix with column names intact post adding new columns to existing numeric matrix.

答:
Read your data with defined colClasses

```<code>data_mat <- read.table(path.to.data, header = TRUE, colClasses = "numeric")
</code>```

This assures that your data is numeric and you can use cbind to add more columns the way you did. Of couse datam needs to be numeric, too. As a side effect, defining colClasses also accelerates the reading process.

Body:
i am a beginner in R. I have a data set called data_mat. it has only binary variables i.e. all variables have 0 or 1 as values. It look like this:

      Elderflower high low medium
 [1,]           0    1   0      0
 [2,]           0    1   0      0
 [3,]           0    1   0      0
 [4,]           0    1   0      0

it is a numeric matrix. on adding 3 more columns (which are again binary in nature) into it using following code, it no more remains numeric:

data_mat<-cbind(data_mat,datam[,c(5:6,9)])

post executing above code, data now looks like this:

      Elderflower high low medium Sugar Chewy Content
 [1,] "0"         "1"  "0" "0"    "1"   "1"   "1"
 [2,] "0"         "1"  "0" "0"    "0"   "0"   "1"
 [3,] "0"         "1"  "0" "0"    "1"   "1"   "1"
 [4,] "0"         "1"  "0" "0"    "0"   "0"   "1"

in order to convert this matrix into numeric i ran following code:

data11<-matrix(as.numeric(unlist(data_mat,use.names =
TRUE)),nrow=nrow(data_mat))

with this my data remains a numeric matrix but column names are gone. it now looks like this:

      [,59] [,60]
 [1,]     1     1
 [2,]     0     1
 [3,]     1     1
 [4,]     0     1

Kindly suggest how do i tackle this problem? Motive is to get numeric matrix with column names intact post adding new columns to existing numeric matrix.

Body:
Read your data with defined colClasses

data_mat <- read.table(path.to.data, header = TRUE, colClasses = "numeric")

This assures that your data is numeric and you can use cbind to add more columns the way you did. Of couse datam needs to be numeric, too. As a side effect, defining colClasses also accelerates the reading process.


来源: stackexchange

问:
Solr 6.1 How to use PatternTokenizerFactory tokenizer get Number
I need to analyze the text and get the number

1.e.g.  "acbt-10.2" => 10.2

2.e.g.  "acbt - 10.2" => 10.2

3.e.g.  "acbt" => 0

how to setting the pattern and group on PatternTokenizerFactory tokenizer for this feature?

答:
Add this fieldType to schema file. restart solr or reload core
and check on analyse page</p>

```<code><fieldType name="text_ptnreplace" class="solr.TextField" positionIncrementGap="100">
       <analyzer>
         <tokenizer class="solr.KeywordTokenizerFactory"/>
         <filter class="solr.PatternReplaceFilterFactory" pattern="[^0-9.]+" replacement="" replace="all"/>
       </analyzer>
     </fieldType>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Add this fieldType to schema file. restart solr or reload core
and check on analyse page

<fieldType name="text_ptnreplace" class="solr.TextField" positionIncrementGap="100">
       <analyzer>
         <tokenizer class="solr.KeywordTokenizerFactory"/>
         <filter class="solr.PatternReplaceFilterFactory" pattern="[^0-9.]+" replacement="" replace="all"/>
       </analyzer>
     </fieldType>


问:
Step definition is not getting recognized in test runner
``In  My Java cucumber setup -test runner Step definitions are not running.
Please find attached the screenshot of runner class,feature file and step definition locations.I am just launching the application
<img src="https://i.stack.imgur.com/LCTXy.png" alt="Stepdefinitions"> </p>

```<code>  package com;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;

public class StepDefinition {
    WebDriver driver;
    @Before

    public void setUp(){
         driver=new FirefoxDriver();

    }

    @After
    public void tearDown(){
        driver.quit();
    }

    @Given("^Launch the application$")
    public void loadUrl() throws Throwable {
        driver.get("https://www.google.com");

        throw new PendingException();
    }

}
</code>```

答:
Segregate all your test runner classes in one package(com.tests) and all the step definition classes in another package(com.stepDefs). Then, glue the stepDefs package to each test runner.

I am using cucumber-junit 1.2.4 , that @Cucumber.Options syntax is @CucumberOptions for me.

template Syntax :

```<code>@CucumberOptions(features = "src/test/resources/features/",
            tags = {"@soWeb"},
            plugin = {"pretty","html:target/cucumber-html-report",
                    "json:target/cucumber-json-report.json"
                        },
            glue = "com.ba.StepDefs")

public class AltoroMutual_TestRunner {

}
</code>```

Body:
``In  My Java cucumber setup -test runner Step definitions are not running.
Please find attached the screenshot of runner class,feature file and step definition locations.I am just launching the application

  package com;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.PendingException;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;

public class StepDefinition {
    WebDriver driver;
    @Before

    public void setUp(){
         driver=new FirefoxDriver();

    }

    @After
    public void tearDown(){
        driver.quit();
    }

    @Given("^Launch the application$")
    public void loadUrl() throws Throwable {
        driver.get("https://www.google.com");

        throw new PendingException();
    }

}

Body:
Segregate all your test runner classes in one package(com.tests) and all the step definition classes in another package(com.stepDefs). Then, glue the stepDefs package to each test runner.

I am using cucumber-junit 1.2.4 , that @Cucumber.Options syntax is @CucumberOptions for me.

template Syntax :

@CucumberOptions(features = "src/test/resources/features/",
            tags = {"@soWeb"},
            plugin = {"pretty","html:target/cucumber-html-report",
                    "json:target/cucumber-json-report.json"
                        },
            glue = "com.ba.StepDefs")

public class AltoroMutual_TestRunner {

}


问:
How to make unknown width inline-block element stay in the center position after hover
Here is what I have
A navigation menu with unknown width which I try to center it.
The problem is on hover state the width of this navigation expands so the rule doesn't apply anymore.  (because the width goes above its container width)

  #centerContent {
    width: 300px;
    margin: auto auto;
    padding: 110px 30px 30px 30px;
    background-color: #fff;
    text-align: center;
    outline: 1px solid red;
    }
        #mainNav {
        display: inline-block;
     height: 42px;
     background-color: #f5f5f5;
        white-space: nowrap;
        outline: 1px solid blue;
    }

    #mainNav a {
     transition: all 0.15s ease-in-out;
    }

    #mainNav a > * {
     transition: all 0.15s ease-in-out;
    }

    #mainNav > a {
     display: inline-block;
     height: 100%;
     position: relative;
     font: 13px/42px "IranYekanWebLight";
     font-weight: 700;
     color: #575757;
     overflow: hidden;
    }

    #mainNav > a:hover {
     background-color: #ddd;
    }

    #mainNav > a:hover span {
     color: #fff;
     font-size: 17px;
     padding-right: 75px;
    }

    #mainNav > a:hover svg {
     left: 40%;
     fill: #fff;
     animation: 0.3s 1 mainNavAnim;
     animation-timing-function: ease-out;
    }

    #mainNav span {
     padding: 0 28px;
     position: relative;
     z-index: 1;
    }

    #mainNav svg {
     height: 90px;
     position: absolute;
     bottom: -90%;
     left: 10%;
     fill: #e3e3e3;
     z-index: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>          <div id="centerContent">
            <nav id="mainNav">

        <span>aaa</span>
                    <svg></svg>
                <a
                    class="aqua" href="#">
        <span>bbb</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>ccc</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>ddd</span>
                    <svg></svg>
                </a>
           </nav>
        </div></code>```

As you can see, the #mainNav width is undefined which makes its width as long as its children expand.

I want when I hover on each A tag, the mainNav stay in the center position to its container

答:
You can use a wrapper block with this styles:

#centerContent {
    width: 700px;
    background-color: #fff;
    padding-top: 30px;
    padding-bottom: 30px;
    text-align: center;
    }
        #mainNav {
        display: inline-block;
     height: 42px;
     background-color: #f5f5f5;
        white-space: nowrap;
    }

    #mainNav a {
     transition: all 0.15s ease-in-out;
    }

    #mainNav a > * {
     transition: all 0.15s ease-in-out;
    }

    #mainNav > a {
     display: inline-block;
     height: 100%;
     position: relative;
     font: 13px/42px "IranYekanWebLight";
     font-weight: 700;
     color: #575757;
     overflow: hidden;
    }

    #mainNav > a:hover {
     background-color: #ddd;
    }

    #mainNav > a:hover span {
     color: #fff;
     font-size: 17px;
     padding-right: 75px;
    }

    #mainNav > a:hover svg {
     left: 40%;
     fill: #fff;
     animation: 0.3s 1 mainNavAnim;
     animation-timing-function: ease-out;
    }

    #mainNav span {
     padding: 0 28px;
     position: relative;
     z-index: 1;
    }

    #mainNav svg {
     height: 90px;
     position: absolute;
     bottom: -90%;
     left: 10%;
     fill: #e3e3e3;
     z-index: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="centerContent">
            <nav id="mainNav">

        <span>aaa</span>
                    <svg></svg>
                <a
                    class="aqua" href="#">
        <span>bbb</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>ccc</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>ddd</span>
                    <svg></svg>
                </a>
           </nav>
        </div></code>```

Body:
Here is what I have
A navigation menu with unknown width which I try to center it.
The problem is on hover state the width of this navigation expands so the rule doesn't apply anymore.  (because the width goes above its container width)

  #centerContent {
    width: 300px;
    margin: auto auto;
    padding: 110px 30px 30px 30px;
    background-color: #fff;
    text-align: center;
    outline: 1px solid red;
    }
        #mainNav {
        display: inline-block;
     height: 42px;
     background-color: #f5f5f5;
        white-space: nowrap;
        outline: 1px solid blue;
    }

    #mainNav a {
     transition: all 0.15s ease-in-out;
    }

    #mainNav a > * {
     transition: all 0.15s ease-in-out;
    }

    #mainNav > a {
     display: inline-block;
     height: 100%;
     position: relative;
     font: 13px/42px "IranYekanWebLight";
     font-weight: 700;
     color: #575757;
     overflow: hidden;
    }

    #mainNav > a:hover {
     background-color: #ddd;
    }

    #mainNav > a:hover span {
     color: #fff;
     font-size: 17px;
     padding-right: 75px;
    }

    #mainNav > a:hover svg {
     left: 40%;
     fill: #fff;
     animation: 0.3s 1 mainNavAnim;
     animation-timing-function: ease-out;
    }

    #mainNav span {
     padding: 0 28px;
     position: relative;
     z-index: 1;
    }

    #mainNav svg {
     height: 90px;
     position: absolute;
     bottom: -90%;
     left: 10%;
     fill: #e3e3e3;
     z-index: 0;
    }

        aaa
                    <svg></svg>

        bbb
                    <svg></svg>

        ccc
                    <svg></svg>

        ddd
                    <svg></svg>

As you can see, the #mainNav width is undefined which makes its width as long as its children expand.

I want when I hover on each A tag, the mainNav stay in the center position to its container

Body:
You can use a wrapper block with this styles:

#centerContent {
    width: 700px;
    background-color: #fff;
    padding-top: 30px;
    padding-bottom: 30px;
    text-align: center;
    }
        #mainNav {
        display: inline-block;
     height: 42px;
     background-color: #f5f5f5;
        white-space: nowrap;
    }

    #mainNav a {
     transition: all 0.15s ease-in-out;
    }

    #mainNav a > * {
     transition: all 0.15s ease-in-out;
    }

    #mainNav > a {
     display: inline-block;
     height: 100%;
     position: relative;
     font: 13px/42px "IranYekanWebLight";
     font-weight: 700;
     color: #575757;
     overflow: hidden;
    }

    #mainNav > a:hover {
     background-color: #ddd;
    }

    #mainNav > a:hover span {
     color: #fff;
     font-size: 17px;
     padding-right: 75px;
    }

    #mainNav > a:hover svg {
     left: 40%;
     fill: #fff;
     animation: 0.3s 1 mainNavAnim;
     animation-timing-function: ease-out;
    }

    #mainNav span {
     padding: 0 28px;
     position: relative;
     z-index: 1;
    }

    #mainNav svg {
     height: 90px;
     position: absolute;
     bottom: -90%;
     left: 10%;
     fill: #e3e3e3;
     z-index: 0;
    }

 <div id="centerContent">
            <nav id="mainNav">
       <a class="aqua" href="#">
        <span>aaa</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>bbb</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>ccc</span>
                    <svg></svg>
                </a><a
                    class="aqua" href="#">
        <span>ddd</span>
                    <svg></svg>
                </a>
           </nav>
        </div>


问:
Parsing XML using Python ElementTree
I have an XML document in the following format

```<code><root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
</code>```

How can I extract the text from 'D' inside H tag and also all the text inside the F tags.

答:
You did not specifiy what exactly you whant to use so i recommend lxml for python. For getting the values you whant you have more possibiltys:

With a loop:

```<code>from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
text = []
for element in root:
   text.append(element.get('D',None))
     for child in element:
       for grandchild in child:
         text.append(grandchild.text)
print(text)
</code>```

Output:
['14/11/2017', 'The quick', 'brown', 'fox', '14/11/2017', 'The lazy', 'fox']

With xpath:

```<code>from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
D = root.xpath("./H")
F = root.xpath(".//F")

for each in D:
  print(each.get('D',None))

for each in F:
  print(each.text)
</code>```

Output:
14/11/2017
14/11/2017
The quick
brown
fox
The lazy
fox

Both have there own advantages but give you a good starting point.
I recommend the xpath since it gives you more freedom when values are
missing.

Title: Parsing XML using Python ElementTree

Body:
I have an XML document in the following format

<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>

How can I extract the text from 'D' inside H tag and also all the text inside the F tags.

Body:
You did not specifiy what exactly you whant to use so i recommend lxml for python. For getting the values you whant you have more possibiltys:

With a loop:

from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
text = []
for element in root:
   text.append(element.get('D',None))
     for child in element:
       for grandchild in child:
         text.append(grandchild.text)
print(text)

Output:
['14/11/2017', 'The quick', 'brown', 'fox', '14/11/2017', 'The lazy', 'fox']

With xpath:

from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
D = root.xpath("./H")
F = root.xpath(".//F")

for each in D:
  print(each.get('D',None))

for each in F:
  print(each.text)

Output:
14/11/2017
14/11/2017
The quick
brown
fox
The lazy
fox

Both have there own advantages but give you a good starting point.
I recommend the xpath since it gives you more freedom when values are
missing.


问:
Kibana doesn't show any results in "Discover" tab
I setup elasticsearch and Kibana for indexing our application (error) logs. The issue is that Kibana doesn't display any data in the "Discover" tab.

Current situation

Elasticsearch is up and running, responds to API

executing a query directly on Elasticsearch like http://elasticserver.com:9200/applogs/_search?q=* returns lots of results (see below on how a single found record looks like)

Kibana is up and running, even finds the applogs index exposed by Elasticsearch

Kibana also shows the correct properties and data type of the applogs documents

"Discover" tab doesn't show any results...even when setting the time period to a couple of years...

Any ideas??

Here's how Kibana sees the applogs index:

Elastic search query result object looks like this:

```<code>{
_index: "applogs",
_type: "1",
_id: "AUxv8uxX6xaLDVAP5Zud",
_score: 1,
_source: {
   appUid: "esb.Idman_v4.getPerson",
   level: "trace",
   message: "WS stopwatch is at 111ms.",
   detail: "",
   url: "",
   user: "bla bla bla",
   additionalInfo: "some more info",
   timestamp: "2015-03-31T15:08:49"
 }
},
</code>```

..and what I see in the discover tab:

答: I had probably the same issue - I see data in the dashboard but 0 results in discover. Going to Managerment > Index Pattern > Refresh filed list button (a button with refresh icon only) solved it for me.</p>

Body:
I setup elasticsearch and Kibana for indexing our application (error) logs. The issue is that Kibana doesn't display any data in the "Discover" tab.

Current situation

Elasticsearch is up and running, responds to API

executing a query directly on Elasticsearch like http://elasticserver.com:9200/applogs/_search?q=* returns lots of results (see below on how a single found record looks like)

Kibana is up and running, even finds the applogs index exposed by Elasticsearch

Kibana also shows the correct properties and data type of the applogs documents

"Discover" tab doesn't show any results...even when setting the time period to a couple of years...

Any ideas??

Here's how Kibana sees the applogs index:

Elastic search query result object looks like this:

{
_index: "applogs",
_type: "1",
_id: "AUxv8uxX6xaLDVAP5Zud",
_score: 1,
_source: {
   appUid: "esb.Idman_v4.getPerson",
   level: "trace",
   message: "WS stopwatch is at 111ms.",
   detail: "",
   url: "",
   user: "bla bla bla",
   additionalInfo: "some more info",
   timestamp: "2015-03-31T15:08:49"
 }
},

..and what I see in the discover tab:


问:
Remove a verb as a stopword
There are some words which are used sometimes as a verb and sometimes as other part of speech.

Example

A sentence with the meaning of the word as verb:

```<code>I blame myself for what happened
</code>```

And a sentence with the meaning of word as noun:

```<code>For what happened the blame is yours
</code>```

The word I want to detect is known to me, in the example above is "blame". I would like to detect and remove as stopwords only when it has meaning like a verb.

Is there any easy way to make it?

答:
In python it is done as:

```<code>from nltk import pos_tag
s1 = "I blame myself for what happened"
pos_tag(s1.split())
</code>```

It will give you words with there tags

Title: Remove a verb as a stopword

Body:
There are some words which are used sometimes as a verb and sometimes as other part of speech.

Example

A sentence with the meaning of the word as verb:

I blame myself for what happened

And a sentence with the meaning of word as noun:

For what happened the blame is yours

The word I want to detect is known to me, in the example above is "blame". I would like to detect and remove as stopwords only when it has meaning like a verb.

Is there any easy way to make it?

Body:
In python it is done as:

from nltk import pos_tag
s1 = "I blame myself for what happened"
pos_tag(s1.split())

It will give you words with there tags


问:
Where do I get Java default Library on windows?
I couldn't find HttpURLConnection in my java environment, and I wonder how to get that class.
How to get Java Basic Library on windows?
I've searched for that for 2 hours.

e.g:

```<code>import java.net.HttpURLConnection;
import java.net.URL;
</code>```

答:
well, you can find java default library on your system location as mentioned below
C:\Program Files\Java\jre1.8.0_151\lib(follow this path)</p>

Body:
I couldn't find HttpURLConnection in my java environment, and I wonder how to get that class.
How to get Java Basic Library on windows?
I've searched for that for 2 hours.

e.g:

import java.net.HttpURLConnection;
import java.net.URL;


问:
Method reference is ambiguous for Thread.sleep
I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.

```<code>package test;

public class Test
{
    public static void main(String[] args)
    {
        foo(Test::sleep, 1000L); //fine
        foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
        foo(Thread::sleep, 1000L); //error
    }

    public static void sleep(long millis) throws InterruptedException
    {
        Thread.sleep(millis);
    }

    public static <P, R> void foo(Foo<P, R> function, P param) {}

    public static <P> void foo(FooVoid<P> function, P param) {}

    @FunctionalInterface
    public interface Foo<P, R> {
        R call(P param1) throws Exception;
    }

    @FunctionalInterface
    public interface FooVoid<P> {
        void call(P param1) throws Exception;
    }
}
</code>```

I get those 2 errors:

```<code>Error:(9, 17) java: reference to foo is ambiguous
  both method <P,R>foo(test.Test.Foo<P,R>,P) in test.Test and method <P>foo(test.Test.FooVoid<P>,P) in test.Test match

Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)
</code>```

The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?

EDIT: Using javac version 1.8.0_111

答:
Personally I see this as some sort of recursion, somehow like this: we need to resolve the method in order to find the target type, but we need to know the target type in order to resolve the method. This has something to do with a special void compatibility rule, but I admit I do not entirely get it.

Things are even funner when you have something like this:

```<code>public static void cool(Predicate<String> predicate) {

}

public static void cool(Function<String, Integer> function) {

}
</code>```

And try to call it via:

```<code>cool(i -> "Test"); // this will fail compilation
</code>```

And btw if you make your lambda explicit, this will work:

```<code>foo((Long t) -> Thread.sleep(t), 1000L);
</code>```

Body:
I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.

package test;

public class Test
{
    public static void main(String[] args)
    {
        foo(Test::sleep, 1000L); //fine
        foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
        foo(Thread::sleep, 1000L); //error
    }

    public static void sleep(long millis) throws InterruptedException
    {
        Thread.sleep(millis);
    }

    public static
 void foo(Foo
 function, P param) {}

    public static
 void foo(FooVoid
 function, P param) {}

    @FunctionalInterface
    public interface Foo
 {
        R call(P param1) throws Exception;
    }

    @FunctionalInterface
    public interface FooVoid
 {
        void call(P param1) throws Exception;
    }
}

I get those 2 errors:

Error:(9, 17) java: reference to foo is ambiguous
  both method
foo(test.Test.Foo
,P) in test.Test and method
foo(test.Test.FooVoid
,P) in test.Test match

Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)

The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?

EDIT: Using javac version 1.8.0_111

Body:
Personally I see this as some sort of recursion, somehow like this: we need to resolve the method in order to find the target type, but we need to know the target type in order to resolve the method. This has something to do with a special void compatibility rule, but I admit I do not entirely get it.

Things are even funner when you have something like this:

public static void cool(Predicate<String> predicate) {

}

public static void cool(Function<String, Integer> function) {

}

And try to call it via:

cool(i -> "Test"); // this will fail compilation

And btw if you make your lambda explicit, this will work:

foo((Long t) -> Thread.sleep(t), 1000L);


问:
Calculate all the subsets of a list in python using java approach
I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem:

```<code>    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> list = new ArrayList<>();
     Arrays.sort(nums);
     backtrack(list, new ArrayList<>(), nums, 0);
     return list;
    }

   private void backtrack(List<List<Integer>> list , List<Integer> {
     tempList, int [] nums, int start){
     list.add(new ArrayList<>(tempList));
     for(int i = start; i < nums.length; i++){
      tempList.add(nums[i]);
     backtrack(list, tempList, nums, i + 1);
     tempList.remove(tempList.size() - 1);
   }
 }
</code>```

I'm trying to do the same thing but using python instead:

```<code>class Solution:
  def subsets(self, nums):
   lista = []
   self.backtrack(lista, [], sorted(nums), 0)
   return lista
 def backtrack(self, lista, tempList, nums, start):
   lista.append(tempList)
   for i in range(start, len(nums)):
     tempList.append(nums[i])
     self.backtrack(lista, tempList, nums, i+1)
     tempList.pop()
</code>```

I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!

答:
You need to make a copy of tempList. Otherwise, you're just appending multiple references to the same tempList object to lista. When backtrack finally returns, tempList is empty, so lista will just contain multiple references to that empty list.

Here's a more Pythoic way to write your code. This version doesn't need to make a copy because each recursive call creates a new templist rather than modifying the original templist object.

```<code>def subsets(nums):
    lista = []
    backtrack(lista, [], sorted(nums), 0)
    return lista

def backtrack(lista, templist, nums, start):
    lista.append(templist)
    for i in range(start, len(nums)):
        backtrack(lista, templist + nums[i:i+1], nums, i+1)

# Test

for t in subsets([1,2,3]):
    print(t)
</code>```

output

```<code>[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]
</code>```

Just for fun, here's the same algorithm in the form of a generator function. I've eliminated the sorting step, the caller can sort the input if they really want that.

```<code>def subsets(nums, templist=None, start=0):
    if templist is None:
        templist = []
    yield templist
    for i in range(start, len(nums)):
        yield from subsets(nums, templist + nums[i:i+1], i+1)

for t in subsets([1, 2, 3]):
    print(t)
</code>```

This code produces the same output as the earlier code.

Here's a non-recursive way to make subsets that's a little more compact. It uses a similar algorithm to the earlier code, but it produces the subsets in a slightly different order. It may be helpful to work through the algorithm by hand, on paper, to see how it works.

```<code>def subsets(seq):
    z = [[]]
    for x in seq:
        z += [y + [x] for y in z]
    return z

for t in subsets([1, 2, 3]):
    print(t)
</code>```

output

```<code>[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]
</code>```

And here's the almost-unreadable one-liner version of that algorithm. ;)

```<code>from functools import reduce

def subsets(seq):
    return reduce(lambda z, x: z + [y + [x] for y in z], seq, [[]])
</code>```

Lastly, here's a way to make subsets using binary numbers. This is handy if you want to get specific subsets without producing them all.

Given a set S of n items there are 2**n subsets. Each subset of S corresponds to a n-bit binary number: a 1 bit in the number means the corresponding item in S is in the subset.

```<code>def subsets(seq):
    for i in range(1<<len(seq)):
        a = []
        for u in seq:
            if not i:
                break
            if i & 1:
                a.append(u)
            i >>= 1
        yield a
</code>```

This generator yields subsets in the same order as the last 2 versions.

Body:
I'm working through some interview problems and one of the classic ones, which uses backtracking, is to calculate the powerset (all the subsets) of a list. I have the java solution for the problem:

    public List<List<Integer>> subsets(int[] nums) {
     List<List<Integer>> list = new ArrayList<>();
     Arrays.sort(nums);
     backtrack(list, new ArrayList<>(), nums, 0);
     return list;
    }

   private void backtrack(List<List<Integer>> list , List<Integer> {
     tempList, int [] nums, int start){
     list.add(new ArrayList<>(tempList));
     for(int i = start; i < nums.length; i++){
      tempList.add(nums[i]);
     backtrack(list, tempList, nums, i + 1);
     tempList.remove(tempList.size() - 1);
   }
 }

I'm trying to do the same thing but using python instead:

class Solution:
  def subsets(self, nums):
   lista = []
   self.backtrack(lista, [], sorted(nums), 0)
   return lista
 def backtrack(self, lista, tempList, nums, start):
   lista.append(tempList)
   for i in range(start, len(nums)):
     tempList.append(nums[i])
     self.backtrack(lista, tempList, nums, i+1)
     tempList.pop()

I printed the tempList and it seems to be working as expected. The problem I believe is that it lista.append(tempList) is not working as I expected. Is there some particularity in python that is yielding this different result? Thanks!

Body:
You need to make a copy of tempList. Otherwise, you're just appending multiple references to the same tempList object to lista. When backtrack finally returns, tempList is empty, so lista will just contain multiple references to that empty list.

Here's a more Pythoic way to write your code. This version doesn't need to make a copy because each recursive call creates a new templist rather than modifying the original templist object.

def subsets(nums):
    lista = []
    backtrack(lista, [], sorted(nums), 0)
    return lista

def backtrack(lista, templist, nums, start):
    lista.append(templist)
    for i in range(start, len(nums)):
        backtrack(lista, templist + nums[i:i+1], nums, i+1)

# Test

for t in subsets([1,2,3]):
    print(t)

output

[]
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

Just for fun, here's the same algorithm in the form of a generator function. I've eliminated the sorting step, the caller can sort the input if they really want that.

def subsets(nums, templist=None, start=0):
    if templist is None:
        templist = []
    yield templist
    for i in range(start, len(nums)):
        yield from subsets(nums, templist + nums[i:i+1], i+1)

for t in subsets([1, 2, 3]):
    print(t)

This code produces the same output as the earlier code.

Here's a non-recursive way to make subsets that's a little more compact. It uses a similar algorithm to the earlier code, but it produces the subsets in a slightly different order. It may be helpful to work through the algorithm by hand, on paper, to see how it works.

def subsets(seq):
    z = [[]]
    for x in seq:
        z += [y + [x] for y in z]
    return z

for t in subsets([1, 2, 3]):
    print(t)

output

[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]

And here's the almost-unreadable one-liner version of that algorithm. ;)

from functools import reduce

def subsets(seq):
    return reduce(lambda z, x: z + [y + [x] for y in z], seq, [[]])

Lastly, here's a way to make subsets using binary numbers. This is handy if you want to get specific subsets without producing them all.

Given a set S of n items there are 2**n subsets. Each subset of S corresponds to a n-bit binary number: a 1 bit in the number means the corresponding item in S is in the subset.

def subsets(seq):
    for i in range(1<<len(seq)):
        a = []
        for u in seq:
            if not i:
                break
            if i & 1:
                a.append(u)
            i >>= 1
        yield a

This generator yields subsets in the same order as the last 2 versions.


问:
Alignment restrictions for malloc()/free()
Older K&R (2nd ed.) and other C-language texts I have read that discuss the implementation of a dynamic memory allocator in the style of malloc() and free() usually also mention, in passing, something about data type alignment restrictions. Apparently certain computer hardware architectures (CPU, registers, and memory access) restrict how you can store and address certain value types. For example, there may be a requirement that a 4 byte (long) integer must be stored beginning at addresses that are multiples of four.

What restrictions, if any, do major platforms (Intel & AMD, SPARC, Alpha) impose for memory allocation and memory access, or can I safely ignore aligning memory allocations on specific address boundaries?

答:
Note that even on IA-32 and the AMD64, some of the SSE instructions/intrinsics require aligned data. These instructions will throw an exception if the data is unaligned, so at least you won't have to debug "wrong data" bugs. There are equivalent unaligned instructions as well, but like Denton says, they're are slower.

If you're using VC++, then besides the #pragma pack directives, you also have the __declspec(align) directives for precise alignment. VC++ documentation also mentions an __aligned_malloc function for specific alignment requirements.

As a rule of thumb, unless you are moving data across compilers/languages or are using the SSE instructions, you can probably ignore alignment issues.

OwnerDisplayName: anon c hacker

OwnerDisplayName: Pramod

ContentLicense: CC BY-SA 2.5


问:
Parsing mixed data with Java
Kind of a Java noob, and have flipped between about 6 different streams+scanner and still haven't found a way to do everything I need to.  Am trying to implement an algorithm to parse a file that follows a certain syntax.  There are several places where I need to peek at the next character to see if it is a parenthesis or comma, and also need to be able to read strings and decimal values.  I had it working with a stream up to the point that I tried to read the double.  The double is NOT in a binary format, so DataInputStream is not what I want.

I could use the scanner for its getNextFloat, but the problem with using a scanner is there are no real delimiters in the file: (test:1.234,rightTest:5.6789)

If I specify ( , : ) as delimeters with the Scanner, then I lose the ability to test for their existence of the delimiter(I thionk, because the way it seems is it eats the delimiter).  These blocks can be nested in each other in various ways, so I often need to test the next char to see if it's a opening parenthesis and then branch to different pieces of logic. I.e. it forms a tree(but please don't right code to parse a tree because that is my homework assignment).

I could do away with the scanner and just go back to my original solution with a stream if I could only figure out how to parse the decimal value.  I need something that does a "read until you find one of these characters" so that I can say stream.ReadUntil(",)").  The decimals are always followed by a comma or closing paren.  As a hack I will probably just read one char at a time.  This is the same thing I did to grab the string like "test" and "rightTest", and it felt really awful.

The only other option I know if is something with a string tokenizer, but my feeling from examples is that I'd have to read the entire file into a string to tokenize it, essentially defeating the purpose of using a stream.  These files can be really big and just as an exersize for myself I like to try and code such that I don't bring it all into memory if it is unnecessary, even though for this assignment it doesn't really matter.

So essentially what I'm looking for is some help on the mechanics of the file IO to be able to peek at the next char so I can check for  ( , : ) when necesary, and also have the ability to read a string up to a : and read a decimal value up to a : or )

答: You can also try to map your file through a MappedByteBuffer to access it (roughly) as it were a byte array in memory. And if you need to treat it as a character stream, you can wrap it into a CharBuffer. See for eg. here (Mapped Files section).

Title: Parsing mixed data with Java


问:
How to upload images in Hapi.Js via multipart request?
How to make an API in node.js using hapi and accept multipart request from client? I found pez, but I don't really know what it is and know how it works since it doesn't really provide any description or document.

I've made similar service in Express using multer multer, or perhaps is it the same thing as pez?

答: I manage to make a little library to parse multipart request in javascript generally, the code is available here.</p>


问:
how to change icon colors dynamically in react js
how to change icons colors dynamically below here:

```<code>var byillingvalues=[];
for(var i in this.state.Alldata){
  byillingvalues.push({bycdata:this.state.Alldata[i].label})
}

var values=byillingvalues.map(function(d,idx){
        let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
        for(var i=0;i<=colors.length;i++){
              if(i==idx){
               return (<span key={idx}>{<i className="fa fa-square" aria-
                hidden="true" color:colors[i]></i>} {d.bycdata}   </span>);
             }

        }

});
</code>```

How to change icon colors dynamically in react?

答:
```<code>    var byillingvalues=[];
    for(var i in this.state.Alldata){
         byillingvalues.push({bycdata:this.state.Alldata[i].label})
    }
    var values=byillingvalues.map(function(d,idx){
    let colors=
        ["#6cbe45","#347cb5","#6cc1e6","#9d6bad","#4ebe9f","#4ebe9f","#bed730"];
    for(var i=0;i<colors.length;i++){
            if(i==idx){
             return (<span key={idx}>{<i className="fa fa-square" aria-
              hidden="true"  style={{color:colors[i]}}></i>} {d.bycdata}
                    </span>);
            }
    }

});
</code>```

Body:
how to change icons colors dynamically below here:

var byillingvalues=[];
for(var i in this.state.Alldata){
  byillingvalues.push({bycdata:this.state.Alldata[i].label})
}

var values=byillingvalues.map(function(d,idx){
        let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
        for(var i=0;i<=colors.length;i++){
              if(i==idx){
               return ({} {d.bycdata}   );
             }

        }

});

How to change icon colors dynamically in react?

Body:
    var byillingvalues=[];
    for(var i in this.state.Alldata){
         byillingvalues.push({bycdata:this.state.Alldata[i].label})
    }
    var values=byillingvalues.map(function(d,idx){
    let colors=
        ["#6cbe45","#347cb5","#6cc1e6","#9d6bad","#4ebe9f","#4ebe9f","#bed730"];
    for(var i=0;i<colors.length;i++){
            if(i==idx){
             return (<span key={idx}>{<i className="fa fa-square" aria-
              hidden="true"  style={{color:colors[i]}}></i>}&nbsp;{d.bycdata}
                  &nbsp;&nbsp;</span>);
            }
    }

});


问:
Unity Bouncy PhysicsMat2D Not Works properly
When I Shoot a ball with force, if the force is faster than a number, everything goes well and the ball bouncing. but when the force is less than a number, it seems that bounce not works anymore and the ball move along the wall.

https://imgur.com/a/ZSoVB
(excuse me that i couldn't upload picture here)

the green one is correct for me, and the red one not correct.
I use physicsMat2D,

Friction = 0 and Bounciness = 1

答:
There is a threshold for the speed in Box2D. Try changing the velocity threshold in Edit -> Project Settings -> Physics2D

The closer the value is to zero the smaller the impact can be to stil be counted as a bounce.


问:
How to append and remove all element under div using jquery
I created a form for product sale. admin can add fields for multiple product's click on add button using jquery and can remove by clicking on remove button. I'm trying to append this using div id but this doesn't work.
here is my html part.

```<code><div class="row" id="dsf">
    <div class="col-md-2">
        <select name="p_name" class="form-control" id="p_name">
            <option value="">-Select Product-</option>
            @foreach($products as $product)
                <option value="{{$product->product_id}}">{{$product->name}}</option>
            @endforeach
        </select>
    </div>
    <div class="col-md-2">
        <input type="text" name="p_code" id="p_code" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="u_price" id="u_price" class="form-control" readonly="">
    </div>
    <div class="col-md-1">
        <input type="text" name="ctn" id="ctn" class="form-control">
    </div>
    <div class="col-md-1">
        <input type="text" name="pcs" id ="pcs" class="form-control">
    </div>
    <div class="col-md-2">
        <input type="text" name="t_amt" id="t_amt" class="form-control">
    </div>
</div>
</code>```

Here is my jquery part.

```<code>$(document).ready(function(){
    $("#addrow").click(function(){
        $("#dsf").append();
    });
});
</code>```

答:
if you want to append data after div then use this code

```<code>$(document).ready(function(){
        $("#addrow").click(function(){
            var content = $("#dsf").html();
            $('#addrow').append(content);
        });
    });
</code>```

this is demo code for test

    $(document).ready(function(){
        $("#addrow").click(function(){
            var content = $("#dsf").html();
            $('#addrow').append(content);
        });
    });```
<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 class="row" id="dsf">

    <div class="col-md-2">
        <input type="text" name="p_code" id="p_code" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="u_price" id="u_price" class="form-control" readonly="">
    </div>
    <div class="col-md-1">
        <input type="text" name="ctn" id="ctn" class="form-control">
    </div>
    <div class="col-md-1">
        <input type="text" name="pcs" id ="pcs" class="form-control">
    </div>
    <div class="col-md-2">
        <input type="text" name="t_amt" id="t_amt" class="form-control">
    </div>
</div>

<div id="addrow">Click</div></code>```

or you can append after addrow

$(document).ready(function(){
        $("#addrow").click(function(){
            var content = $("#dsf").html();
            $( content ).insertBefore( "#addrow" );
        });
    });```
<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 class="row" id="dsf">

    <div class="col-md-2">
        <input type="text" name="p_code" id="p_code" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="u_price" id="u_price" class="form-control" readonly="">
    </div>
    <div class="col-md-1">
        <input type="text" name="ctn" id="ctn" class="form-control">
    </div>
    <div class="col-md-1">
        <input type="text" name="pcs" id ="pcs" class="form-control">
    </div>
    <div class="col-md-2">
        <input type="text" name="t_amt" id="t_amt" class="form-control">
    </div>
</div>

<div id="addrow">Click</div></code>```

Body:
I created a form for product sale. admin can add fields for multiple product's click on add button using jquery and can remove by clicking on remove button. I'm trying to append this using div id but this doesn't work.
here is my html part.

        <select name="p_name" class="form-control" id="p_name">
            <option value="">-Select Product-</option>
            @foreach($products as $product)
                <option value="{{$product->product_id}}">{{$product->name}}</option>
            @endforeach
        </select>

        <input type="text" name="p_code" id="p_code" class="form-control" readonly="">

        <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">

        <input type="text" name="u_price" id="u_price" class="form-control" readonly="">

        <input type="text" name="ctn" id="ctn" class="form-control">

        <input type="text" name="pcs" id ="pcs" class="form-control">

        <input type="text" name="t_amt" id="t_amt" class="form-control">

Here is my jquery part.

$(document).ready(function(){
    $("#addrow").click(function(){
        $("#dsf").append();
    });
});

Body:
if you want to append data after div then use this code

$(document).ready(function(){
        $("#addrow").click(function(){
            var content = $("#dsf").html();
            $('#addrow').append(content);
        });
    });

this is demo code for test

    $(document).ready(function(){
        $("#addrow").click(function(){
            var content = $("#dsf").html();
            $('#addrow').append(content);
        });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="dsf">

    <div class="col-md-2">
        <input type="text" name="p_code" id="p_code" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="u_price" id="u_price" class="form-control" readonly="">
    </div>
    <div class="col-md-1">
        <input type="text" name="ctn" id="ctn" class="form-control">
    </div>
    <div class="col-md-1">
        <input type="text" name="pcs" id ="pcs" class="form-control">
    </div>
    <div class="col-md-2">
        <input type="text" name="t_amt" id="t_amt" class="form-control">
    </div>
</div>

<div id="addrow">Click</div>

or you can append after addrow

$(document).ready(function(){
        $("#addrow").click(function(){
            var content = $("#dsf").html();
            $( content ).insertBefore( "#addrow" );
        });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="dsf">

    <div class="col-md-2">
        <input type="text" name="p_code" id="p_code" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="unit_pctn" id="unit_pctn" class="form-control" readonly="">
    </div>
    <div class="col-md-2">
        <input type="text" name="u_price" id="u_price" class="form-control" readonly="">
    </div>
    <div class="col-md-1">
        <input type="text" name="ctn" id="ctn" class="form-control">
    </div>
    <div class="col-md-1">
        <input type="text" name="pcs" id ="pcs" class="form-control">
    </div>
    <div class="col-md-2">
        <input type="text" name="t_amt" id="t_amt" class="form-control">
    </div>
</div>

<div id="addrow">Click</div>


问:
PHP Singleton Acting Funny
I have the following code:

```<code>$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "```";
print_r(self::$extensions);
```

<p>Each getInstance() method looks like this:</p>

```public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}
```

<p>Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:</p>

```stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)
```

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!

答:
See http://socket7.net/article/php-5-static-and-inheritance.

The problem is there is only one static variable, defined within the scope of the parent class. To create two static variables, the easiest way is to just define $_instance variable and get_instance method in both subclasses.

Another possible workaround is listed in the comments of the above article: "pass an extra class name parameter into the static method calls telling the method which class it should 'act as.'"

Title: PHP Singleton Acting Funny

Body:
I have the following code:

$e1 = call_user_func(array("MySQL_Extension", "getInstance"));
$e2 = call_user_func(array("Error_Extension", "getInstance"));
self::$extensions->MySQL = $e1;
self::$extensions->Error = $e2;

// Debug
echo "
";
print_r(self::$extensions);

Each getInstance() method looks like this:

public static function getInstance()
{
    if (self::$_instance == null)
    {
        self::$_instance = new self;
    }

    return self::$_instance;
}

Both classes extend the same "Extension_Abstract" class, but for some reason, the "print_r" debug statement listed outputs the following:

stdClass Object (
    [MySQL] => MySQL_Extension Object
    [Error] => MySQL_Extension Object
)

Do you all have any idea why it would be returning two "MySQL_Extension" objects, and completely ignoring the Error_Extension class?  I'm so confused!


问:
How to align the input fields?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

答:
You have to add a  to your last name field.
You should always include a label for better accessibility.
If you don't want to use a label (which is not recommended), you can use flex-box to align it to the bottom:

```<code>.form-group: {
  align-items: flex-end;
  display: flex;
}
</code>```

Title: How to align the input fields?

Body:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

Body:
You have to add a <label> to your last name field.
You should always include a label for better accessibility.
If you don't want to use a label (which is not recommended), you can use flex-box to align it to the bottom:

.form-group: {
  align-items: flex-end;
  display: flex;
}


问:
placing a text right beside another text
I have designed a simple layout in android where I needed to place an element right beside another element. On attempting to do that the textview jumps below the textview that is supposed to be at the side of it. Here is my approach

```<code><LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/movieImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nameTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Name"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:text="Up"
            android:textSize="15sp" />

I want this textview to be placed beside the above textview
        <TextView
            android:id="@+id/2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/1"
            android:text="Two"
            android:textSize="15sp" />

    </LinearLayout>
</code>```

Thanks in assistance

答:
LinearLayouts have and orientation property, that indicates how they elements will grow.
You can nest LinearLayout inside another one if you want to mix orientations, like this:

```<code><LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@id/movieImage"
    android:orientation="vertical">

    <TextView
        android:id="@+id/nameTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Name"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:text="Up"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Two"
            android:textSize="15sp" />
    </LinearLayout>
</LinearLayout>
</code>```

Body:
I have designed a simple layout in android where I needed to place an element right beside another element. On attempting to do that the textview jumps below the textview that is supposed to be at the side of it. Here is my approach

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/movieImage"
        android:orientation="vertical">

        <TextView
            android:id="@+id/nameTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Name"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:text="Up"
            android:textSize="15sp" />

I want this textview to be placed beside the above textview
        <TextView
            android:id="@+id/2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/1"
            android:text="Two"
            android:textSize="15sp" />

    </LinearLayout>

Thanks in assistance

Body:
LinearLayouts have and orientation property, that indicates how they elements will grow.
You can nest LinearLayout inside another one if you want to mix orientations, like this:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@id/movieImage"
    android:orientation="vertical">

    <TextView
        android:id="@+id/nameTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Name"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/movieImage"
            android:text="Up"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Two"
            android:textSize="15sp" />
    </LinearLayout>
</LinearLayout>


问:
Reading multiple lines from an external file - Python
I need to sum certain lines from an external file to calculate the total number for those certain lines. Such as there are 31 days in January and I need to add lines 1-31 to calculate a number of defects for that month. I tried using readline and readlines but all I got was the error code: "TypeError: must be str, not int".

Here is my code (formatting is a little off down below):

```<code>def main():
    print('Hello, this program will calculate the number of defects')
    print('per month and defects per year and average defects per
    month.')
    counter = 0
    keepGoing = 'x'

jan = feb = mar = apr = may = jun = jul = aug = sep = oct = nov = dec = 0
choice = userSelection()
infile = open('data.txt', 'r')
while keepGoing == 'x':
    if choice == 1:
        keepGoing = 'y'
        jan = infile.readline(1-31)
        jan += counter
        print('The number of defects in January were:')

        feb = infile.readline(32-59)
        feb += counter
        print('The number of defects in February were:')

        mar = infile.readline(60-90)
        mar += counter
        print('The number of defects in March were:')

        apr = infile.readline(91-120)
        apr += counter
        print('The number of defects in April were:')

        may = infile.readline(121-151)
        may += counter
        print('The number of defects in May were:')

        jun = infile.readline(152-181)
        jun += counter
        print('The number of defects in June were:')

        jul = infile.readline(182-212)
        jul += counter
        print('The number of defects in July were:')

        aug = infile.readline(213-243)
        aug += counter
        print('The number of defects in August were:')

        sep = infile.readline(244-273)
        sep += counter
        print('The number of defects in September were:')

        oct = infile.readline(274-304)
        oct += counter
        print('The number of defects in October were:')

        nov = infile.readline(305-334)
        nov += counter
        print('The number of defects in November were:')

        dec = infile.readline(335-365)
        dec += counter
        print('The number of defects in December were:')
        print('Program ending, have a nice day.')
</code>```

答:
The while loop isn't really necessary. </p>

```<code>infile = open('filename.txt','r')

infile_list = infile.readlines()

jan = infile_list[0:31]
feb = infile_list[31:60]
.
.
.
.
</code>```

Body:
I need to sum certain lines from an external file to calculate the total number for those certain lines. Such as there are 31 days in January and I need to add lines 1-31 to calculate a number of defects for that month. I tried using readline and readlines but all I got was the error code: "TypeError: must be str, not int".

Here is my code (formatting is a little off down below):

def main():
    print('Hello, this program will calculate the number of defects')
    print('per month and defects per year and average defects per
    month.')
    counter = 0
    keepGoing = 'x'

jan = feb = mar = apr = may = jun = jul = aug = sep = oct = nov = dec = 0
choice = userSelection()
infile = open('data.txt', 'r')
while keepGoing == 'x':
    if choice == 1:
        keepGoing = 'y'
        jan = infile.readline(1-31)
        jan += counter
        print('The number of defects in January were:')

        feb = infile.readline(32-59)
        feb += counter
        print('The number of defects in February were:')

        mar = infile.readline(60-90)
        mar += counter
        print('The number of defects in March were:')

        apr = infile.readline(91-120)
        apr += counter
        print('The number of defects in April were:')

        may = infile.readline(121-151)
        may += counter
        print('The number of defects in May were:')

        jun = infile.readline(152-181)
        jun += counter
        print('The number of defects in June were:')

        jul = infile.readline(182-212)
        jul += counter
        print('The number of defects in July were:')

        aug = infile.readline(213-243)
        aug += counter
        print('The number of defects in August were:')

        sep = infile.readline(244-273)
        sep += counter
        print('The number of defects in September were:')

        oct = infile.readline(274-304)
        oct += counter
        print('The number of defects in October were:')

        nov = infile.readline(305-334)
        nov += counter
        print('The number of defects in November were:')

        dec = infile.readline(335-365)
        dec += counter
        print('The number of defects in December were:')
        print('Program ending, have a nice day.')

Body:
The while loop isn't really necessary.

infile = open('filename.txt','r')

infile_list = infile.readlines()

jan = infile_list[0:31]
feb = infile_list[31:60]
.
.
.
.


问:
helm install --name=mariadb ./mariadb --namespace=openstack is not running
I am following the procedure on this page.

https://docs.openstack.org/openstack-helm/latest/install/developer/all-in-one.html

kubernetes-AIO install complete and running kubeadm.

But, mariadb chart install was failed.

(Status is Running -> Error -> CrashLoopbackOff-> Runing -> Error... loop)

so, I used this command to solve the problem.

kubectl logs mariadb-0 --namespace openstack

The result is like this:

+ CLUSTER_INIT_ARGS=
+ '[' '!' -d /var/lib/mysql/mysql ']'
+ CLUSTER_CONFIG_PATH=/etc/mysql/conf.d/10-cluster-config.cnf
+ MEMBERS=
++ seq 1 3
+ for i in '$(seq 1 ${MARIADB_REPLICAS})'
+ '[' 1 -eq 1 ']'
+ NUM=0
+ CANDIDATE_POD=mariadb-0.mariadb-discovery
+ '[' xmariadb-0.mariadb-discovery '!=' xmariadb-0.mariadb-discovery ']'
+ for i in '$(seq 1 ${MARIADB_REPLICAS})'
+ '[' 2 -eq 1 ']'
++ expr 2 - 1
+ NUM=1
+ CANDIDATE_POD=mariadb-1.mariadb-discovery
+ '[' xmariadb-1.mariadb-discovery '!=' xmariadb-0.mariadb-discovery ']'
+ '[' -n '' ']'
+ MEMBERS+=mariadb-1.mariadb-discovery:4567
+ for i in '$(seq 1 ${MARIADB_REPLICAS})'
+ '[' 3 -eq 1 ']'
++ expr 3 - 1
+ NUM=2
+ CANDIDATE_POD=mariadb-2.mariadb-discovery
+ '[' xmariadb-2.mariadb-discovery '!=' xmariadb-0.mariadb-discovery ']'
+ '[' -n mariadb-1.mariadb-discovery:4567 ']'
+ MEMBERS+=,
+ MEMBERS+=mariadb-2.mariadb-discovery:4567
+ echo 'Writing cluster config for mariadb-0 to /etc/mysql/conf.d/10-cluster-config.cnf'
+ cat
Writing cluster config for mariadb-0 to /etc/mysql/conf.d/10-cluster-config.cnf
Executing upstream docker-entrypoint.
+ echo 'Executing upstream docker-entrypoint.'
+ set +e
+ exec /usr/local/bin/docker-entrypoint.sh mysqld
2017-11-14  7:27:42 139786759522240 [Note] mysqld (mysqld 10.1.23-MariaDB-1~jessie) starting as process 1 ...
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Read nil XID from storage engines, skipping position init
2017-11-14  7:27:42 139786759522240 [Note] WSREP: wsrep_load(): loading provider library '/usr/lib/galera/libgalera_smm.so'
2017-11-14  7:27:42 139786759522240 [Note] WSREP: wsrep_load(): Galera 25.3.20(r3703) by Codership Oy <info@codership.com> loaded successfully.
2017-11-14  7:27:42 139786759522240 [Note] WSREP: CRC-32C: using hardware acceleration.
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Found saved state: 00000000-0000-0000-0000-000000000000:-1, safe_to_bootsrap: 1
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Passing config to GCS: base_dir = /var/lib/mysql/; base_host = 10.1.60.5; base_port = 4567; cert.log_conflicts = no; debug = no; evs.auto_evict = 0; evs.delay_margin = PT1S; evs.delayed_keep_period = PT30S; evs.inactive_check_period = PT0.5S; evs.inactive_timeout = PT15S; evs.join_retrans_period = PT1S; evs.max_install_timeouts = 3; evs.send_window = 4; evs.stats_report_period = PT1M; evs.suspect_timeout = PT5S; evs.user_send_window = 2; evs.view_forget_timeout = PT24H; gcache.dir = /var/lib/mysql/; gcache.keep_pages_size = 0; gcache.mem_size = 0; gcache.name = /var/lib/mysql//galera.cache; gcache.page_size = 128M; gcache.recover = no; gcache.size = 128M; gcomm.thread_prio = ; gcs.fc_debug = 0; gcs.fc_factor = 1.0; gcs.fc_limit = 16; gcs.fc_master_slave = no; gcs.max_packet_size = 64500; gcs.max_throttle = 0.25; gcs.recv_q_hard_limit = 9223372036854775807; gcs.recv_q_soft_limit = 0.25; gcs.sync_donor = no; gmcast.listen_addr = tcp://0.0.0.0:4567; gmcast.segment = 0; gmcast.version = 0; pc.announce_tim
2017-11-14  7:27:42 139786759522240 [Note] WSREP: GCache history reset: old(00000000-0000-0000-0000-000000000000:0) -> new(00000000-0000-0000-0000-000000000000:-1)
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Assign initial position for certification: -1, protocol version: -1
2017-11-14  7:27:42 139786759522240 [Note] WSREP: wsrep_sst_grab()
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Start replication
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Setting initial position to 00000000-0000-0000-0000-000000000000:-1
2017-11-14  7:27:42 139786759522240 [Note] WSREP: protonet asio version 0
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Using CRC-32C for message checksums.
2017-11-14  7:27:42 139786759522240 [Note] WSREP: backend: asio
2017-11-14  7:27:42 139786759522240 [Note] WSREP: gcomm thread scheduling priority set to other:0
2017-11-14  7:27:42 139786759522240 [Warning] WSREP: access file(/var/lib/mysql//gvwstate.dat) failed(No such file or directory)
2017-11-14  7:27:42 139786759522240 [Note] WSREP: restore pc from disk failed
2017-11-14  7:27:42 139786759522240 [Note] WSREP: GMCast version 0
2017-11-14  7:28:10 139786759522240 [Warning] WSREP: Failed to resolve tcp://mariadb-1.mariadb-discovery:4567
2017-11-14  7:28:30 139786759522240 [Warning] WSREP: Failed to resolve tcp://mariadb-2.mariadb-discovery:4567
2017-11-14  7:28:30 139786759522240 [Note] WSREP: (4d30eff1, 'tcp://0.0.0.0:4567') listening at tcp://0.0.0.0:4567
2017-11-14  7:28:30 139786759522240 [Note] WSREP: (4d30eff1, 'tcp://0.0.0.0:4567') multicast: , ttl: 1
2017-11-14  7:28:30 139786759522240 [Note] WSREP: EVS version 0
2017-11-14  7:28:30 139786759522240 [Note] WSREP: gcomm: connecting to group 'mariadb', peer 'mariadb-1.mariadb-discovery:4567,mariadb-2.mariadb-discovery:4567'
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: failed to open gcomm backend connection: 131: No address to connect (FATAL)
         at gcomm/src/gmcast.cpp:connect_precheck():282
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: gcs/src/gcs_core.cpp:gcs_core_open():208: Failed to open backend connection: -131 (State not recoverable)
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: gcs/src/gcs.cpp:gcs_open():1404: Failed to open channel 'mariadb' at 'gcomm://mariadb-1.mariadb-discovery:4567,mariadb-2.mariadb-discovery:4567': -131 (State not recoverable)
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: gcs connect failed: State not recoverable
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: wsrep::connect(gcomm://mariadb-1.mariadb-discovery:4567,mariadb-2.mariadb-discovery:4567) failed: 7
2017-11-14  7:28:30 139786759522240 [ERROR] Aborting```

What should I do?

答:
It seems to me that some packages are being filtered and thus the network discovery is not working. Maybe you the network configuration in your Openstack cluster does not allow service discovery communications.

Also, it could be that you set wrong anything in the chart values configuration. I advise you to check if it works in dev environments like Minikube or Kubernetes Sandbox. If it works in that environment, then there is definitely something wrong in the communication technology you used to configure neutron.

Body:
I am following the procedure on this page.

https://docs.openstack.org/openstack-helm/latest/install/developer/all-in-one.html

kubernetes-AIO install complete and running kubeadm.

But, mariadb chart install was failed.

(Status is Running -> Error -> CrashLoopbackOff-> Runing -> Error... loop)

so, I used this command to solve the problem.

kubectl logs mariadb-0 --namespace openstack

The result is like this:

+ CLUSTER_INIT_ARGS=
+ '[' '!' -d /var/lib/mysql/mysql ']'
+ CLUSTER_CONFIG_PATH=/etc/mysql/conf.d/10-cluster-config.cnf
+ MEMBERS=
++ seq 1 3
+ for i in '$(seq 1 ${MARIADB_REPLICAS})'
+ '[' 1 -eq 1 ']'
+ NUM=0
+ CANDIDATE_POD=mariadb-0.mariadb-discovery
+ '[' xmariadb-0.mariadb-discovery '!=' xmariadb-0.mariadb-discovery ']'
+ for i in '$(seq 1 ${MARIADB_REPLICAS})'
+ '[' 2 -eq 1 ']'
++ expr 2 - 1
+ NUM=1
+ CANDIDATE_POD=mariadb-1.mariadb-discovery
+ '[' xmariadb-1.mariadb-discovery '!=' xmariadb-0.mariadb-discovery ']'
+ '[' -n '' ']'
+ MEMBERS+=mariadb-1.mariadb-discovery:4567
+ for i in '$(seq 1 ${MARIADB_REPLICAS})'
+ '[' 3 -eq 1 ']'
++ expr 3 - 1
+ NUM=2
+ CANDIDATE_POD=mariadb-2.mariadb-discovery
+ '[' xmariadb-2.mariadb-discovery '!=' xmariadb-0.mariadb-discovery ']'
+ '[' -n mariadb-1.mariadb-discovery:4567 ']'
+ MEMBERS+=,
+ MEMBERS+=mariadb-2.mariadb-discovery:4567
+ echo 'Writing cluster config for mariadb-0 to /etc/mysql/conf.d/10-cluster-config.cnf'
+ cat
Writing cluster config for mariadb-0 to /etc/mysql/conf.d/10-cluster-config.cnf
Executing upstream docker-entrypoint.
+ echo 'Executing upstream docker-entrypoint.'
+ set +e
+ exec /usr/local/bin/docker-entrypoint.sh mysqld
2017-11-14  7:27:42 139786759522240 [Note] mysqld (mysqld 10.1.23-MariaDB-1~jessie) starting as process 1 ...
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Read nil XID from storage engines, skipping position init
2017-11-14  7:27:42 139786759522240 [Note] WSREP: wsrep_load(): loading provider library '/usr/lib/galera/libgalera_smm.so'
2017-11-14  7:27:42 139786759522240 [Note] WSREP: wsrep_load(): Galera 25.3.20(r3703) by Codership Oy <info@codership.com> loaded successfully.
2017-11-14  7:27:42 139786759522240 [Note] WSREP: CRC-32C: using hardware acceleration.
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Found saved state: 00000000-0000-0000-0000-000000000000:-1, safe_to_bootsrap: 1
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Passing config to GCS: base_dir = /var/lib/mysql/; base_host = 10.1.60.5; base_port = 4567; cert.log_conflicts = no; debug = no; evs.auto_evict = 0; evs.delay_margin = PT1S; evs.delayed_keep_period = PT30S; evs.inactive_check_period = PT0.5S; evs.inactive_timeout = PT15S; evs.join_retrans_period = PT1S; evs.max_install_timeouts = 3; evs.send_window = 4; evs.stats_report_period = PT1M; evs.suspect_timeout = PT5S; evs.user_send_window = 2; evs.view_forget_timeout = PT24H; gcache.dir = /var/lib/mysql/; gcache.keep_pages_size = 0; gcache.mem_size = 0; gcache.name = /var/lib/mysql//galera.cache; gcache.page_size = 128M; gcache.recover = no; gcache.size = 128M; gcomm.thread_prio = ; gcs.fc_debug = 0; gcs.fc_factor = 1.0; gcs.fc_limit = 16; gcs.fc_master_slave = no; gcs.max_packet_size = 64500; gcs.max_throttle = 0.25; gcs.recv_q_hard_limit = 9223372036854775807; gcs.recv_q_soft_limit = 0.25; gcs.sync_donor = no; gmcast.listen_addr = tcp://0.0.0.0:4567; gmcast.segment = 0; gmcast.version = 0; pc.announce_tim
2017-11-14  7:27:42 139786759522240 [Note] WSREP: GCache history reset: old(00000000-0000-0000-0000-000000000000:0) -> new(00000000-0000-0000-0000-000000000000:-1)
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Assign initial position for certification: -1, protocol version: -1
2017-11-14  7:27:42 139786759522240 [Note] WSREP: wsrep_sst_grab()
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Start replication
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Setting initial position to 00000000-0000-0000-0000-000000000000:-1
2017-11-14  7:27:42 139786759522240 [Note] WSREP: protonet asio version 0
2017-11-14  7:27:42 139786759522240 [Note] WSREP: Using CRC-32C for message checksums.
2017-11-14  7:27:42 139786759522240 [Note] WSREP: backend: asio
2017-11-14  7:27:42 139786759522240 [Note] WSREP: gcomm thread scheduling priority set to other:0
2017-11-14  7:27:42 139786759522240 [Warning] WSREP: access file(/var/lib/mysql//gvwstate.dat) failed(No such file or directory)
2017-11-14  7:27:42 139786759522240 [Note] WSREP: restore pc from disk failed
2017-11-14  7:27:42 139786759522240 [Note] WSREP: GMCast version 0
2017-11-14  7:28:10 139786759522240 [Warning] WSREP: Failed to resolve tcp://mariadb-1.mariadb-discovery:4567
2017-11-14  7:28:30 139786759522240 [Warning] WSREP: Failed to resolve tcp://mariadb-2.mariadb-discovery:4567
2017-11-14  7:28:30 139786759522240 [Note] WSREP: (4d30eff1, 'tcp://0.0.0.0:4567') listening at tcp://0.0.0.0:4567
2017-11-14  7:28:30 139786759522240 [Note] WSREP: (4d30eff1, 'tcp://0.0.0.0:4567') multicast: , ttl: 1
2017-11-14  7:28:30 139786759522240 [Note] WSREP: EVS version 0
2017-11-14  7:28:30 139786759522240 [Note] WSREP: gcomm: connecting to group 'mariadb', peer 'mariadb-1.mariadb-discovery:4567,mariadb-2.mariadb-discovery:4567'
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: failed to open gcomm backend connection: 131: No address to connect (FATAL)
         at gcomm/src/gmcast.cpp:connect_precheck():282
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: gcs/src/gcs_core.cpp:gcs_core_open():208: Failed to open backend connection: -131 (State not recoverable)
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: gcs/src/gcs.cpp:gcs_open():1404: Failed to open channel 'mariadb' at 'gcomm://mariadb-1.mariadb-discovery:4567,mariadb-2.mariadb-discovery:4567': -131 (State not recoverable)
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: gcs connect failed: State not recoverable
2017-11-14  7:28:30 139786759522240 [ERROR] WSREP: wsrep::connect(gcomm://mariadb-1.mariadb-discovery:4567,mariadb-2.mariadb-discovery:4567) failed: 7
2017-11-14  7:28:30 139786759522240 [ERROR] Aborting

What should I do?


问:
JSON - Unable to parse
I am unable to parse the following piece.
Please let me know if you have any clue(s)</p>

```<code><HTML>
<HEAD>
<SCRIPT>
var s = '{"CCMP_11":{"QuestionText":"\u003cp\u003eFor all inputs received, automated sanity checks with the last cycle data are performed and QC of control totals are conducted.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_11","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":2.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_20":{"QuestionText":"\u003cp\u003eAll client deliverable reports / files (interim and final) containing compliance sensitive data are clearly marked with requisite compliance circulation warning before sharing with the client.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_20","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.25,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_21":{"QuestionText":"\u003cp\u003eAll system changes and QC results are reviewed by a senior team member. Review comments are incorporated and rerun test results are shared with the project manager and formal sign off is taken.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_21","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_6":{"QuestionText":"\u003cp\u003eNo parallel tools (eg. Deconstructor tool) are used for QC and automated QCs are established for any deliverable\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_6","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.25,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_12":{"QuestionText":"\u003cp\u003eAll the Javelin-to-Javelin integrations are in place as a precursor to implementing Next Gen Sales Compensation (NGSC)\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_12","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":2.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_29":{"QuestionText":"\u003cp\u003eError-free runs are celebrated and team achievements are recognized at least once a quarter.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_29","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.66667,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_18":{"QuestionText":"\u003cp\u003eResponsibilities are clearly defined and accountability is created within the team as to who will implement and who will check the compliance aspects.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_18","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Implemented, but not doing consistently","Answer":4,"OverallMean":3.5,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CCMP_4":{"QuestionText":"\u003cp\u003eStandard reusable templates are created for deliverables and/or communication that are shared with the client on a regular basis:\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CCMP_4","CheckBoxListItems":"E-mail templates||||Minutes of Meeting||||Status Updates||||Adhoc/Change Request Form","CheckBoxListLabels":"1||||2||||3||||4","CheckBoxes":null,"CheckBoxResponseCodes":"1,3","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.6,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_3":{"QuestionText":"\u003cp\u003eParameterization: All Ad-hoc Inputs to the system have a placeholder within the system and are handled through data inputs (e.g. consuming adjustment blocks for sales,  goal adjustment, payout adjustment, eligibility exceptions,   product weights, report metrics, plan parameters)\u003c/p\u003e\u003cp\u003eA list of all use cases that need system changes during or between operations is maintained by the project and is being worked with JPS team for building the same within the system.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_3","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.5,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"IC_8":{"QuestionText":"\u003cp\u003eThe Individual who runs operations does NOT have access to make system changes ( e.g. data structure change, business rule change, procedure change, report template change, etc.)\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"IC_8","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":2.75,"SectionName":"Common Minimum Practices","IsChecked":false,"SectionId":-999},"CRM_4":{"QuestionText":"\u003cp\u003eAn internal ZS approval and a formal client sign-off on the scope of all change requests and the revised timelines (if any) is obtained, as per the ChaRM framework.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_4","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.16667,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"CRM_5":{"QuestionText":"\u003cp\u003ePeer reviews are formally planned and conducted for all changes. All outcomes are documented and action items tracked until completion.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_5","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.33333,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"CRM_1":{"QuestionText":"\u003cp\u003e* All changes impacting the creation or change of business rules are documented in accordance with the Change Request Management (ChaRM) framework and have the following sections:\u003c/p\u003e\u003cp\u003e\u003col\u003e\u003cli\u003eChange description\u003c/li\u003e\u003cli\u003eImpacted deliverables\u003c/li\u003e\u003cli\u003eBusiness use cases and expected results\u003c/li\u003e\u003cli\u003eChange details for inputs, process and output sections along with assumptions\u003c/li\u003e\u003cli\u003eInput/output mockups indicating changes for all business cases\u003c/li\u003e\u003cli\u003eRisks, if any\u003c/li\u003e\u003cli\u003eCosts, if any\u003c/li\u003e\u003c/ol\u003e\u003c/p\u003e\u003cp\u003eClear owner(s) are identified who will be accountable for tracking all requirement/business rule change decisions and documenting them properly.\u003c/p\u003e \u003cp\u003eClick here to understand ChaRM framework in detail.\u003cbr /\u003e\u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-43529\"\u003ehttps://zspace.zsassociates.com/docs/DOC-43529\u003c/a\u003e\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_1","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.16667,"SectionName":"Change Request Management","IsChecked":true,"SectionId":3},"CRM_2":{"QuestionText":"\u003cp\u003eOnTrak/ client tool or Excel template is used by the project team and/or client to implement a structured review-approve process for:\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"\u003cp\u003eFollowing parameters should be added for each ticket - Complexity, Business impact, process impact, scope, ownerships, impact on deliverables, testing and functional design, timelines, business context.\u003c/p\u003e \u003cp\u003e\u003ca target=_blank href = \"https://zspace.zsassociates.com/docs/DOC-45596\"\u003eClick here\u003c/a\u003e to see the OnTrak guides on ZSpace.\u003c/p\u003e","QuestionId":"CRM_2","CheckBoxListItems":"Observed defects, enhancements, issues, rework, Adhocs and operational items||||Changes of Business rules||||Change requests and operations related items (e.g. approvals, confirmations, Input notification, etc.)","CheckBoxListLabels":"1||||2||||3","CheckBoxes":null,"CheckBoxResponseCodes":"2","AnswerText":"Implemented, but not doing consistently","Answer":4,"OverallMean":3.66667,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"CRM_3":{"QuestionText":"\u003cp\u003eA comprehensive impact analysis of change requests is conducted using Data Flow Diagrams (DFDs) and documented. A template capturing the impact of all change requests and associated dependencies is maintained internally by the team.\u003c/p\u003e\u003cp\u003ePlease refer to the ChaRM framework for the template:\u003cbr /\u003e\u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-43529\"\u003ehttps://zspace.zsassociates.com/docs/DOC-43529\u003c/a\u003e\u003cp\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"CRM_3","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Implementation in progress","Answer":3,"OverallMean":3.83333,"SectionName":"Change Request Management","IsChecked":false,"SectionId":3},"PM_3":{"QuestionText":"\u003cp\u003e* Cross-work stream trainings are planned and imparted to team members.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_3","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":2.75,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_5":{"QuestionText":"\u003cp\u003eAll the project team members are provided in the moment/immediate feedback by applying the COIN framework. The channels leveraged include email, informal/formal meeting or ZS COIN app.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_5","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.33333,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_7":{"QuestionText":"\u003cp\u003eThe EVOLVE program sheet is maintained for all team roles and is used for team reviews and role discussions with team members.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_7","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Not considering","Answer":1,"OverallMean":3.33333,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_4":{"QuestionText":"\u003cp\u003e* Backup and succession planning is done periodically (at least each semester) and well documented. The team structure and upcoming resource needs are also reviewed as a part of the same.\u003c/p\u003e\u003cp\u003eClick on the link below to see sample documents on ZSpace\u003cbr /\u003e \u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-45693\"\u003ehttps://zspace.zsassociates.com/docs/DOC-45693\u003c/a\u003e\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_4","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":4,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_6":{"QuestionText":"\u003cp\u003eThe project Consultant/Manager has a formal one on one discussion with each team member at least once a quarter.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_6","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3.66667,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_8":{"QuestionText":"\u003cp\u003eThe project manager sets specific short and long-term goals for each individual for each review period.\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"","QuestionId":"PM_8","CheckBoxListItems":"","CheckBoxListLabels":"","CheckBoxes":null,"CheckBoxResponseCodes":"","AnswerText":"Planning in progress","Answer":2,"OverallMean":3,"SectionName":"People Management","IsChecked":false,"SectionId":6},"PM_2":{"QuestionText":"\u003cp\u003e* A training, transition \u0026 onboarding plan is setup for the project which includes a list of courses that each team member should take and is consistently followed for all project onboardings.\u003cp\u003e\u003c/p\u003eThe training, transition and onboarding plans should also cover:\u003c/p\u003e","QuestionPrefix":"","QuestionSuffix":"\u003cp\u003eClick on the link below to see sample documents on ZSpace \u003cbr /\u003e\u003ca target=_blank href=\"https://zspace.zsassociates.com/docs/DOC-45692\"\u003ehttps://zspace.zsassociates.com/docs/DOC-45692\u003c/a\u003e\u003c/p\u003e","QuestionId":"PM_2","CheckBoxListItems":"Client Business context and team structure||||Business rules||||Project SOW and noteworthy Work orders/Change requests||||Process Visio Diagrams for system overview and detailed sections||||Project Calendar||||SLA details||||System Access setup||||System inputs||||System setup including Javelin Suite||||Deliverables||||Tools","CheckBoxListLabels":"1||||2||||3||||4||||5||||6||||7||||8||||9||||10||||11","CheckBoxes":null,"CheckBoxResponseCodes":"1,2","AnswerText":"Implementation in progress","Answer":3,"OverallMean":3.5,"SectionName":"People Management","IsChecked":false,"SectionId":6}}';
var v = JSON.parse(s);
</SCRIPT>
</HEAD>
<body>
TESTING JSON
</BODY>
</HTML>
</code>```

答:
String should be supported by JSON, You have unwanted characters in your string, You must remove those character from string.

Example :

```<code><HTML>
<HEAD>
<SCRIPT>
var s = '{"CCMP_11":{"hello":"hai"}}'; // Correct string format for JSON
var v = JSON.parse(s);
console.log(v);
</SCRIPT>
</HEAD>
<body>
TESTING JSON
</BODY>
</HTML>
</code>```

Title: JSON - Unable to parse

Body:
I am unable to parse the following piece.
Please let me know if you have any clue(s)

TESTING JSON

Body:
String should be supported by JSON, You have unwanted characters in your string, You must remove those character from string.

Example :

<HTML>
<HEAD>
<SCRIPT>
var s = '{"CCMP_11":{"hello":"hai"}}'; // Correct string format for JSON
var v = JSON.parse(s);
console.log(v);
</SCRIPT>
</HEAD>
<body>
TESTING JSON
</BODY>
</HTML>


问:
AWS PinPoint - Sending push notifications FROM Android device
I need to send push notifications between Android devices for an AWS Mobile Hub project. It is only device-to-device messaging, no topics involved. I have already integrated FCM and PinPoint

```<code>pinpointManager.getNotificationClient().registerDeviceToken(newToken)
</code>```

I'm getting the endPointID using this code

```<code>String epID = pinpointManager.getTargetingClient().currentEndpoint().getEndpointId();
</code>```

I can successfully push messages to the device from PinPoint console using the above endPointID. But I want to push from the android device itself. However, since there isn't any publish API available in PinPoint Android SDK, I have integrated SNS. I'm trying to publish with SNS using the endpointID received from PinPoint using this code:

```<code>PublishRequest publishRequest = new PublishRequest();
publishRequest.setTargetArn(epID);
publishRequest.setMessage("Hello from android");

AmazonSNSClient snsClient = new AmazonSNSClient(App.getCCCProvider());
snsClient.publish(publishRequest);
</code>```

but receiving the following exception

com.amazonaws.services.sns.model.InvalidParameterException: Invalid parameter: TargetArn Reason: An ARN must have at least 6 elements, not 1 (Service: AmazonSNS; Status Code: 400; Error Code: InvalidParameter; Request ID: 7ff39768-c6f9-5a6e-8211-c5ec586276fb)

If it helps, my endpointID is : 1fa93529-a5ac-4d70-995a-be1584c68a37

Any pointers or solutions from you guys?

答:
The API you are looking for is the Pinpoint.sendMessages API.

REST Documentation

JavaDoc for sendMessages

Your request would probably look something like:

```<code>amazonPinpoint.sendMessages(
        new SendMessagesRequest()
                .withApplicationId("APP_ID")
                .withMessageRequest(
                        new MessageRequest()
                                .withMessageConfiguration(
                                        new DirectMessageConfiguration()
                                                .withGCMMessage(
                                                        new GCMMessage()
                                                                .withBody("Hello from android")
                                                )
                                )
                                .addEndpointsEntry(
                                        "DESTINATION_ENDPOINT_ID",
                                        // You can provide overrides and the like here
                                        new EndpointSendConfiguration()
                                )
                )
)
</code>```

Body:
I need to send push notifications between Android devices for an AWS Mobile Hub project. It is only device-to-device messaging, no topics involved. I have already integrated FCM and PinPoint

pinpointManager.getNotificationClient().registerDeviceToken(newToken)

I'm getting the endPointID using this code

String epID = pinpointManager.getTargetingClient().currentEndpoint().getEndpointId();

I can successfully push messages to the device from PinPoint console using the above endPointID. But I want to push from the android device itself. However, since there isn't any publish API available in PinPoint Android SDK, I have integrated SNS. I'm trying to publish with SNS using the endpointID received from PinPoint using this code:

PublishRequest publishRequest = new PublishRequest();
publishRequest.setTargetArn(epID);
publishRequest.setMessage("Hello from android");

AmazonSNSClient snsClient = new AmazonSNSClient(App.getCCCProvider());
snsClient.publish(publishRequest);

but receiving the following exception

com.amazonaws.services.sns.model.InvalidParameterException: Invalid parameter: TargetArn Reason: An ARN must have at least 6 elements, not 1 (Service: AmazonSNS; Status Code: 400; Error Code: InvalidParameter; Request ID: 7ff39768-c6f9-5a6e-8211-c5ec586276fb)

If it helps, my endpointID is : 1fa93529-a5ac-4d70-995a-be1584c68a37

Any pointers or solutions from you guys?

Body:
The API you are looking for is the Pinpoint.sendMessages API.

REST Documentation

JavaDoc for sendMessages

Your request would probably look something like:

amazonPinpoint.sendMessages(
        new SendMessagesRequest()
                .withApplicationId("APP_ID")
                .withMessageRequest(
                        new MessageRequest()
                                .withMessageConfiguration(
                                        new DirectMessageConfiguration()
                                                .withGCMMessage(
                                                        new GCMMessage()
                                                                .withBody("Hello from android")
                                                )
                                )
                                .addEndpointsEntry(
                                        "DESTINATION_ENDPOINT_ID",
                                        // You can provide overrides and the like here
                                        new EndpointSendConfiguration()
                                )
                )
)