问:
Excel - Search for string in list
So let's say we have a list of sentences in the cells of column A that may or may not contain names.

```<code>A1: "The sea was blue"
A2: "together with Mary"
A3: "onward and upward" and so on...
</code>```

I want to be able to check if a certain name exist within the entire list with True / False. For example, if I checked Mary it would return True. Joe would return False.

I've tried a few things, but they only seem to work if the name is the only thing in the cell. I want it to be able to search sentences in the list of cells, I'm just not sure how to proceed.

Much appreciated!

答:
This searches for the text in a cell (B8 in this example) in the list of sentences (A8:A10). It's surrounded by an IF statement to turn it into TRUE FALSE. SEARCH returns #VALUE if not found, hence use of IFERROR.</p>

```<code>=IF(IFERROR(SEARCH(B8,$A$8:$A$10),0)=1,TRUE,FALSE)
</code>```

Title: Excel - Search for string in list

Body:
So let's say we have a list of sentences in the cells of column A that may or may not contain names.

A1: "The sea was blue"
A2: "together with Mary"
A3: "onward and upward" and so on...

I want to be able to check if a certain name exist within the entire list with True / False. For example, if I checked Mary it would return True. Joe would return False.

I've tried a few things, but they only seem to work if the name is the only thing in the cell. I want it to be able to search sentences in the list of cells, I'm just not sure how to proceed.

Much appreciated!

Body:
This searches for the text in a cell (B8 in this example) in the list of sentences (A8:A10). It's surrounded by an IF statement to turn it into TRUE FALSE. SEARCH returns #VALUE if not found, hence use of IFERROR.

=IF(IFERROR(SEARCH(B8,$A$8:$A$10),0)=1,TRUE,FALSE)


来源: stackexchange

问:
Programmatically update the value of the Flight Plan 'rotation' parameter
I would like to programmatically update the value of the Flight Plan 'rotation' parameter (flight direction).
However, it seems that this parameter is part of the 'info' substructure that is read-only and cannot be updated.
Is there another way to update the rotation value?
Obviously, I expect the flight duration to get recalculated and updated accordingly by the DroneDeploy App as a result of this update.</p>

答:
Thanks  @Eyal.

I think we should make that parameter available for you to edit, but bear in mind that we are intending to auto optimise the flight direction ourselves as a default feature in the next 4 weeks.

The optimisation will be relatively naive though, and only seek to reduce the flight time.

ContentLicense: CC BY-SA 3.0


问:
Regex to match exact phrase before certain word
I would like to match any four digits occurring before double space and word "from"  ex.

2356  from

1524  from

1223  from

The expression \d{4}  from extracts digits, double space and the word "from", but ideally I would like to get only those four digits (without the trailing spaces and word "from") and only in cases when they are not part of number with hyphen like this example:

2536  from = 2536

8574  from = 8574

35-6655  from = no match

3652 = no match (number without word "from" after the digits)

答:
You need to use either grouping (...) operators in your regex:

```<code>(\d{4})  from
</code>```

and then extract group #1 from the match.  Or a zero-width look-ahead match using (?=...).

```<code>\d{4}(?=  from)
</code>```

To avoiding a match following the hyphen, you can use a zero-width negative look-behind.

```<code>(?<!-)\d{4}(?=  from)
</code>```

Explanation:

(?<!_)_______________ negative zero-width look-behind ...

____-________________ ... doesn't match if a "-" is found

______\d{4}__________ four digits

___________(?=______) positive zero-width look-ahead ...

______________  from_ ... matches if "  from" is found

Body:
You need to use either grouping (...) operators in your regex:

(\d{4})  from

and then extract group #1 from the match.  Or a zero-width look-ahead match using (?=...).

\d{4}(?=  from)

To avoiding a match following the hyphen, you can use a zero-width negative look-behind.

(?<!-)\d{4}(?=  from)

Explanation:

(?<!_)_______________ negative zero-width look-behind ...

____-________________ ... doesn't match if a "-" is found

______\d{4}__________ four digits

___________(?=______) positive zero-width look-ahead ...

______________  from_ ... matches if "  from" is found


问:
CSS Style sheet is applying to all pages, but is showing different results
I am trying to get all pages to look the same and the DIVs connected.

Here is my code

```<code>footer{
height:auto;
padding:10px;
background-color:lightgray;
margin-right:auto;
margin-left:auto;
text-align:center;

}

article{
height:auto;
background-color:darkgray;
margin-right:auto;
margin-left:auto;
text-align:center;
}

h1,h2,h3,h4,h5,h6{
margin:0;
}

#wrapper{
width:80%;
margin-left:10%;
margin-right:10%;
border:2px solid black;
background-color:lightgray;
box-shadow: 10px 10px 5px #888888;
border-top-left-radius:18px;
border-top-right-radius:18px;
border-bottom-left-radius:18px;
border-bottom-right-radius:18px;
}

header{
height:140px;
background-color:lightgray;
background-image:url(logo1.png);
background-repeat:no-repeat;
background-position:20px center;
text-align:center;
border-bottom-left-radius:18px;
border-bottom-right-radius:18px;
}

nav{
height:40px;
background-color:lightgray;
margin-left:auto;
margin-right:auto;
text-align:center;
width:auto;
}
</code>```

I expect all the corners to be rounded and all margins to be the same.

The result I receive is a top corner rounded but bottom not, the margins on one page are great, but there are none on another, border not showing up on certain. I am positive the page is linked. The background colors are not following.

Here's the link to my assignment:
https://iceconescafe.000webhostapp.com/index.html

I just want to let you know I fixed a majority of the issues, but the nav table is aligning different on most pages. Some pages don't have the div styling done yet so please focus on Kids Menu and Menu, as well as Index.

The issues are the margins on kids menu, and the nav table alignments, as well as the article not changing on testimonials (background).

Here is the html code:

```<code><html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="icon" href="logo.png" type=" image/png">
<title> IceCones</title>
</head>

<body>
<div id="wrapper">
<header>
<h1 id="t" class="l"> Ice Cones Cafe </h1>

</header>

<nav>
<table  id=navtable class="tr">
<tr>
<td class="td"><a href="index.html" class="b3">Home</a></td>
<td class="td"><a href="menu.html" class="b3">Menu</a></td>
<td class="td"><a href="kids.html" class="b3">Kids Menu</a></td>
<td class="td"><a href="nutrition.html" class="b3">Nutrition</a></td>
<td class="td"><a href="testimonials.html" class="b3">Testimonials</a></td>
<td class="td"><a href="orderonline.html" class="b3">Order Online</a></h5></td>
</tr>
</table>

</nav>
<article class="setmin">
<br>
<img src="IceConesLog.jpg" border="3">

<br>
<blockquote>
<p >

Ice Cones Cafe, established in 1880, is the best ice cream joint in town!  With desserts ranging from waffles to ice cream, Ice Cones only uses the purest  ice from Antarctica. With our wide selection of foods, and our expertise  chefs,
you will never leave unhappy.  Only when you walk through our doors  will you taste the best ice cream the world has to offer! </p>
</blockquote>
</article>

<footer>

<h4><b> Contact Information </h4>

<ul>
<li> Abdu Hijazi </li>
<li>contact_support@icecones.com</li>
<li>(313)962-7906</li> </b>

<audio autoplay loop>
  <source src="ice.mp3" type="audio/mpeg">
</footer>
</div>
</body>
</html>

Ignore this (Next page Menu)

<html>
<head>
<link rel="icon" href="IceConesfavicon.ico" type=" image/png">
<link rel="stylesheet" type="text/css" href="index.css">
<title> Menu</title>
</head>
<body>
<div id="wrapper">
<header>

<h1 id="t"> Ice Cones Cafe </h1>
</header>
<nav>
<table class="tr">
<tr>
<td class="td"><a href="index.html" class="b3">Home</a></td>
<td class="td"><a href="menu.html" class="b3">Menu</a></td>
<td class="td"><a href="kids.html" class="b3">Kids Menu</a></td>
<td class="td"><a href="nutrition.html" class="b3">Nutrition</a></td>
<td class="td"><a href="testimonials.html" class="b3">Testimonials</a></td>
<td class="td"><a href="orderonline.html" class="b3">Order Online</a></h5></td>
</tr>
</table>
</nav>

</tr>

<article>
<h2> Menu</h2>

<table>
<th colspan="3"> Menu </th>

<tr>
<th>Picture</th>
<th>Description</th>
<th>Price</th>
</tr>

<tr>
<td><img src="SnowConeMenu1.jpg"></td>
<td>The classic ice in a cup. Our Ice Cones come in flavors of lemon lime, blue berry, and cotton candy. This product is our cafe's specialty.</td>
<td>Small/$0.99 Large/$1.99</td>
</tr>

<tr>
<td><img src="IceCream.jpg"></td>

<td>Another famous classic using ice imported directly from the freshest and purest ice.
With our different flavors of chocolate, vanilla, buttermilk, and pistachio, there are various flavors to try. We also come up with new flavors weekly. </td>
<td>1 scoop/$1.50    2 scoop/$2</td>
</tr>

<tr>
<td><img src="BananaSplit.jpg"></td>
<td> The banana split features a combination of banana, whipped cream, sprinkles, and even a cherry on top. The best part however, is that
warm, melting chocolate syrup.</td>
<td>$2.99</td>

<tr>
<td><img src="OreoShake.jpg"></td>
<td> The classic American favorite of Oreo cookies mixed with milk. A tasty, chunky, cold recipe that your taste buds won't soon forget.</td>
<td>$2.50</td>
</tr>

</table>
</article>
<footer>
<h4> Contact Information </h4>

<ul>
<li> Abdu Hijazi </li>
<li>contact_support@icecones.com</li>
<li>(313)962-7906</li> </b>
</footer>
</div>
</body>
</html>

Kids Menu

<html>
<head>
<title> KidsMenu</title>
<link rel="icon" href="IceConesfavicon.ico" type=" image/png">
<link rel="stylesheet" type="text/css" href="index.css">
</head>

<body>
<header>
<h1 id="t"> Ice Cones Cafe </h1>
</header>

<nav>
<table class="tr">
<tr>
<td class="td"><a href="index.html" class="b3">Home</a></td>
<td class="td"><a href="menu.html" class="b3">Menu</a></td>
<td class="td"><a href="kids.html" class="b3">Kids Menu</a></td>
<td class="td"><a href="nutrition.html" class="b3">Nutrition</a></td>
<td class="td"><a href="testimonials.html" class="b3">Testimonials</a></td>
<td class="td"><a href="orderonline.html" class="b3">Order Online</a></h5></td>
</tr>
</table>

</nav>
<article>

<h2>Kids Menu</h2>

<table>
<th colspan="3"> Kid's Menu </th>

<tr >
<th>Picture</th>
<th>Description</th>
<th>Price</th>
</tr>

<tr>
<td><img src="MiniWaffle.png"></td>
<td> Our chef specially makes these in sizes of 1/3 regular waffles. A great meal for you kid in the morning, or anytime.</td>
<td>$4.59</td>
</tr>

<tr>
<td><img src="SmoresKids.jpg"></td>

<td> These smores are a small, but tasty item for your kids. Includes chocolate syrup, marshmallows, graham crackers, and whipped cream. </td>
<td>$3.99 <br> with whip/$4.50</td>
</tr>

<tr>
<td><img src="FrozenHotChoco.jpg"></td>
<td> Although you're probably thinking warm at a ice cream place is crazy, we have added a frozen aspect to hot chocolate for your kids. They will love
the whipped cream and added syrup.</td>
<td>$3.50</td>

<tr>
<td><img src="KidsCrepe.jpg"></td>
<td> A small, warm crepe filled with whatever your child desires. Banana, Nutella, and strawberry are all viable options, along with
syrups and creams on top.</td>
<td>$4.99</td>
</tr>
<br>
</table>

<h1>Kiddie Activity</h1>
<br>
<img src="Danykmem84.png">
</article>
<footer>
<br>
<br>
<h4> Contact Information </h4>

<ul>
<li> Abdu Hijazi </li>
<li>contact_support@icecones.com</li>
<li>(313)962-7906</li> </b>
</ul>
</footer>
</div>

</body>
</html>

lastly, testimonials
<html>
<head>
<link rel="icon" href="IceConesfavicon.ico" type=" image/png">
<link rel="stylesheet" type="text/css" href="index.css">
<title> IceCones</title>
</head>
<body>
<div id="wrapper">

<div id="header">
<h1 id="t"> Ice Cones Cafe </h1>
</div>
<div id="nav">
<table class="tr">
<tr>
<td class="td"><a href="index.html" class="b3">Home</a></td>
<td class="td"><a href="menu.html" class="b3">Menu</a></td>
<td class="td"><a href="kids.html" class="b3">Kids Menu</a></td>
<td class="td"><a href="nutrition.html" class="b3">Nutrition</a></td>
<td class="td"><a href="testimonials.html" class="b3">Testimonials</a></td>
<td class="td"><a href="orderonline.html" class="b3">Order Online</a></h5></td>
</tr>
</table>
</div>
<div id="article">
<h2>Testimonials</h2>

<p> Below are some testimonials from our CEO and a trusted customer:</p>

<p> Testimonial~CEO Abdu Hijazi</p>

<video controls>
<source src="Test1.mp4" type="video/mp4">
</video>

<p> Testimonial~Satisfied Customer Sara Hijazi</p>

<video controls>
<source src="Test2.mp4" type="video/mp4">
</video>
</div>
<div id="footer">
<h4>Contact Information </h4>

<ul>
<li> Abdu Hijazi </li>
<li>contact_support@icecones.com</li>
<li>(313)962-7906</li>
</div>
</div>
</body>
</html>
</code>```

答:
1) Make sure the HTML you are applying your CSS to does not have any inline styling (style="...") or any embedded CSS already that is overriding your linked style sheet.

Or if their are other linked style sheets, consider removing them or making the main style sheet above the last link so it overrides any conflicting rules in the others.

2) If you still have issues, try using Chrome devtools (F12) or right-click on the page where it doesn't look right and select "inspect element". The right-hand side of the window that pops up shows how the browser is interpreting the CSS. So you can use that to debug why it's not showing up right.

3) And/or try adding the !important rule (What does !important in CSS mean?) to any rule in your style sheet that seems to be getting ignored. But it's generally better form to remove the overriding style rules in the HTML and/or fix any issues in your stylesheets

Hope that helps!

Body:
I am trying to get all pages to look the same and the DIVs connected.

Here is my code

footer{
height:auto;
padding:10px;
background-color:lightgray;
margin-right:auto;
margin-left:auto;
text-align:center;

}

article{
height:auto;
background-color:darkgray;
margin-right:auto;
margin-left:auto;
text-align:center;
}

h1,h2,h3,h4,h5,h6{
margin:0;
}

#wrapper{
width:80%;
margin-left:10%;
margin-right:10%;
border:2px solid black;
background-color:lightgray;
box-shadow: 10px 10px 5px #888888;
border-top-left-radius:18px;
border-top-right-radius:18px;
border-bottom-left-radius:18px;
border-bottom-right-radius:18px;
}

header{
height:140px;
background-color:lightgray;
background-image:url(logo1.png);
background-repeat:no-repeat;
background-position:20px center;
text-align:center;
border-bottom-left-radius:18px;
border-bottom-right-radius:18px;
}

nav{
height:40px;
background-color:lightgray;
margin-left:auto;
margin-right:auto;
text-align:center;
width:auto;
}

I expect all the corners to be rounded and all margins to be the same.

The result I receive is a top corner rounded but bottom not, the margins on one page are great, but there are none on another, border not showing up on certain. I am positive the page is linked. The background colors are not following.

Here's the link to my assignment:
https://iceconescafe.000webhostapp.com/index.html

I just want to let you know I fixed a majority of the issues, but the nav table is aligning different on most pages. Some pages don't have the div styling done yet so please focus on Kids Menu and Menu, as well as Index.

The issues are the margins on kids menu, and the nav table alignments, as well as the article not changing on testimonials (background).

Here is the html code:

<link rel="stylesheet" type="text/css" href="index.css">
<link rel="icon" href="logo.png" type=" image/png">
<title> IceCones</title>

 Ice Cones Cafe

Home
Menu
Kids Menu
Nutrition
Testimonials
Order Online

Ice Cones Cafe, established in 1880, is the best ice cream joint in town!  With desserts ranging from waffles to ice cream, Ice Cones only uses the purest  ice from Antarctica. With our wide selection of foods, and our expertise  chefs,
you will never leave unhappy.  Only when you walk through our doors  will you taste the best ice cream the world has to offer!

 Contact Information

 Abdu Hijazi

contact_support@icecones.com

(313)962-7906

<audio autoplay loop>
  <source src="ice.mp3" type="audio/mpeg">

Ignore this (Next page Menu)

<link rel="icon" href="IceConesfavicon.ico" type=" image/png">
<link rel="stylesheet" type="text/css" href="index.css">
<title> Menu</title>

 Ice Cones Cafe

Home
Menu
Kids Menu
Nutrition
Testimonials
Order Online

 Menu

 Menu

Picture
Description
Price

The classic ice in a cup. Our Ice Cones come in flavors of lemon lime, blue berry, and cotton candy. This product is our cafe's specialty.
Small/$0.99 Large/$1.99

Another famous classic using ice imported directly from the freshest and purest ice.
With our different flavors of chocolate, vanilla, buttermilk, and pistachio, there are various flavors to try. We also come up with new flavors weekly.
1 scoop/$1.50    2 scoop/$2

 The banana split features a combination of banana, whipped cream, sprinkles, and even a cherry on top. The best part however, is that
warm, melting chocolate syrup.
$2.99

 The classic American favorite of Oreo cookies mixed with milk. A tasty, chunky, cold recipe that your taste buds won't soon forget.
$2.50

 Contact Information

 Abdu Hijazi

contact_support@icecones.com

(313)962-7906

Kids Menu

<title> KidsMenu</title>
<link rel="icon" href="IceConesfavicon.ico" type=" image/png">
<link rel="stylesheet" type="text/css" href="index.css">

 Ice Cones Cafe

Home
Menu
Kids Menu
Nutrition
Testimonials
Order Online

Kids Menu

 Kid's Menu

Picture
Description
Price

 Our chef specially makes these in sizes of 1/3 regular waffles. A great meal for you kid in the morning, or anytime.
$4.59

 These smores are a small, but tasty item for your kids. Includes chocolate syrup, marshmallows, graham crackers, and whipped cream.
$3.99
 with whip/$4.50

 Although you're probably thinking warm at a ice cream place is crazy, we have added a frozen aspect to hot chocolate for your kids. They will love
the whipped cream and added syrup.
$3.50

 A small, warm crepe filled with whatever your child desires. Banana, Nutella, and strawberry are all viable options, along with
syrups and creams on top.
$4.99

Kiddie Activity

 Contact Information

 Abdu Hijazi

contact_support@icecones.com

(313)962-7906

lastly, testimonials

<link rel="icon" href="IceConesfavicon.ico" type=" image/png">
<link rel="stylesheet" type="text/css" href="index.css">
<title> IceCones</title>

 Ice Cones Cafe

Home
Menu
Kids Menu
Nutrition
Testimonials
Order Online

Testimonials

 Below are some testimonials from our CEO and a trusted customer:

 Testimonial~CEO Abdu Hijazi

<video controls>
<source src="Test1.mp4" type="video/mp4">
</video>

 Testimonial~Satisfied Customer Sara Hijazi

<video controls>
<source src="Test2.mp4" type="video/mp4">
</video>

Contact Information

 Abdu Hijazi

contact_support@icecones.com

(313)962-7906


问:
Output Path for Shared T4 Template
How can I specify the output path of a T4 template?

When I add my T4 template using "Add as Link" to my project from $TemplatePath$, it generates the output file in $TemplatePath$, not $ProjectPath$. How can I specify that $ProjectPath is where the generated file is placed?

答: I got around this by having a master template in one location and then templates that imported that one (but did little else) in each project. Of course, that's not the nicest solution.</p>

ContentLicense: CC BY-SA 2.5

Title: Output Path for Shared T4 Template


问:
Having trouble printing the results of my query
```<code>query = c.execute('SELECT * FROM Patients')

resultset = c.fetchall()

if not resultset:
    print("Sorry, the last name you entered does not match any patients "
          "in the hospital.") #if there are no results this is printed
else:
    for result in resultset:
        result = ' '.join(result)
        print("\n\t", result)
</code>```

I saw a suggestion that said to change it to ','.join([None])  but I tried it and it did not work.

答:
Ensure that you have created a cursor object:</p>

```<code>c = sqlite3.connect('databasename.db').cursor()
query = list(c.execute('SELECT * FROM Patients'))
#now, you can check query:

if not query  :
    print("Sorry, the last name you entered does not match any patients "
      "in the hospital.") #if there are no results this is printed
else:
   for val in [' '.join(i) for i in query]:
     print "\n\t{}".format(val)
</code>```

Body:
query = c.execute('SELECT * FROM Patients')

resultset = c.fetchall()

if not resultset:
    print("Sorry, the last name you entered does not match any patients "
          "in the hospital.") #if there are no results this is printed
else:
    for result in resultset:
        result = ' '.join(result)
        print("\n\t", result)

I saw a suggestion that said to change it to ','.join([None])  but I tried it and it did not work.

Body:
Ensure that you have created a cursor object:

c = sqlite3.connect('databasename.db').cursor()
query = list(c.execute('SELECT * FROM Patients'))
#now, you can check query:

if not query  :
    print("Sorry, the last name you entered does not match any patients "
      "in the hospital.") #if there are no results this is printed
else:
   for val in [' '.join(i) for i in query]:
     print "\n\t{}".format(val)


问:
Dropwizard example giving 400 error when creating new resource
I am new to the Dropwizard framework. I am trying to work on creating a new resource similar to person and people resource mentioned in the tutorial here https://github.com/dropwizard/dropwizard/tree/master/dropwizard-example.

I am creating a document class like this -

@Entity
@Table(name = "document")
@NamedQueries({
        @NamedQuery(
                name = "com.example.helloworld.core.Document.findAll",
                query = "SELECT d FROM Document d"
        ),
        @NamedQuery(
                name = "com.example.helloworld.core.Document.findById",
                query = "SELECT d FROM Document d WHERE d.Id = :Id"
        )
})
public class Document {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long Id;

    @Column(name = "ProcessingSetID")
    private String ProcessingSetID;

    @Column(name = "processed")
    private String processed;

    public long getId() {
        return Id;
    }

    public void setId(long id) {
        this.Id = id;
    }

    public String getProcessingSetID() {
        return ProcessingSetID;
    }

    public void setProcessingSetID(String processingSetID) {
        ProcessingSetID = processingSetID;
    }

    public String getProcessed() {
        return processed;
    }

    public void setProcessed(String processed) {
        this.processed = processed;
    }
}
```

<p>My document Dao is like this,</p>

<pre class="lang-java prettyprint-override"><code>public Optional<Document> findById(Long id) {
    return Optional.fromNullable(get(id));
}

public Document create(Document document) {
    return persist(document);
}

public List<Document> findAll() {
    return list(namedQuery("com.example.helloworld.core.Document.findAll"));
}
}
</code>```

I am trying to call the POST method on my document resource,

@Path("/documents")
@Produces(MediaType.APPLICATION_JSON)

public class DocumentsResource {

    private final DocumentDao documentDAO;
    private static final Logger log = LoggerFactory.getLogger(DocumentsResource.class);

    public DocumentsResource(DocumentDao documentDAO) {
        this.documentDAO = documentDAO;
    }

    @POST
    @UnitOfWork
    public Document createDocument(Document document) {
        log.info("inside POST method of document.");
        System.out.println("inside POST method of document.....");
        return documentDAO.create(document);
    }

    @GET
    @UnitOfWork
    public List<Document> listDocuments() {
        return documentDAO.findAll();
    }
}
```

<p>But I am getting a 400 response back from my client request, please find below the client request</p>

<pre class="lang-java prettyprint-override"><code>Client client = Client.create();

WebResource webResource = client.resource("http://localhost:8080/documents");

String input = "{\"processed\":\"new process\",\"ProcessingSetID\":\"new iD\"}";

ClientResponse response =
        webResource.type("application/json").post(ClientResponse.class, input);

if (response.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatus());
}
</code>```

I tried to debug the problem, but the call is not reaching the POST method at the first place. It seems that it is not creating the document object from the JSON string, but i could not see a reason for that. Also when I do an entry directly in my database and make a GET call, perfect JSON string equivalent to object is received.

答: If you are registering the Jersey's CsrfProtectionFilter in your Dropwizard *Application.java within the run(...) method, make sure you're adding the X-Requested-By header to all of your state changing HTTP calls (POST, PUT, etc). The server will return an HTTP 400 Bad Request if that header is not found in the request.

Body:
I am new to the Dropwizard framework. I am trying to work on creating a new resource similar to person and people resource mentioned in the tutorial here https://github.com/dropwizard/dropwizard/tree/master/dropwizard-example.

I am creating a document class like this -

@Entity
@Table(name = "document")
@NamedQueries({
        @NamedQuery(
                name = "com.example.helloworld.core.Document.findAll",
                query = "SELECT d FROM Document d"
        ),
        @NamedQuery(
                name = "com.example.helloworld.core.Document.findById",
                query = "SELECT d FROM Document d WHERE d.Id = :Id"
        )
})
public class Document {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long Id;

    @Column(name = "ProcessingSetID")
    private String ProcessingSetID;

    @Column(name = "processed")
    private String processed;

    public long getId() {
        return Id;
    }

    public void setId(long id) {
        this.Id = id;
    }

    public String getProcessingSetID() {
        return ProcessingSetID;
    }

    public void setProcessingSetID(String processingSetID) {
        ProcessingSetID = processingSetID;
    }

    public String getProcessed() {
        return processed;
    }

    public void setProcessed(String processed) {
        this.processed = processed;
    }
}

My document Dao is like this,

public Optional<Document> findById(Long id) {
    return Optional.fromNullable(get(id));
}

public Document create(Document document) {
    return persist(document);
}

public List<Document> findAll() {
    return list(namedQuery("com.example.helloworld.core.Document.findAll"));
}
}

I am trying to call the POST method on my document resource,

@Path("/documents")
@Produces(MediaType.APPLICATION_JSON)

public class DocumentsResource {

    private final DocumentDao documentDAO;
    private static final Logger log = LoggerFactory.getLogger(DocumentsResource.class);

    public DocumentsResource(DocumentDao documentDAO) {
        this.documentDAO = documentDAO;
    }

    @POST
    @UnitOfWork
    public Document createDocument(Document document) {
        log.info("inside POST method of document.");
        System.out.println("inside POST method of document.....");
        return documentDAO.create(document);
    }

    @GET
    @UnitOfWork
    public List<Document> listDocuments() {
        return documentDAO.findAll();
    }
}

But I am getting a 400 response back from my client request, please find below the client request

Client client = Client.create();

WebResource webResource = client.resource("http://localhost:8080/documents");

String input = "{\"processed\":\"new process\",\"ProcessingSetID\":\"new iD\"}";

ClientResponse response =
        webResource.type("application/json").post(ClientResponse.class, input);

if (response.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatus());
}

I tried to debug the problem, but the call is not reaching the POST method at the first place. It seems that it is not creating the document object from the JSON string, but i could not see a reason for that. Also when I do an entry directly in my database and make a GET call, perfect JSON string equivalent to object is received.


问:
React setState causes a "cannot render object" error
I have a simple statefull component with a form.

```<code>export class example extends React.Component {
  constructor() {
    this.state = {
      issue: {id: '', isValid: false}
    }
    this.onSubmit = this.onSubmit.bind(this)
  }

  onSubmit (e) {
    fetch('/some/api/path').then((newIssue) => {
      newIssue.json().then(convertedIssue => {
        this.setState({issue: convertedIssue})
      })
    })
  }

  render() {
    const issue = this.state.issue
    return (
      <div>
        <form onSubmit={this.onSubmit}>
          ID: {issue.id}
          ...
        </form>
      </div>
     )
   }
</code>```

The issue comes when I get the API response. The response is a simple object that maps the the issue object that initialized the state in the constructor. When I try to call setState({issue: issue}) I get the error: Uncaught (in promise) Error: Objects are not valid as a React child (found: Sun Nov 06 2016 16:00:00 GMT-0800 (PST)). If you meant to render a collection of children, use an array instead.

I can hack around this error by changing the call from setState({issue: newIssue}) to setState({newIssue})

Why is this? What am I doing wrong?

答:
The problem is not that you're assigning an object to the value of this.state.issue, that is valid.

The error message is indicating that somewhere in your component or children you're trying to render the value of this.state.issue. However React doesn't render objects directly.

So if you did something like

```<code>render() {
 return <div>{this.state.issue}</div>
}
</code>```

or if you passed this.state.issue as a prop and then tried to render it in a child component, you would also receive an error.

Before rendering you need to select what part of this.state.issue you'd like to display. This would be valid:

```<code>render() {
  return (
    <span>Issue Id: {this.state.issue.id}</span>
  )
}
</code>```

Body:
I have a simple statefull component with a form.

export class example extends React.Component {
  constructor() {
    this.state = {
      issue: {id: '', isValid: false}
    }
    this.onSubmit = this.onSubmit.bind(this)
  }

  onSubmit (e) {
    fetch('/some/api/path').then((newIssue) => {
      newIssue.json().then(convertedIssue => {
        this.setState({issue: convertedIssue})
      })
    })
  }

  render() {
    const issue = this.state.issue
    return (

        <form onSubmit={this.onSubmit}>
          ID: {issue.id}
          ...
        </form>

     )
   }

The issue comes when I get the API response. The response is a simple object that maps the the issue object that initialized the state in the constructor. When I try to call setState({issue: issue}) I get the error: Uncaught (in promise) Error: Objects are not valid as a React child (found: Sun Nov 06 2016 16:00:00 GMT-0800 (PST)). If you meant to render a collection of children, use an array instead.

I can hack around this error by changing the call from setState({issue: newIssue}) to setState({newIssue})

Why is this? What am I doing wrong?

Body:
The problem is not that you're assigning an object to the value of this.state.issue, that is valid.

The error message is indicating that somewhere in your component or children you're trying to render the value of this.state.issue. However React doesn't render objects directly.

So if you did something like

render() {
 return <div>{this.state.issue}</div>
}

or if you passed this.state.issue as a prop and then tried to render it in a child component, you would also receive an error.

Before rendering you need to select what part of this.state.issue you'd like to display. This would be valid:

render() {
  return (
    <span>Issue Id: {this.state.issue.id}</span>
  )
}


问:
Dynamically create a class name in Javascript
I have some code in PHP file that creates a button and the target of that button is a DIV (findOptionsBox).

The button gets repeated multiple times on the page and so the target of each button should be a unique DIV Id.

```<code><button type="button" id="myBtn" class="btn" data-toggle="collapse" data-
 target="#findOptionsBox">
       ......
</button>

<div id="findOptionsBox" class="search-box collapse">
......
<div>
</code>```

So my question is how to make 'findOptionsBox' a variable that can be supplied to the data-target of each myBtn and the same variable can also be the ID of the corresponding div.

I am looking to end up with something like this:

           ......

```<code><div id="findOptionsBox_1" class="search-box collapse">
......
<div>
</code>```

           ......

```<code><div id="findOptionsBox_2" class="search-box collapse">
......
<div>
</code>```

I need the btnIds and the DivIds to be unique and each btnId to refer to the corresponding DivId.

I am looking to do this in Javascript and am trying something like:

```<code><script type="application/javascript">
    $(function(){
        var count = 0;

            count++;
    });
</script>
</code>```

Thanks.

答:
https://jsfiddle.net/sudarpochong/0hx4mLaw/1/

Create a div to contain options box (#options-container)

Clone #findOptionsBox and change the id

Insert into #options-container

Code:

```<code>var PREFIX_ID = "findOptionsBox_";

$("#myBtn").click(function(e) {

  $("#options-container").empty();
    var totalOptions = $("#numberOfOptions").val();
    for (var i=0; i<totalOptions; i++) {
    var newBox = $("#findOptionsBox").clone();
    newBox.attr("id", PREFIX_ID + i);
    newBox.appendTo("#options-container");
    newBox.show();
  }

  e.preventDefault();
});
</code>```

Body:
I have some code in PHP file that creates a button and the target of that button is a DIV (findOptionsBox).

The button gets repeated multiple times on the page and so the target of each button should be a unique DIV Id.

<button type="button" id="myBtn" class="btn" data-toggle="collapse" data-
 target="#findOptionsBox">
       ......
</button>

......

So my question is how to make 'findOptionsBox' a variable that can be supplied to the data-target of each myBtn and the same variable can also be the ID of the corresponding div.

I am looking to end up with something like this:

           ......

......

           ......

......

I need the btnIds and the DivIds to be unique and each btnId to refer to the corresponding DivId.

I am looking to do this in Javascript and am trying something like:

Thanks.

Body:
https://jsfiddle.net/sudarpochong/0hx4mLaw/1/

Create a div to contain options box (#options-container)

Clone #findOptionsBox and change the id

Insert into #options-container

Code:

var PREFIX_ID = "findOptionsBox_";

$("#myBtn").click(function(e) {

  $("#options-container").empty();
    var totalOptions = $("#numberOfOptions").val();
    for (var i=0; i<totalOptions; i++) {
    var newBox = $("#findOptionsBox").clone();
    newBox.attr("id", PREFIX_ID + i);
    newBox.appendTo("#options-container");
    newBox.show();
  }

  e.preventDefault();
});


答:
You can do by ([0-9]{4})  from

More see in here

Title: Regex to match exact phrase before certain word

Body:
I would like to match any four digits occurring before double space and word "from"  ex.

2356  from

1524  from

1223  from

The expression \d{4}  from extracts digits, double space and the word "from", but ideally I would like to get only those four digits (without the trailing spaces and word "from") and only in cases when they are not part of number with hyphen like this example:

2536  from = 2536

8574  from = 8574

35-6655  from = no match

3652 = no match (number without word "from" after the digits)


问:
Sample n random draw within group with different nrows
How can I draw n rows from a group where each group has a different number of rows?

```<code>df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)
</code>```

I've tried,

```<code>library(dplyr)
outdat <- df %>%
  group_by(color) %>%
  sample_n(nrow(.), replace = TRUE)
outdat
</code>```

but this returns a data.frame where nrow(.) are nrows from df and not the subset.

This SO post is close, but defines a specific number of row draws. I need it to be specific to group within dplyr.

Body:
How can I draw n rows from a group where each group has a different number of rows?

df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)

I've tried,

library(dplyr)
outdat <- df %>%
  group_by(color) %>%
  sample_n(nrow(.), replace = TRUE)
outdat

but this returns a data.frame where nrow(.) are nrows from df and not the subset.

This SO post is close, but defines a specific number of row draws. I need it to be specific to group within dplyr.

Body:
A workaround using the purrr pakcage. It seems like the sample_n function cannot take n() as the size argument, probably because that argument does not take vectorized input. However, if we split the data frame by color as group, we can apply the sample_n with nrow() for each group.

# Set seed for reproducibility
set.seed(123)

# Create example data frame
df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)

# Load packages
library(dplyr)
library(purrr)

outdat <- df %>%
  # Split the data frame by color
  split(.$color) %>%
  # Apply the sample_n function to all data frames
  map_dfr(~sample_n(., size = nrow(.), replace = TRUE))

outdat
#             X1          X2  color
# 1   1.71506499 -1.12310858   blue
# 2   0.07050839  2.16895597   blue
# 3   0.46091621 -0.40288484   blue
# 4   0.07050839  2.16895597   blue
# 5   0.07050839  2.16895597   blue
# 6   1.71506499 -1.12310858   blue
# 7  -1.26506123 -0.46665535   blue
# 8   1.55870831 -1.26539635   blue
# 9   0.12928774  1.20796200   blue
# 10  1.55870831 -1.26539635   blue
# 11  0.55391765 -0.28477301   pink
# 12 -0.29507148 -2.30916888   pink
# 13 -0.30596266  0.18130348   pink
# 14 -0.06191171 -1.22071771   pink
# 15  0.55391765 -0.28477301   pink
# 16  0.55391765 -0.28477301   pink
# 17  0.87813349 -0.70920076   pink
# 18  0.68864025  1.02557137   pink
# 19 -0.30596266  0.18130348   pink
# 20  0.68864025  1.02557137   pink
# 21  0.70135590  0.12385424    red
# 22  0.11068272  1.36860228    red
# 23 -1.96661716  0.58461375    red
# 24  0.40077145 -0.04287046    red
# 25  1.78691314  1.51647060    red
# 26 -0.55584113 -0.22577099    red
# 27  0.40077145 -0.04287046    red
# 28  1.78691314  1.51647060    red
# 29 -0.47279141  0.21594157    red
# 30 -0.47279141  0.21594157    red
# 31 -1.02600445 -0.33320738 yellow
# 32 -0.72889123 -1.01857538 yellow
# 33  1.25381492  2.05008469 yellow
# 34  0.83778704  0.44820978 yellow
# 35  1.25381492  2.05008469 yellow
# 36 -0.62503927 -1.07179123 yellow
# 37 -0.62503927 -1.07179123 yellow
# 38  0.83778704  0.44820978 yellow
# 39 -0.21797491 -0.50232345 yellow
# 40 -1.68669331  0.30352864 yellow


问:
Xcode Crash on Swift 4 Conversion
I have a project that I am working on in Xcode 9.1 that is currently a Swift 3 project. I get the warning from Xcode that prompts me to convert to Swift 4, but upon clicking it: Xcode crashes. Xcode also crashes when I go through Edit > Convert > To Modern Swift Syntax. I have tried restarting Xcode and my computer to no avail.

This issue only occurs in this project as I am able to convert other projects with no problems.

I have tried converting the Swift Language Version attribute in build settings to Swift 4.0, but I still get the warning.

The real kicker is that Xcode will crash but then not display the normal response to a crash (option to report to Apple, display the crash log, etc.)

What can I try to fix this? The project will still build, run, & archive but the warning is bothering my OCD.

答:
If you are using XCode 9.1 and your project contains Swift Playground, try removing it.
They have fixed this bug in XCode 9.2.</p>

Title: Xcode Crash on Swift 4 Conversion


问:
urllib3 overriding host IP address
I am trying to override the IP address for the destination host on the fly using urllib3, while I am passing client certificates. Here is my code:

```<code>import urllib3
conn = urllib3.connection_from_url('https://MYHOST', ca_certs='ca_crt.pem', key_file='pr.pem', cert_file='crt.pem', cert_reqs='REQUIRED')
response = conn.request('GET', 'https://MYHOST/OBJ', headers={"HOST": "MYHOST"})
print(response.data)
</code>```

I was thinking to use transport adapters, but I am not quite sure how to do it without using sessions.

Any thoughts or help?

答:
I guess we can follow the solutions presented here: Python 'requests' library - define specific DNS?

Hence a nasty way to do this is to override the hostname to the IP address we want by adding:

```<code>from urllib3.util import connection
import urllib3

hostname = "MYHOST"
host_ip = "10.10.10.10"
_orig_create_connection = connection.create_connection

def patched_create_connection(address, *args, **kwargs):
    overrides = {
        hostname: host_ip
    }
    host, port = address
    if host in overrides:
        return _orig_create_connection((overrides[host], port), *args, **kwargs)
    else:
        return _orig_create_connection((host, port), *args, **kwargs)

connection.create_connection = patched_create_connection

conn = urllib3.connection_from_url('https://MYHOST', ca_certs='ca_crt.pem', key_file='pr.pem', cert_file='crt.pem', cert_reqs='REQUIRED')
response = conn.request('GET', 'https://MYHOST/OBJ', headers={"HOST": "MYHOST"})
print(response.data)
</code>```

But, again based on the posted link, the better way to implement it is to have a proper adapter to override the IP address.

Title: urllib3 overriding host IP address

Body:
I am trying to override the IP address for the destination host on the fly using urllib3, while I am passing client certificates. Here is my code:

import urllib3
conn = urllib3.connection_from_url('https://MYHOST', ca_certs='ca_crt.pem', key_file='pr.pem', cert_file='crt.pem', cert_reqs='REQUIRED')
response = conn.request('GET', 'https://MYHOST/OBJ', headers={"HOST": "MYHOST"})
print(response.data)

I was thinking to use transport adapters, but I am not quite sure how to do it without using sessions.

Any thoughts or help?

Body:
I guess we can follow the solutions presented here: Python 'requests' library - define specific DNS?

Hence a nasty way to do this is to override the hostname to the IP address we want by adding:

from urllib3.util import connection
import urllib3

hostname = "MYHOST"
host_ip = "10.10.10.10"
_orig_create_connection = connection.create_connection

def patched_create_connection(address, *args, **kwargs):
    overrides = {
        hostname: host_ip
    }
    host, port = address
    if host in overrides:
        return _orig_create_connection((overrides[host], port), *args, **kwargs)
    else:
        return _orig_create_connection((host, port), *args, **kwargs)

connection.create_connection = patched_create_connection

conn = urllib3.connection_from_url('https://MYHOST', ca_certs='ca_crt.pem', key_file='pr.pem', cert_file='crt.pem', cert_reqs='REQUIRED')
response = conn.request('GET', 'https://MYHOST/OBJ', headers={"HOST": "MYHOST"})
print(response.data)

But, again based on the posted link, the better way to implement it is to have a proper adapter to override the IP address.


问:
Split one column to two columns depending one the content in pandas dataframe
I have a pandas DataFrame like this:

df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9])

```<code>    0
0   A
1   1
2   2
3   3
4   B
5   4
6   5
7   C
8   6
9   7
10  8
11  9
</code>```

It's mix of strings and numbers. I want to split this DF into tow columns like this:

```<code>   name value
0   A   1
1   A   2
2   A   3
3   B   4
4   B   5
5   C   6
6   C   7
7   C   8
8   C   9
</code>```

what's an efficient way to do this?

答:
IIUC

```<code>df['New']=df[df.your.str.isalpha().fillna(False)]
df.ffill().loc[df.your!=df.New,:]
Out[217]:
   your New
1     1   A
2     2   A
3     3   A
5     4   B
6     5   B
8     6   C
9     7   C
10    8   C
11    9   C
</code>```

Data input

```<code>df = pd.DataFrame({'your':['A',1,2,3,'B',4,5,'C',6,7,8,9]})
</code>```

Body:
I have a pandas DataFrame like this:

df = pd.DataFrame(['A',1,2,3,'B',4,5,'C',6,7,8,9])

    0
0   A
1   1
2   2
3   3
4   B
5   4
6   5
7   C
8   6
9   7
10  8
11  9

It's mix of strings and numbers. I want to split this DF into tow columns like this:

   name value
0   A   1
1   A   2
2   A   3
3   B   4
4   B   5
5   C   6
6   C   7
7   C   8
8   C   9

what's an efficient way to do this?

Body:
IIUC

df['New']=df[df.your.str.isalpha().fillna(False)]
df.ffill().loc[df.your!=df.New,:]
Out[217]:
   your New
1     1   A
2     2   A
3     3   A
5     4   B
6     5   B
8     6   C
9     7   C
10    8   C
11    9   C

Data input

df = pd.DataFrame({'your':['A',1,2,3,'B',4,5,'C',6,7,8,9]})


问:
Basic MVC with linked tables
I am new to cakephp.
I am working on an application where authors can create new and translate existing articles to their language.
I have three tables: articles, article_translations and authors.

When an author creates a new article, a record in article and article_translations is created.
When an author translate an existing article, a record only in article_translations is created.

```<code>articles
------
id
authors_id
preview_image
detail_image
...

article_translations
------
id
article_id
authors_id
language
title
subtitle
...

authors
------
id
user_name
email
...
</code>```

I baked models, controllers and templates, and they are working fine.

articles Model:

```<code>class RecipesTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('articles');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Users', [
            'foreignKey' => 'authors_id'
        ]);

        $this->hasMany('ArticleTranslations', [
            'foreignKey' => 'article_id'
        ]);

    }
// Some validation methods
}
</code>```

article_translations model

```<code>class ArticleTranslationsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('article_translations');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Articles', [
            'foreignKey' => 'author_id',
            'joinType' => 'INNER'
        ]);
    }
// Some validation methods

}
</code>```

authors model

```<code>class UsersTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('authors');
        $this->setDisplayField('user_name');
        $this->setPrimaryKey('id');
    }
// Some validation methods
}
</code>```

Articles Controller

```<code>class ArticlesController extends AppController
{
    public function index()
    {
        $this->paginate = [
            'contain' => ['Authors']
        ];
        $articles = $this->paginate($this->Articles);

        $this->set(compact('articles'));
        $this->set('_serialize', ['articles']);
    }
    // More methods
}
</code>```

ArticleTranslations Controller

```<code>class ArticleTranslationsController extends AppController
{
    public function index()
    {
        $this->paginate = [
            'contain' => ['Articles']
        ];
        $articleTranslations = $this->paginate($this->ArticleTranslations);

        $this->set(compact('articleTranslations'));
        $this->set('_serialize', ['articleTranslations']);
    }
    // More methods
}
</code>```

Authors Controller

```<code>class AuthorsController extends AppController
{
    public function index()
    {
        $authors = $this->paginate($this->Authors);

        $this->set(compact('authors'));
        $this->set('_serialize', ['authors']);
    }
    // More methods
}
</code>```

The Articles template (=index function) renders the following table:
    id    Author       preview_image
    --------------------------------
    1
    2
    ...........

What I want is a list of all article translations for all articles, like this:

```<code><preview_image of article one>

id    Author       title             language
---------------------------------------------
1     <user_name>  <article_title>    en
1     <user_name>  <article_title>    fr

<preview_image of article two>

id    Author       title             language
---------------------------------------------
2     <user_name>  <article_title>    it
2     <user_name>  <article_title>    de

.
.
.
</code>```

But how do I load data from article_translations in the Articles Controller?

答:
In Articles Controller, just extend the containment to include the data you want.</p>

```<code>'contain' => ['Authors', 'ArticleTranslations']
</code>```

Title: Basic MVC with linked tables

Body:
I am new to cakephp.
I am working on an application where authors can create new and translate existing articles to their language.
I have three tables: articles, article_translations and authors.

When an author creates a new article, a record in article and article_translations is created.
When an author translate an existing article, a record only in article_translations is created.

articles
------
id
authors_id
preview_image
detail_image
...

article_translations
------
id
article_id
authors_id
language
title
subtitle
...

authors
------
id
user_name
email
...

I baked models, controllers and templates, and they are working fine.

articles Model:

class RecipesTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('articles');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Users', [
            'foreignKey' => 'authors_id'
        ]);

        $this->hasMany('ArticleTranslations', [
            'foreignKey' => 'article_id'
        ]);

    }
// Some validation methods
}

article_translations model

class ArticleTranslationsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('article_translations');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Articles', [
            'foreignKey' => 'author_id',
            'joinType' => 'INNER'
        ]);
    }
// Some validation methods

}

authors model

class UsersTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('authors');
        $this->setDisplayField('user_name');
        $this->setPrimaryKey('id');
    }
// Some validation methods
}

Articles Controller

class ArticlesController extends AppController
{
    public function index()
    {
        $this->paginate = [
            'contain' => ['Authors']
        ];
        $articles = $this->paginate($this->Articles);

        $this->set(compact('articles'));
        $this->set('_serialize', ['articles']);
    }
    // More methods
}

ArticleTranslations Controller

class ArticleTranslationsController extends AppController
{
    public function index()
    {
        $this->paginate = [
            'contain' => ['Articles']
        ];
        $articleTranslations = $this->paginate($this->ArticleTranslations);

        $this->set(compact('articleTranslations'));
        $this->set('_serialize', ['articleTranslations']);
    }
    // More methods
}

Authors Controller

class AuthorsController extends AppController
{
    public function index()
    {
        $authors = $this->paginate($this->Authors);

        $this->set(compact('authors'));
        $this->set('_serialize', ['authors']);
    }
    // More methods
}

The Articles template (=index function) renders the following table:
    id    Author       preview_image
    --------------------------------
    1
    2
    ...........

What I want is a list of all article translations for all articles, like this:

<preview_image of article one>

id    Author       title             language
---------------------------------------------
1     <user_name>  <article_title>    en
1     <user_name>  <article_title>    fr

<preview_image of article two>

id    Author       title             language
---------------------------------------------
2     <user_name>  <article_title>    it
2     <user_name>  <article_title>    de

.
.
.

But how do I load data from article_translations in the Articles Controller?

Body:
In Articles Controller, just extend the containment to include the data you want.

'contain' => ['Authors', 'ArticleTranslations']


问:
Div is null even though it has a child
In the console I am getting the error that div cannot be appended to body because it has a value of null. Why is this? It has content.</p>

```<code>var div = document.createElement("div");
document.getElementsByTagName('div').innerHTML = '<img alt="pickle"
src="images/pickle">';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
document.body.appendChild(div);
</code>```

答:
getElementsByTagName() method returns HTMLCollection (i.e. an array of HTMLElements [ div, div, ... ]) even if it found only 1 element

```<code>var divarray = document.getElementsByTagName("div");
if (divarray.length >= 1) var firstdiv = divarray[0];
</code>```

Title: Div is null even though it has a child

Body:
In the console I am getting the error that div cannot be appended to body because it has a value of null. Why is this? It has content.

var div = document.createElement("div");
document.getElementsByTagName('div').innerHTML = '';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
document.body.appendChild(div);

Body:
getElementsByTagName() method returns HTMLCollection (i.e. an array of HTMLElements [ div, div, ... ]) even if it found only 1 element

var divarray = document.getElementsByTagName("div");
if (divarray.length >= 1) var firstdiv = divarray[0];


问:
Cannot set Azure SQL Database Long-term backup retention
I'm trying to re-configure long term backup retention for my Azure SQL Database from a previously deleted recovery services vault (via Powershell) to a new recovery services vault

Now when I try to configure it gives me an error saying

TemplateBladeVirtualPart
  SQLAZUREEXTENSION

Here is the script I used to removed the old recovery services vault (if it matters?)

```<code>$vault = Get-AzureRmRecoveryServicesVault -Name "is-vault-prod"
Set-AzureRmRecoveryServicesVaultContext -Vault $vault
$container = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name
$item = Get-AzureRmRecoveryServicesBackupItem -Container $container -WorkloadType AzureSQLDatabase
$availableBackups = Get-AzureRmRecoveryServicesBackupRecoveryPoint -Item $item
$containers = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name
ForEach ($container in $containers)
{
    $items = Get-AzureRmRecoveryServicesBackupItem -container $container -WorkloadType AzureSQLDatabase
    ForEach ($item in $items)
    {
        Disable-AzureRmRecoveryServicesBackupProtection -item $item -RemoveRecoveryPoints -ea SilentlyContinue
    }
    Unregister-AzureRmRecoveryServicesBackupContainer -Container $container
}
Remove-AzureRmRecoveryServicesVault -Vault $vault
</code>```

答:
Unfortunately, you just cannot choose another Recovery service vault once you had already used one.

I did a test in my lab and tried to disable the long backup retention but still failed, and found that:

This screenshot means that once you configured a recovery service vault for a SQL Server, it will be locked , you cannot use another vault.

I also found this in a FAQ:

Can I register my server to store backups to more than one vault?

No, you can currently store backups to only one vault at a time.

I understand why you want to use another vault.

However, We can just use this recovery service vault currently.If it was deleted, we cannot use long-term backup retention. It seems like a bad point of design. I will report this issue and I believe this feature would be better in future.

You can also post your idea in this Feedback Forum.

Hope this helps!

Body:
I'm trying to re-configure long term backup retention for my Azure SQL Database from a previously deleted recovery services vault (via Powershell) to a new recovery services vault

Now when I try to configure it gives me an error saying

TemplateBladeVirtualPart
  SQLAZUREEXTENSION

Here is the script I used to removed the old recovery services vault (if it matters?)

$vault = Get-AzureRmRecoveryServicesVault -Name "is-vault-prod"
Set-AzureRmRecoveryServicesVaultContext -Vault $vault
$container = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name
$item = Get-AzureRmRecoveryServicesBackupItem -Container $container -WorkloadType AzureSQLDatabase
$availableBackups = Get-AzureRmRecoveryServicesBackupRecoveryPoint -Item $item
$containers = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name
ForEach ($container in $containers)
{
    $items = Get-AzureRmRecoveryServicesBackupItem -container $container -WorkloadType AzureSQLDatabase
    ForEach ($item in $items)
    {
        Disable-AzureRmRecoveryServicesBackupProtection -item $item -RemoveRecoveryPoints -ea SilentlyContinue
    }
    Unregister-AzureRmRecoveryServicesBackupContainer -Container $container
}
Remove-AzureRmRecoveryServicesVault -Vault $vault


问:
How do I code an event that calls a method
OK,

I have 5 methods

Move(), TurnRight(), TurnLeft(), Accelerate(), Decelerate()

I have 5 buttons on my windows form called:

Move, Turn Right, Turn Left, Accelerate, Decelerate

How do take values entered from texboxes and store them, so that when a user clicks one of those buttons it calls the method to perform calculations, and then display the information.

I just don't know how or what to code inside the event that I activated from the form.
Can anyone show me a sample of how they would do it?

Here is my move method

public void move()
        {
            double radians = direction * Math.PI / 180;

```<code>        //change the x location by the x vector of the speed
        X_Coordinate += (int)(speed * Math.Cos(radians));

        //change the y location by the y vectior of the speed
        Y_Coordinate -= (int)(speed * Math.Sin(radians));

    }
</code>```

I created a button on my form and named it btnMove

What should I code inside the event for my move button to call the move method and the display that for an outcome?

答:
For each buttons click event (Double click on button in designer to open code for click event)
call your respective method.

However its not clear if your Move()...etc methods take Values.

You can try this

```<code>public void btnMove_Click(object sender, EventArgs e)
{
     Move();
}

public void Move()
{
     string thetext = Convert.ToInt32(this.textbox1.Text);
     //Perform Calculations
}
</code>```

similarly for other buttons

Body:
OK,

I have 5 methods

Move(), TurnRight(), TurnLeft(), Accelerate(), Decelerate()

I have 5 buttons on my windows form called:

Move, Turn Right, Turn Left, Accelerate, Decelerate

How do take values entered from texboxes and store them, so that when a user clicks one of those buttons it calls the method to perform calculations, and then display the information.

I just don't know how or what to code inside the event that I activated from the form.
Can anyone show me a sample of how they would do it?

Here is my move method

public void move()
        {
            double radians = direction * Math.PI / 180;

        //change the x location by the x vector of the speed
        X_Coordinate += (int)(speed * Math.Cos(radians));

        //change the y location by the y vectior of the speed
        Y_Coordinate -= (int)(speed * Math.Sin(radians));

    }

I created a button on my form and named it btnMove

What should I code inside the event for my move button to call the move method and the display that for an outcome?

Body:
For each buttons click event (Double click on button in designer to open code for click event)
call your respective method.

However its not clear if your Move()...etc methods take Values.

You can try this

public void btnMove_Click(object sender, EventArgs e)
{
     Move();
}

public void Move()
{
     string thetext = Convert.ToInt32(this.textbox1.Text);
     //Perform Calculations
}

similarly for other buttons


问:
Coin flipping - returning random outcome
forgive me if this was already posted :) I have had a problem stuck in my head all day which I have been trying to think of an efficient solution for. Basically the problem is this: Imagine you have to flip a coin 3 billion times and would like a function that returns the amount of heads after all these flips. One possible solution would be to obviously make a for loop iterating 3 billion times recording how many heads and tails and returning the heads - this is obviously an incredibly inefficient solution. I thought of binomial probability but could not see where this could come in to help solve this problem (i'm probably missing something really obvious).

For example say I input in the function NumberOfHeads(flips) most the time (statistically) it will likely return some number around flips / 2. However say flips = 3 billion there should still be a chance that (although incredibly slim to never) it may return 1000 heads or something. Hope I explained whats been troubling me well enough :) thanks for any reponses.

答:
You could use scipy.stats.binom here.  The function below returns the number of heads from a randomly sampled binomial distribution with fair coin flips at each (bernoulli) trial.

```<code>import scipy.stats as scs
def num_heads(num_flips):
    flips = scs.binom(n=num_flips, p=0.5)
    return np.asscalar(flips.rvs(1))

num_heads(3000000000)
# 1499985766
</code>```

.rvs() here stands for random variate.

Without looking through the source, I'm going to guess random number generation is using the analytic binomial CDF p=CDF(x), taking the inverse CDF, then choosing p from a ~U(0,1) distribution.  You can read more about that method in Downey - ThinkStats - section 5.6.  Disclosure: I might be totally wrong, as I often am.

Body:
You could use scipy.stats.binom here.  The function below returns the number of heads from a randomly sampled binomial distribution with fair coin flips at each (bernoulli) trial.

import scipy.stats as scs
def num_heads(num_flips):
    flips = scs.binom(n=num_flips, p=0.5)
    return np.asscalar(flips.rvs(1))

num_heads(3000000000)
# 1499985766

.rvs() here stands for random variate.

Without looking through the source, I'm going to guess random number generation is using the analytic binomial CDF p=CDF(x), taking the inverse CDF, then choosing p from a ~U(0,1) distribution.  You can read more about that method in Downey - ThinkStats - section 5.6.  Disclosure: I might be totally wrong, as I often am.


问:
React-native-maps Blank page Only google logo
I've been trying to install google maps for react-native for a week an still no success. I've searched and tried the solutions in the react-native-maps github issue but still I get a blank page.

What I do:

```<code>react-native init myapp
npm install
yarn add react-native-maps
react-native link react-native-maps
</code>```

In Google Console APIs -> Create new Project -> Enable Google Maps Android API, Google Maps JavaScript API and Places API -> Create credentials

In AndroidManifest.xml

```<code>    <application>
....
       <meta-data
          android:name="com.google.android.geo.API_KEY"
          android:value="XXX"/>
    </application>
</code>```

package.json

```<code>    {
    "name": "maps",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0",
        "react-native": "0.50.4",
        "react-native-maps": "^0.18.3"
    },
    "devDependencies": {
        "babel-jest": "21.2.0",
        "babel-preset-react-native": "4.0.0",
        "jest": "21.2.1",
        "react-test-renderer": "16.0.0"
    },
    "jest": {
        "preset": "react-native"
    }
}
</code>```

App.js

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import MapView from 'react-native-maps'

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
      <MapView
        style={styles.map}
        region={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121,
        }}
      >
      </MapView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});
</code>```

Edit:
Because some people asked me for stack trace: Sample 1

答:
Can you provide some stack traces so that we can have a better insight on your problem? Your problem description sounds like your phone is not connected to the internet and this is why map is not rendered.

Regardless, here's some tips to get react-native-maps running based on my past experiences.

First and foremost, always configure your Android app according to the official documentation here.

Make sure a Google Maps API key is generated through the console.

Check whether your react-native-maps is compatible with your react-native version.

Check your android build-tools version.

If you are using the android emulator from Genymotion (older version), make sure you include Google Play Services, otherwise Map will not work.

Active internet connection. Make sure your phone or emulator is connected for the Map to load (iOS is good without internet access).

Always inject a latlong object to the initialRegion prop so that the map knows where to focus on.

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to install google maps for react-native for a week an still no success. I've searched and tried the solutions in the react-native-maps github issue but still I get a blank page.

What I do:

react-native init myapp
npm install
yarn add react-native-maps
react-native link react-native-maps

In Google Console APIs -> Create new Project -> Enable Google Maps Android API, Google Maps JavaScript API and Places API -> Create credentials

In AndroidManifest.xml

    <application>
....
       <meta-data
          android:name="com.google.android.geo.API_KEY"
          android:value="XXX"/>
    </application>

package.json

    {
    "name": "maps",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0",
        "react-native": "0.50.4",
        "react-native-maps": "^0.18.3"
    },
    "devDependencies": {
        "babel-jest": "21.2.0",
        "babel-preset-react-native": "4.0.0",
        "jest": "21.2.1",
        "react-test-renderer": "16.0.0"
    },
    "jest": {
        "preset": "react-native"
    }
}

App.js

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import MapView from 'react-native-maps'

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
      <MapView
        style={styles.map}
        region={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121,
        }}
      >
      </MapView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

Edit:
Because some people asked me for stack trace: Sample 1


问:
Add a css class using to "this" item in a forEach within EJS/node.js
I've been trying this for hours but I am stumped.

I have a kind of "shopping list" node.js app where you can tick off items as bought. I want the bought items to be styled green or smth. It is passing a mongoose obj to the client side along a route.

Server side:

```<code>router.get("/:id", function(req, res){
   //find the list with provided ID
    List.findById(req.params.id).populate("listItems").exec(function(err, foundList){
        if(err){
            console.log(err);
        } else {
            //render show template with that list
            res.render("lists/show", {list: foundList});
</code>```

The foundList obj basically has a structure of (not valid code, just so u can get an idea):

```<code>List {
   name: String,
   listItems: [{
        text: String,
        bought: Boolean
     }]
</code>```

On the client side I am using a forEach in ejs to loop through the listItems and display a html element for each item:

```<code><% list.listItems.forEach(function(listItem){ %>
    <div class="card">
       <div class="card list">
          ..listItem name here
       </div>
    </div>

<% }) %>
</code>```

I want to basically make it so that when an element is checked off and listItem.bought == true, the card list element is green, and when lisItem.bought == false, it's just white.

I've got it working with following code, however if one occurrence of the forEach is bought = true, all .card elements turn green. I want it so that only the element in question is effected.

```<code><% list.listItems.forEach(function(listItem){ %>

            <% if(listItem.bought === true){ %>
                <script>
                    $(document).ready(function(){
                       (".card").css("background-color","green");
                    });
                </script>
             <% } else { %>
                <script>
                    $(document).ready(function(){
                        (".card").css("background-color","white");
                    });
                </script>
              <% } %>
       <div class="card">
        <div class="card list">
            ....
</code>```

Question: How do I target 1 occurrence of a forEach from server side data in ejs, and add a class/style to it. E.g. if there is 2 items on the list, 1 is bought and one not, one should be green and one white. Currently they both go green.

Thanks!

答:
I don't think you need jQuery for this. You can just add the background color like this:

```<code><% list.listItems.forEach(function (listItem) { %>
    <div class="card" style="background-color: <%= listItem.bought ? 'green' : 'white' %>">
        <div class="card list">
            ...
        </div>
    </div>
<% }); %>
</code>```

If you want to use jQuery you probably need do add ids to the cards and use them to change the backgrounds.

Body:
I've been trying this for hours but I am stumped.

I have a kind of "shopping list" node.js app where you can tick off items as bought. I want the bought items to be styled green or smth. It is passing a mongoose obj to the client side along a route.

Server side:

router.get("/:id", function(req, res){
   //find the list with provided ID
    List.findById(req.params.id).populate("listItems").exec(function(err, foundList){
        if(err){
            console.log(err);
        } else {
            //render show template with that list
            res.render("lists/show", {list: foundList});

The foundList obj basically has a structure of (not valid code, just so u can get an idea):

List {
   name: String,
   listItems: [{
        text: String,
        bought: Boolean
     }]

On the client side I am using a forEach in ejs to loop through the listItems and display a html element for each item:

<% list.listItems.forEach(function(listItem){ %>

          ..listItem name here

<% }) %>

I want to basically make it so that when an element is checked off and listItem.bought == true, the card list element is green, and when lisItem.bought == false, it's just white.

I've got it working with following code, however if one occurrence of the forEach is bought = true, all .card elements turn green. I want it so that only the element in question is effected.

<% list.listItems.forEach(function(listItem){ %>

            <% if(listItem.bought === true){ %>

             <% } else { %>

              <% } %>

            ....

Question: How do I target 1 occurrence of a forEach from server side data in ejs, and add a class/style to it. E.g. if there is 2 items on the list, 1 is bought and one not, one should be green and one white. Currently they both go green.

Thanks!

Body:
I don't think you need jQuery for this. You can just add the background color like this:

<% list.listItems.forEach(function (listItem) { %>
    <div class="card" style="background-color: <%= listItem.bought ? 'green' : 'white' %>">
        <div class="card list">
            ...
        </div>
    </div>
<% }); %>

If you want to use jQuery you probably need do add ids to the cards and use them to change the backgrounds.


问:
Jekyll multiple pages using the same template
I'm aware you can use _layouts and in your pages do something like

```<code>---
layout: some_layout
title: Home
---
</code>```

So say I have 20 pages. All using the same template but slightly different content and stuff inside.

Instead of creating 20 different pages.html files with different names and different permalinks.

Is there a way to create 1 page.html and based on the permalink change what's inside the {{ content }}?

答:
You could organize the 20 pages under a collection and assign defaults on the collection.
For example, say your collection is labelled docs, then all those 20 pages need to be placed inside a directory named _docs, at the root of your source directory. Following that configure your collection to use the layout some_layout for its documents.

```<code># _config.yml

# enable rendering on your collection(s)
collections:
  docs:
    output: true
  another_collection:
    output: true

# set defaults on your collection. (note the indentation..)
defaults:
  -
    scope:
      type: docs
      path: _docs
    values:
      layout: some_layout # The layout for this collections' files
  -
    scope:
      type: another_collection
      [...]
</code>```

Body:
I'm aware you can use _layouts and in your pages do something like

---
layout: some_layout
title: Home
---

So say I have 20 pages. All using the same template but slightly different content and stuff inside.

Instead of creating 20 different pages.html files with different names and different permalinks.

Is there a way to create 1 page.html and based on the permalink change what's inside the {{ content }}?

Body:
You could organize the 20 pages under a collection and assign defaults on the collection.
For example, say your collection is labelled docs, then all those 20 pages need to be placed inside a directory named _docs, at the root of your source directory. Following that configure your collection to use the layout some_layout for its documents.

# _config.yml

# enable rendering on your collection(s)
collections:
  docs:
    output: true
  another_collection:
    output: true

# set defaults on your collection. (note the indentation..)
defaults:
  -
    scope:
      type: docs
      path: _docs
    values:
      layout: some_layout # The layout for this collections' files
  -
    scope:
      type: another_collection
      [...]


问:
Excel - Search for string in list
So let's say we have a list of sentences in the cells of column A that may or may not contain names.

```<code>A1: "The sea was blue"
A2: "together with Mary"
A3: "onward and upward" and so on...
</code>```

I want to be able to check if a certain name exist within the entire list with True / False. For example, if I checked Mary it would return True. Joe would return False.

I've tried a few things, but they only seem to work if the name is the only thing in the cell. I want it to be able to search sentences in the list of cells, I'm just not sure how to proceed.

Much appreciated!

答:
you cant using it :

```<code>=IF(ISNUMBER(FIND("Mary",A1)),"true","false") //you get a string value
</code>```

or using it :

```<code>=if(iserror(find("Mary", lower(A1),1)),0,1) //you get a boolean value
</code>```

Title: Excel - Search for string in list

Body:
So let's say we have a list of sentences in the cells of column A that may or may not contain names.

A1: "The sea was blue"
A2: "together with Mary"
A3: "onward and upward" and so on...

I want to be able to check if a certain name exist within the entire list with True / False. For example, if I checked Mary it would return True. Joe would return False.

I've tried a few things, but they only seem to work if the name is the only thing in the cell. I want it to be able to search sentences in the list of cells, I'm just not sure how to proceed.

Much appreciated!

Body:
you cant using it :

=IF(ISNUMBER(FIND("Mary",A1)),"true","false") //you get a string value

or using it :

=if(iserror(find("Mary", lower(A1),1)),0,1) //you get a boolean value


问:
Error accessing Spark thrift Server
Spark version: 1.6.3

I running Spark thrift server as proxy. But it not running as long as I expected. It always stop when get high load.

This is Error when I access.

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 500 Server Error</title>

HTTP ERROR 500

Problem accessing /jobs/. Reason:
```    Server Error```

Caused by:
```java.lang.OutOfMemoryError: Java heap space
 at java.util.Arrays.copyOfRange(Arrays.java:3664)
 at java.lang.String.<init>(String.java:207)
 at java.lang.StringBuilder.toString(StringBuilder.java:407)
 at scala.collection.mutable.StringBuilder.toString(StringBuilder.scala:427)
 at scala.xml.Node.buildString(Node.scala:161)
 at scala.xml.Node.toString(Node.scala:166)
 at org.apache.spark.ui.JettyUtils$$anonfun$htmlResponderToServlet$1.apply(JettyUtils.scala:55)
 at org.apache.spark.ui.JettyUtils$$anonfun$htmlResponderToServlet$1.apply(JettyUtils.scala:55)
 at org.apache.spark.ui.JettyUtils$$anon$1.doGet(JettyUtils.scala:83)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
 at org.spark-project.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
 at org.spark-project.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1507)
 at org.apache.hadoop.yarn.server.webproxy.amfilter.AmIpFilter.doFilter(AmIpFilter.java:179)
 at org.spark-project.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1478)
 at org.spark-project.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
 at org.spark-project.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
 at org.spark-project.jetty.servlet.ServletHandler.doScope(ServletHandler.java:427)
 at org.spark-project.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
 at org.spark-project.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
 at org.spark-project.jetty.server.handler.GzipHandler.handle(GzipHandler.java:301)
 at org.spark-project.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
 at org.spark-project.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
 at org.spark-project.jetty.server.Server.handle(Server.java:370)
 at org.spark-project.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
 at org.spark-project.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:973)
 at org.spark-project.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1035)
 at org.spark-project.jetty.http.HttpParser.parseNext(HttpParser.java:641)
 at org.spark-project.jetty.http.HttpParser.parseAvailable(HttpParser.java:231)
 at org.spark-project.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
 at org.spark-project.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
 at org.spark-project.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)
```

Powered by Jetty://

```

I see error is java.lang.OutOfMemoryError: Java heap space

But I don't know what memory I need increase:

Memory of server running SPARK

Memory of executor configure with SPARK

other Memory configure...

Update: my SPARK configure

my SPARK configure

答:
The thrift server runs in it's own memory space. You can specify that via the executor memory property.

For example

```<code>./sbin/start-thriftserver.sh --executor-memory 512m
</code>```

I think the default is 1g, as the spark-env.sh has.

Title: Error accessing Spark thrift Server

Body:
Spark version: 1.6.3

I running Spark thrift server as proxy. But it not running as long as I expected. It always stop when get high load.

This is Error when I access.

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 500 Server Error</title>

HTTP ERROR 500

Problem accessing /jobs/. Reason:

    Server Error

Caused by:

java.lang.OutOfMemoryError: Java heap space
 at java.util.Arrays.copyOfRange(Arrays.java:3664)
 at java.lang.String.<init>(String.java:207)
 at java.lang.StringBuilder.toString(StringBuilder.java:407)
 at scala.collection.mutable.StringBuilder.toString(StringBuilder.scala:427)
 at scala.xml.Node.buildString(Node.scala:161)
 at scala.xml.Node.toString(Node.scala:166)
 at org.apache.spark.ui.JettyUtils$$anonfun$htmlResponderToServlet$1.apply(JettyUtils.scala:55)
 at org.apache.spark.ui.JettyUtils$$anonfun$htmlResponderToServlet$1.apply(JettyUtils.scala:55)
 at org.apache.spark.ui.JettyUtils$$anon$1.doGet(JettyUtils.scala:83)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
 at org.spark-project.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
 at org.spark-project.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1507)
 at org.apache.hadoop.yarn.server.webproxy.amfilter.AmIpFilter.doFilter(AmIpFilter.java:179)
 at org.spark-project.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1478)
 at org.spark-project.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
 at org.spark-project.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
 at org.spark-project.jetty.servlet.ServletHandler.doScope(ServletHandler.java:427)
 at org.spark-project.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
 at org.spark-project.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
 at org.spark-project.jetty.server.handler.GzipHandler.handle(GzipHandler.java:301)
 at org.spark-project.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
 at org.spark-project.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
 at org.spark-project.jetty.server.Server.handle(Server.java:370)
 at org.spark-project.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)
 at org.spark-project.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:973)
 at org.spark-project.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1035)
 at org.spark-project.jetty.http.HttpParser.parseNext(HttpParser.java:641)
 at org.spark-project.jetty.http.HttpParser.parseAvailable(HttpParser.java:231)
 at org.spark-project.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
 at org.spark-project.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:696)
 at org.spark-project.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:53)

Powered by Jetty://

I see error is java.lang.OutOfMemoryError: Java heap space

But I don't know what memory I need increase:

Memory of server running SPARK

Memory of executor configure with SPARK

other Memory configure...

Update: my SPARK configure

my SPARK configure

Body:
The thrift server runs in it's own memory space. You can specify that via the executor memory property.

For example

./sbin/start-thriftserver.sh --executor-memory 512m

I think the default is 1g, as the spark-env.sh has.


问:
PHP enable <?= ?>

Possible Duplicate:

  How to enable PHP short tags ?

  Enable short open tags without php.ini

Hey,

I never used that in php (as I never needed it) but currently I'm working with another php programmer and he uses it. So I don't want to end up rewriting his code all the time just to make it work on my machine. How should I enable this in php ? Probably it's something in the php.ini ?

答:
You should put in php.ini:

short_open_tag=on

Title: PHP enable <?= ?>


问:
How to properly detach and remove shared memory between 2 processes in PHP?
I developed a way to make async tasks with PHP and it's working very well, until now.

The logic based in 3 extensions  PCNTL, POSIX e Semaphore.

To have a full control of the master process and child process I must share the status of the task and the PID between them. These 2 variables are shared using  shm_attach, the fork uses pcntl_fork.

The problem described in the title of this questions is related to the status of the task and the PID between them. These 2 variables are shared using  shm_attach  method because there is no more space available to share create a shared memory.

I use it for 2 moments:
At constructor to create the shared memory

```<code><?php
//...
 final public function __construct() {
self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE);

            $this->var_key_pid = $this->alocatesharedMemory(getmypid(), 112112105100); //112112105100;
            $this->var_key_status = $this->alocatesharedMemory('PENDING', 11511697116117115);  //11511697116117115;
}
</code>```

And on the run method after forking the process

```<code><?php
final public function run($parameters) {
//...
} else { //Frok process
                ignore_user_abort(); //I dont know why but must be set again.
                $sid = posix_setsid();
                self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE);
</code>```

NOTE: The code is a little extensive and I put it into a gist
  https://gist.github.com/LeonanCarvalho/62c6fe0b62db8a478f502f84c5734c83

I think I'm doing something wrong because even though I'm using shm_detach and shm_remove the process sometimes returns the error PHP Warning: "shm_attach" failed for key No space left on the device in when I try to attach a new shared memory.

It is happening because some shared memory is detached and not removed from Shared memory segments, its the result of command ipcs -m :

The tasks are running for months before start doing this, so the one way to work around this problem I removed all shared memory identifiers with the command

```<code>ipcrm --all=shm
</code>```

But I think it's silently growing and for sure it going to happen again.

How to prevent it?

答:
I think the process may be leaking memory due to objects being created and not destroyed inside the process' memory. one way you can analise this is by reviewing the process' memory usage and which queries are being sent, that may be causing this problem, if you can reproduce the creation and leakage of memory, then it should be possible to figure out a way to delete the created objects. this may be happening due to cursors left open among other factors.
Have you considered using RabbitMQ for the async PHP tasks?</p>

Body:
I developed a way to make async tasks with PHP and it's working very well, until now.

The logic based in 3 extensions  PCNTL, POSIX e Semaphore.

To have a full control of the master process and child process I must share the status of the task and the PID between them. These 2 variables are shared using  shm_attach, the fork uses pcntl_fork.

The problem described in the title of this questions is related to the status of the task and the PID between them. These 2 variables are shared using  shm_attach  method because there is no more space available to share create a shared memory.

I use it for 2 moments:
At constructor to create the shared memory

<?php
//...
 final public function __construct() {
self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE);

            $this->var_key_pid = $this->alocatesharedMemory(getmypid(), 112112105100); //112112105100;
            $this->var_key_status = $this->alocatesharedMemory('PENDING', 11511697116117115);  //11511697116117115;
}

And on the run method after forking the process

<?php
final public function run($parameters) {
//...
} else { //Frok process
                ignore_user_abort(); //I dont know why but must be set again.
                $sid = posix_setsid();
                self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE);

NOTE: The code is a little extensive and I put it into a gist
  https://gist.github.com/LeonanCarvalho/62c6fe0b62db8a478f502f84c5734c83

I think I'm doing something wrong because even though I'm using shm_detach and shm_remove the process sometimes returns the error PHP Warning: "shm_attach" failed for key No space left on the device in when I try to attach a new shared memory.

It is happening because some shared memory is detached and not removed from Shared memory segments, its the result of command ipcs -m :

The tasks are running for months before start doing this, so the one way to work around this problem I removed all shared memory identifiers with the command

ipcrm --all=shm

But I think it's silently growing and for sure it going to happen again.

How to prevent it?


Title: Sample n random draw within group with different nrows

Body:
How can I draw n rows from a group where each group has a different number of rows?

df <- data.frame(matrix(rnorm(80), nrow=40))
df$color <-  rep(c("blue", "red", "yellow", "pink"), each=10)

I've tried,

library(dplyr)
outdat <- df %>%
  group_by(color) %>%
  sample_n(nrow(.), replace = TRUE)
outdat

but this returns a data.frame where nrow(.) are nrows from df and not the subset.

This SO post is close, but defines a specific number of row draws. I need it to be specific to group within dplyr.

Body:
Another workaround, use sample_frac:

outdat <- df %>%
    group_by(color) %>%
    sample_frac(1, replace = TRUE)
outdat
# # A tibble: 40 x 3
# # Groups:   color [4]
#             X1          X2 color
#          <dbl>       <dbl> <chr>
#  1  0.69256186  0.97180252  blue
#  2  1.54384827 -0.20268802  blue
#  3 -1.20068240 -0.45402013  blue
#  4  2.63407877 -0.31644247  blue
#  5  1.20716737 -0.91380874  blue
#  6  0.01067475  1.02004679  blue
#  7  0.01067475  1.02004679  blue
#  8  1.79732108 -0.04072946  blue
#  9  0.01067475  1.02004679  blue
# 10  1.79732108 -0.04072946  blue
# # ... with 30 more rows

Additionally, use outdat %>% ungroup() to remove grouping.


问:
How to look ahead one element (peek) in a Python generator?
I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.

Here is what I mean:

```<code>gen = iter([1,2,3])
next_value = gen.next()  # okay, I looked forward and see that next_value = 1
# but now:
list(gen)  # is [2, 3]  -- the first value is gone!
</code>```

Here is a more real example:

```<code>gen = element_generator()
if gen.next_value() == 'STOP':
  quit_application()
else:
  process(gen.next())
</code>```

Can anyone help me write a generator that you can look one element forward?

See also: Resetting generator object in Python

答:
w.r.t @David Z's post, the newer seekable tool can reset a wrapped iterator to a prior position.

```<code>>>> s = mit.seekable(range(3))
>>> s.next()
# 0

>>> s.seek(0)                                              # reset iterator
>>> s.next()
# 0

>>> s.next()
# 1

>>> s.seek(1)
>>> s.next()
# 1

>>> next(s)
# 2
</code>```

Body:
I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.

Here is what I mean:

gen = iter([1,2,3])
next_value = gen.next()  # okay, I looked forward and see that next_value = 1
# but now:
list(gen)  # is [2, 3]  -- the first value is gone!

Here is a more real example:

gen = element_generator()
if gen.next_value() == 'STOP':
  quit_application()
else:
  process(gen.next())

Can anyone help me write a generator that you can look one element forward?

See also: Resetting generator object in Python

Body:
w.r.t @David Z's post, the newer seekable tool can reset a wrapped iterator to a prior position.

>>> s = mit.seekable(range(3))
>>> s.next()
# 0

>>> s.seek(0)                                              # reset iterator
>>> s.next()
# 0

>>> s.next()
# 1

>>> s.seek(1)
>>> s.next()
# 1

>>> next(s)
# 2