问:
Segmentation fault in access vector C++
I'm writing a simple multi-threading program to add and access member in a vector in a multiple thread:

Thread 1: Use push_back to add member to vector

Thread 2: Calling a function Iterate through vector and check if the member is already in the vector then return it, otherwise return NULL

Some time I faced the Segmentation fault at the thread 2. Is the vector is thread safety for doing what I mention above. I do not have any code to remove member from the vector, only adding more.

Here is the full code of function iterate the vector:

```<code>Scope* ScopeList::FindScope(int32_t domain, int32_t channel) {
    Scope* findItem = new Scope(domain, channel);
    Scope* resultItem = NULL;
    for(uint32_t i = 0U; i < m_scope_list.size(); i++) {
        if(m_scope_list.at(i) == NULL) {
            continue;
        }
        if(m_scope_list.at(i)->isEqual(findItem)) {
            resultItem = m_scope_list.at(i);
            break;
        }
    }
    delete findItem;
    findItem = NULL;
    return resultItem;
}
</code>```

Here m_scope_list is a vector of Scope object, which isEqual function  is define as follow:

```<code>bool Scope::isEqual(Scope* scope) {
    if(scope == NULL||!this->m_domain ||!this->m_channel){
        return false;
    }
    bool result = this->m_domain == scope->GetDomain() && this->m_channel == scope->GetChannel();
    return result;
}
</code>```

答:
You need to synchronize both threads. Because a vector is not thread-safe. If you modify the vector from one thread and access from another then there is a high chance of getting a segmentation fault. You might want to look into uniqe_lock or lock_guard and mutex for details. If you don't understand anything about their usages then leave a comment. Happy Multithreading.

EDITED: From comment made by @GianPaolo

push_back will modify the internal state of the vector, in a way that can be not thread safe. if you call push_back when the vector as already reached its capacity, the current T[] array in use will be copied in a new T[] (of higher size), and the original will be deleted. Not something you can safely do while another thread is iterating on the vector

Title: Segmentation fault in access vector C++

Body:
I'm writing a simple multi-threading program to add and access member in a vector in a multiple thread:

Thread 1: Use push_back to add member to vector

Thread 2: Calling a function Iterate through vector and check if the member is already in the vector then return it, otherwise return NULL

Some time I faced the Segmentation fault at the thread 2. Is the vector is thread safety for doing what I mention above. I do not have any code to remove member from the vector, only adding more.

Here is the full code of function iterate the vector:

Scope* ScopeList::FindScope(int32_t domain, int32_t channel) {
    Scope* findItem = new Scope(domain, channel);
    Scope* resultItem = NULL;
    for(uint32_t i = 0U; i < m_scope_list.size(); i++) {
        if(m_scope_list.at(i) == NULL) {
            continue;
        }
        if(m_scope_list.at(i)->isEqual(findItem)) {
            resultItem = m_scope_list.at(i);
            break;
        }
    }
    delete findItem;
    findItem = NULL;
    return resultItem;
}

Here m_scope_list is a vector of Scope object, which isEqual function  is define as follow:

bool Scope::isEqual(Scope* scope) {
    if(scope == NULL||!this->m_domain ||!this->m_channel){
        return false;
    }
    bool result = this->m_domain == scope->GetDomain() && this->m_channel == scope->GetChannel();
    return result;
}


来源: stackexchange

问:
Reusable component to render button or router-link in Vue.js
I'm new using Vue.js and I had a difficulty creating a Button component.

How can I program this component to conditional rendering? In other words, maybe it should be rendering as a router-link maybe as a button? Like that:

```<code><Button type="button" @click="alert('hi!')">It's a button.</Button>
// -> Should return as a <button>.

<Button :to="{ name: 'SomeRoute' }">It's a link.</Button>
// -> Should return as a <router-link>.
</code>```

答:
You can toggle the tag inside render() or just use <component>.

According to the official specification for Dynamic Components:

You can use the same mount point and dynamically switch between multiple components using the reserved <component> element and dynamically bind to it's is attribute.

Here's an example for your case:

ButtonControl.vue

<template>
  <component :is="type" :to="to">
    {{ value }}
  </component>
</template>

```
<p>Now you can easily use it for a <code>button</code>:</p>
<pre class="lang-html prettyprint-override"><code><button-control value="Something"></button-control>
</code>```

Or a router-link:

<button-control to="/" value="Something"></button-control>
```

This is an excellent behavior to keep in mind when it's necessary to create elements that may have links or not, such as buttons or cards.

ContentLicense: CC BY-SA 3.0

Body:
I'm new using Vue.js and I had a difficulty creating a Button component.

How can I program this component to conditional rendering? In other words, maybe it should be rendering as a router-link maybe as a button? Like that:

<Button type="button" @click="alert('hi!')">It's a button.</Button>
// -> Should return as a <button>.

<Button :to="{ name: 'SomeRoute' }">It's a link.</Button>
// -> Should return as a <router-link>.

Body:
You can toggle the tag inside render() or just use <component>.

According to the official specification for Dynamic Components:

You can use the same mount point and dynamically switch between multiple components using the reserved <component> element and dynamically bind to it's is attribute.

Here's an example for your case:

ButtonControl.vue

<template>
  <component :is="type" :to="to">
    {{ value }}
  </component>
</template>

<script>
export default {
  computed: {
    type () {
      if (this.to) {
        return 'router-link'
      }

      return 'button'
    }
  },

  props: {
    to: {
      required: false
    },
    value: {
      type: String
    }
  }
}
</script>

Now you can easily use it for a button:

<button-control value="Something"></button-control>

Or a router-link:

<button-control to="/" value="Something"></button-control>

This is an excellent behavior to keep in mind when it's necessary to create elements that may have links or not, such as buttons or cards.

ContentLicense: CC BY-SA 4.0


问:
Elegant way to combine [[(Int, String)]] into [(Int, String)]?
I am using Swift 4, Xcode 9.

Specifically, I have an array of arrays [[(Int, String)]] where Int is a rank and String is a Name + Items... that are combined using .joined(separator: ";").

The data might look like this:

```<code>[[1,"My Name;Item1;Item2"], [(5,"My Name;Item2;Item3"), (3,"My Second Name;Item1")]]
</code>```

I want to combine the inner arrays so that:

Int adds for matching items based on the name (up to ";")

Strings add subsequent items if not already present

Combining my above example should lead to this:

```<code>[(6,"My Name;Item1;Item2;Item3"), (3,"My Second Name;Item1")]
</code>```

I.e. input is [[(Int, String)]] and output is [(Int, String)]

Currently, I can achieve this through a fairly complex set of loops. With a large dataset, this results in a noticeable performance drop. Is there an elegant/simple way to combine these arrays as I am requesting?

Thank you for any guidance!

答:
(Generally I would make this a comment because it doesn't answer the question, but it feels worth the trouble to explain exactly how you should change this.)

This is certainly possible, but don't. The answer is to replace this with an array of structs. Based on your data description:

```<code>struct Element {
    let rank: Int
    let name: String
    let items: Set<String> // Since you seem to want them to be unique and unordered
}

let elements: [[Element]] =
    [[Element(rank: 1, name: "My Name", items: ["Item1", "Item2"])],
     [Element(rank: 5, name: "My Name", items: ["Item2", "Item3"]),
      Element(rank: 3, name: "My Second Name", items: ["Item1"])]]

// You want to manage these by name, so let's make key/value pairs of all the elements
// as (Name, Element)
let namedElements = elements.joined().map { ($0.name, $0) }

// Now combine them as you describe. Add the ranks, and merge the items
let uniqueElements =
    Dictionary<String, Element>(namedElements,
                                uniquingKeysWith: { (lhs, rhs) -> Element in
                                    return Element(rank: lhs.rank + rhs.rank,
                                                   name: lhs.name,
                                                   items: lhs.items.union(rhs.items))
    })

// The result is the values of the dictionary
let result = uniqueElements.values

// Element(rank: 6, name: "My Name", items: Set(["Item3", "Item2", "Item1"]))
// Element(rank: 3, name: "My Second Name", items: Set(["Item1"]))
</code>```

Body:
I am using Swift 4, Xcode 9.

Specifically, I have an array of arrays [[(Int, String)]] where Int is a rank and String is a Name + Items... that are combined using .joined(separator: ";").

The data might look like this:

[[1,"My Name;Item1;Item2"], [(5,"My Name;Item2;Item3"), (3,"My Second Name;Item1")]]

I want to combine the inner arrays so that:

Int adds for matching items based on the name (up to ";")

Strings add subsequent items if not already present

Combining my above example should lead to this:

[(6,"My Name;Item1;Item2;Item3"), (3,"My Second Name;Item1")]

I.e. input is [[(Int, String)]] and output is [(Int, String)]

Currently, I can achieve this through a fairly complex set of loops. With a large dataset, this results in a noticeable performance drop. Is there an elegant/simple way to combine these arrays as I am requesting?

Thank you for any guidance!

Body:
(Generally I would make this a comment because it doesn't answer the question, but it feels worth the trouble to explain exactly how you should change this.)

This is certainly possible, but don't. The answer is to replace this with an array of structs. Based on your data description:

struct Element {
    let rank: Int
    let name: String
    let items: Set<String> // Since you seem to want them to be unique and unordered
}

let elements: [[Element]] =
    [[Element(rank: 1, name: "My Name", items: ["Item1", "Item2"])],
     [Element(rank: 5, name: "My Name", items: ["Item2", "Item3"]),
      Element(rank: 3, name: "My Second Name", items: ["Item1"])]]

// You want to manage these by name, so let's make key/value pairs of all the elements
// as (Name, Element)
let namedElements = elements.joined().map { ($0.name, $0) }

// Now combine them as you describe. Add the ranks, and merge the items
let uniqueElements =
    Dictionary<String, Element>(namedElements,
                                uniquingKeysWith: { (lhs, rhs) -> Element in
                                    return Element(rank: lhs.rank + rhs.rank,
                                                   name: lhs.name,
                                                   items: lhs.items.union(rhs.items))
    })

// The result is the values of the dictionary
let result = uniqueElements.values

// Element(rank: 6, name: "My Name", items: Set(["Item3", "Item2", "Item1"]))
// Element(rank: 3, name: "My Second Name", items: Set(["Item1"]))


问:
For mobile first approach,how to display all table column in desktop size after hiding some column in mobile size
There are 3 columns in total, for the desktop version, all column will be shown.
For the mobile version, only the first 2 columns will be shown.
Now, for both the desktop and mobile version, 2 columns are shown. The 3rd column is missing for the desktop version. Any thoughs, thankyou

/* Responsive design for the mobile devices  */

#hide,#hide2 {

    display:none;

        position:relative;

        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="2">
<tr>
<th>A</th>
<th>B</th>
<th id="hide">C</th>
</tr>

<td>Anna</td>
<td>BVen</td>
<td id="hide2">Crys</td>
</table></code>```

答:
Your css is being applied always. Media query is pretty much useless as of now.</p>

```<code>#hide,#hide2 {
        display:none;
        position:relative;
        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {
    #hide, #hide2 {
        display: block;
    }
}
</code>```

Body:
There are 3 columns in total, for the desktop version, all column will be shown.
For the mobile version, only the first 2 columns will be shown.
Now, for both the desktop and mobile version, 2 columns are shown. The 3rd column is missing for the desktop version. Any thoughs, thankyou

/* Responsive design for the mobile devices  */

#hide,#hide2 {

    display:none;

        position:relative;

        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {

}

A
B
C

Anna
BVen
Crys

Body:
Your css is being applied always. Media query is pretty much useless as of now.

#hide,#hide2 {
        display:none;
        position:relative;
        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {
    #hide, #hide2 {
        display: block;
    }
}


问:
how to fetch value based from two table with help of another table using sql
Here is my sql schema:

```<code>Table 1: scan_1             Table 2: scan_2          Table 3: scan_detail

P_no        work            P_no        work           P_no       work_date
 1          YES              1          YES             1         2017/11/03
 2          YES              2          NO              2         2017/12/31
 3          NO               3          NO              3         2017/12/13
</code>```

I want to count P_no from scan_1 and scan_2 where date range is belongs to scan_detail.
I use this query to count P_no from scan_1 and scan_2, but not able to add scan_detail in my query.

```<code>SELECT COUNT(*) AS pick FROM (SELECT P_no, work FROM scan_1 WHERE work = 'YES' UNION SELECT P_no, work FROM scan_2 WHERE work = 'YES') AS total
</code>```

In above query i want to add date range from scan_detail like

```<code>  select count(P_no) from scan_detail where work_date >='2017/11/03' and work_date <= '2017/12/31'
</code>```

答:
Use join query to add date time and then apply the filter. A pseudo query is given below</p>

```<code>SELECT COUNT(P_no) AS pick
FROM (SELECT a.P_no as P_no, a.work as work, b.work_date work_date
      FROM scan_1
      LEFT JOIN scan_details b on (a.P_no = b.P_no)
      WHERE work = 'YES'
      UNION
      SELECT c.P_no, c.work, d.work_date work_date
      FROM scan_2 c
      LEFT JOIN scan_details d on (c.P_no = d.P_no)
      WHERE work = 'YES'
      where work_date between date1 and date2)
</code>```

Body:
Here is my sql schema:

Table 1: scan_1             Table 2: scan_2          Table 3: scan_detail

P_no        work            P_no        work           P_no       work_date
 1          YES              1          YES             1         2017/11/03
 2          YES              2          NO              2         2017/12/31
 3          NO               3          NO              3         2017/12/13

I want to count P_no from scan_1 and scan_2 where date range is belongs to scan_detail.
I use this query to count P_no from scan_1 and scan_2, but not able to add scan_detail in my query.

SELECT COUNT(*) AS pick FROM (SELECT P_no, work FROM scan_1 WHERE work = 'YES' UNION SELECT P_no, work FROM scan_2 WHERE work = 'YES') AS total

In above query i want to add date range from scan_detail like

  select count(P_no) from scan_detail where work_date >='2017/11/03' and work_date <= '2017/12/31'

Body:
Use join query to add date time and then apply the filter. A pseudo query is given below

SELECT COUNT(P_no) AS pick
FROM (SELECT a.P_no as P_no, a.work as work, b.work_date work_date
      FROM scan_1
      LEFT JOIN scan_details b on (a.P_no = b.P_no)
      WHERE work = 'YES'
      UNION
      SELECT c.P_no, c.work, d.work_date work_date
      FROM scan_2 c
      LEFT JOIN scan_details d on (c.P_no = d.P_no)
      WHERE work = 'YES'
      where work_date between date1 and date2)


答:
Answer changes according to your comment .

/* Responsive design for the mobile devices  */
 #hide,#hide2 {

 display:none;

        position:relative;

        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {

        #hide,#hide2 {

 display:block;

        position:relative;

        margin: 0 auto;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="2">
<tr>
<th>A</th>
<th>B</th>
<th id="hide">C</th>
</tr>

<td>Anna</td>
<td>BVen</td>
<td id="hide2">Crys</td>
</table></code>```

Title: For mobile first approach,how to display all table column in desktop size after hiding some column in mobile size

Body:
Answer changes according to your comment .

/* Responsive design for the mobile devices  */
 #hide,#hide2 {

 display:none;

        position:relative;

        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {

        #hide,#hide2 {

 display:block;

        position:relative;

        margin: 0 auto;
}

}

<table border="2">
<tr>
<th>A</th>
<th>B</th>
<th id="hide">C</th>
</tr>

<td>Anna</td>
<td>BVen</td>
<td id="hide2">Crys</td>
</table>


问:
Using explicit cursor to calculate the total credits and the overall grade point for each student
I am trying to  calculate the total credits and the overall grade point for each student using PL/SQL cursor and also use the ROUND function to calculate GPA. I have no idea what I am doing wrong here.

I am getting a lot of errors.

Output should look like:

Student Name: Pete

BK 101 Intro to geography     3   B

BK 102 Intro to photographs       3   C

BK 140 Intro to maththematics 3   C

Total Credits: 9

Overall GPA: 2.33

```<code>DECLARE
CURSOR studentCursor IS SELECT StudentName, CourseID, CourseDescription,
CourseCredits, Grade
FROM SampleStudent;
s_StudentName VarChar2 (30)
s_CourseID Varchar2 (20)
s_CourseDescription VarChar2 (30)
s_CourseCredits VarChar2 (2)
s_Grade VarChar (2)
s_GradePoint
BEGIN
OPEN studentcursor;
    LOOP
      FETCH studentcursor INTO s_StudentName, s_CourseID,
s_CourseDescription, s_CourseCredits, s_Grade;
      EXIT WHEN studentcursor%NOTFOUND;
IF s_Grade = 'A' THEN s_GradePoint := 4
IF s_Grade = 'B' THEN s_GradePoint := 3
IF s_Grade = 'C' THEN s_GradePoint := 2
END IF;
END IF;
END IF;
DBMS_OUTPUT.PUT_LINE('Student Name: ' || s_StudentName);
DBMS_OUTPUT.PUT_LINE(s_CourseDescription || s_CourseCredits || s_Grade);
DBMS_OUTPUT.PUT_LINE('Total Credits:' || SUM(s_CourseCredits);
DBMS_OUTPUT.PUT_LINE('Overall GPA:' || ROUND()
END LOOP;
CLOSE studentCursor;
DBMS_OUTPUT.PUT_LINE('GRAND TOTAL VALUE OF ALL ITEMS:');
END;
/
</code>```

答:
I am not test this block, But I think you should use your block like this:</p>

```<code>DECLARE
  V_TOTAL_CREDITS NUMBER := 0;
BEGIN
  FOR RC IN (
            SELECT StudentName,
                   CourseID,
                   CourseDescription,
                   Grade,
                   DECODE(GRADE, 'A', 4, 'B', 3, 'C', 2) GRADE_POINT,
                   CourseCredits,
                   SUM(CourseCredits) OVER(PARTITION BY StudentName ORDER BY CourseID)  SUM_COURSE_CREDITS,
                   AVG(CourseCredits) OVER(PARTITION BY StudentName ORDER BY CourseID)  GPA
            FROM SampleStudent
            )
  LOOP
    V_TOTAL_CREDITS := V_TOTAL_CREDITS + RC.CourseCredits;

    DBMS_OUTPUT.PUT_LINE('Student Name: ' || RC.StudentName);
    DBMS_OUTPUT.PUT_LINE(RC.CourseID || ' '  ||
                         RC.CourseCredits || ' INTRO TO ' ||
                         RC.CourseDescription || ' ' ||
                         GRADE_POINT || ' ' ||
                         s_Grade);
    DBMS_OUTPUT.PUT_LINE('Total Credits:' || RC.SUM_COURSE_CREDITS);
    DBMS_OUTPUT.PUT_LINE('Overall GPA:' || RC.GPA);

  END LOOP;

  DBMS_OUTPUT.PUT_LINE('GRAND TOTAL VALUE OF ALL ITEMS:' || V_TOTAL_CREDITS);

END;
</code>```

Body:
I am trying to  calculate the total credits and the overall grade point for each student using PL/SQL cursor and also use the ROUND function to calculate GPA. I have no idea what I am doing wrong here.

I am getting a lot of errors.

Output should look like:

Student Name: Pete

BK 101 Intro to geography     3   B

BK 102 Intro to photographs       3   C

BK 140 Intro to maththematics 3   C

Total Credits: 9

Overall GPA: 2.33

DECLARE
CURSOR studentCursor IS SELECT StudentName, CourseID, CourseDescription,
CourseCredits, Grade
FROM SampleStudent;
s_StudentName VarChar2 (30)
s_CourseID Varchar2 (20)
s_CourseDescription VarChar2 (30)
s_CourseCredits VarChar2 (2)
s_Grade VarChar (2)
s_GradePoint
BEGIN
OPEN studentcursor;
    LOOP
      FETCH studentcursor INTO s_StudentName, s_CourseID,
s_CourseDescription, s_CourseCredits, s_Grade;
      EXIT WHEN studentcursor%NOTFOUND;
IF s_Grade = 'A' THEN s_GradePoint := 4
IF s_Grade = 'B' THEN s_GradePoint := 3
IF s_Grade = 'C' THEN s_GradePoint := 2
END IF;
END IF;
END IF;
DBMS_OUTPUT.PUT_LINE('Student Name: ' || s_StudentName);
DBMS_OUTPUT.PUT_LINE(s_CourseDescription || s_CourseCredits || s_Grade);
DBMS_OUTPUT.PUT_LINE('Total Credits:' || SUM(s_CourseCredits);
DBMS_OUTPUT.PUT_LINE('Overall GPA:' || ROUND()
END LOOP;
CLOSE studentCursor;
DBMS_OUTPUT.PUT_LINE('GRAND TOTAL VALUE OF ALL ITEMS:');
END;
/

Body:
I am not test this block, But I think you should use your block like this:

DECLARE
  V_TOTAL_CREDITS NUMBER := 0;
BEGIN
  FOR RC IN (
            SELECT StudentName,
                   CourseID,
                   CourseDescription,
                   Grade,
                   DECODE(GRADE, 'A', 4, 'B', 3, 'C', 2) GRADE_POINT,
                   CourseCredits,
                   SUM(CourseCredits) OVER(PARTITION BY StudentName ORDER BY CourseID)  SUM_COURSE_CREDITS,
                   AVG(CourseCredits) OVER(PARTITION BY StudentName ORDER BY CourseID)  GPA
            FROM SampleStudent
            )
  LOOP
    V_TOTAL_CREDITS := V_TOTAL_CREDITS + RC.CourseCredits;

    DBMS_OUTPUT.PUT_LINE('Student Name: ' || RC.StudentName);
    DBMS_OUTPUT.PUT_LINE(RC.CourseID || ' '  ||
                         RC.CourseCredits || ' INTRO TO ' ||
                         RC.CourseDescription || ' ' ||
                         GRADE_POINT || ' ' ||
                         s_Grade);
    DBMS_OUTPUT.PUT_LINE('Total Credits:' || RC.SUM_COURSE_CREDITS);
    DBMS_OUTPUT.PUT_LINE('Overall GPA:' || RC.GPA);

  END LOOP;

  DBMS_OUTPUT.PUT_LINE('GRAND TOTAL VALUE OF ALL ITEMS:' || V_TOTAL_CREDITS);

END;


问:
Concatenating columns in for loop
I have a sample data frame coords with pairs of coordinates and an `id:

```<code>> coords
  coords.x1 coords.x2  id
1 -77.06983  38.89720   A
2 -77.02854  38.89055   B
3 -77.04489  38.88567   C
</code>```

My objective is to loop through each row in the data frame, concatenate the coordinates of each row and then print out the id of each row.  The result should be something like:

```<code>[1] "-77.06983,  38.89720"
[1] "A"

[2] "-77.02854,  38.89055"
[2] "B"

[3] "-77.04489,  38.88567"
[3] "C"
</code>```

But the following code produces something different:

```<code>for (i in coords) {

  print(coords[i, c("coords.x1", "coords.x2")])

  print(coords[i, "id"])

}

  coords.x1 coords.x2
1 -77.06983  38.89720
2 -77.02854  38.89055
3 -77.04489  38.88567
[1] "A" "B" "C"
     coords.x1 coords.x2
NA          NA        NA
NA.1        NA        NA
NA.2        NA        NA
[1] NA NA NA
     coords.x1 coords.x2
NA          NA        NA
NA.1        NA        NA
NA.2        NA        NA
[1] NA NA NA
</code>```

Why does this happen and what am I doing wrong syntactically in this for loop?  Any suggestions would be appreciated

Here is the sample data:

```<code>> dput(coords)
structure(list(coords.x1 = c(-77.06983, -77.028545, -77.0448866666667
), coords.x2 = c(38.897195, 38.8905533333333, 38.8856716666667
), id = c("A", "B", "C")), .Names = c("coords.x1", "coords.x2",
"id"), row.names = c(NA, -3L), class = "data.frame")
</code>```

答:
You will need to change to

```<code>for (i in 1:nrow(coords)) {
.
.
.
}
</code>```

and try to avoid for loop if possible cuz they are quite slow in R
try function like map() from purrr or apply familiy function like lapply sapply and stuff.

```<code>print_coords = function(i,x){
  print( x[i,c("coords.x1", "coords.x2")])
  print(x[i,"id"])
}

invisible(lapply(1:nrow(coords),print_coords,x = coords))
</code>```

Title: Concatenating columns in for loop

Body:
I have a sample data frame coords with pairs of coordinates and an `id:

> coords
  coords.x1 coords.x2  id
1 -77.06983  38.89720   A
2 -77.02854  38.89055   B
3 -77.04489  38.88567   C

My objective is to loop through each row in the data frame, concatenate the coordinates of each row and then print out the id of each row.  The result should be something like:

[1] "-77.06983,  38.89720"
[1] "A"

[2] "-77.02854,  38.89055"
[2] "B"

[3] "-77.04489,  38.88567"
[3] "C"

But the following code produces something different:

for (i in coords) {

  print(coords[i, c("coords.x1", "coords.x2")])

  print(coords[i, "id"])

}

  coords.x1 coords.x2
1 -77.06983  38.89720
2 -77.02854  38.89055
3 -77.04489  38.88567
[1] "A" "B" "C"
     coords.x1 coords.x2
NA          NA        NA
NA.1        NA        NA
NA.2        NA        NA
[1] NA NA NA
     coords.x1 coords.x2
NA          NA        NA
NA.1        NA        NA
NA.2        NA        NA
[1] NA NA NA

Why does this happen and what am I doing wrong syntactically in this for loop?  Any suggestions would be appreciated

Here is the sample data:

> dput(coords)
structure(list(coords.x1 = c(-77.06983, -77.028545, -77.0448866666667
), coords.x2 = c(38.897195, 38.8905533333333, 38.8856716666667
), id = c("A", "B", "C")), .Names = c("coords.x1", "coords.x2",
"id"), row.names = c(NA, -3L), class = "data.frame")

Body:
You will need to change to

for (i in 1:nrow(coords)) {
.
.
.
}

and try to avoid for loop if possible cuz they are quite slow in R
try function like map() from purrr or apply familiy function like lapply sapply and stuff.

print_coords = function(i,x){
  print( x[i,c("coords.x1", "coords.x2")])
  print(x[i,"id"])
}

invisible(lapply(1:nrow(coords),print_coords,x = coords))


问:
How to use @MapKey annotation with 2 levels?
this question is similar to this other question I've asked, but slightly different.

I have this:

```<code>class A{

  private List<B> bs;

  ...
}

class B{

  private Long id;
  private C c;
  ...
}

class C{

  private Long id;
  private String name;
  ...
}
</code>```

And I'd like to have this:

```<code>class A{

  // the map should have b.c.name as key
  private Map<String,B> bs;

  ...
}

class B{

  private Long id;
  private C c;
  private A a;
  ...
}

class C{

  private Long id;
  private String name;
  ...
}
</code>```

I don't know if it is clear what I'd like to do, but it is as simple as mapping a one to many relationship to a Map with the name of C as the key of the map and b as the value.

Thanks in advance,
Neuquino

答:
I have a solution for your bounty. And it REALLY works for me.

This is a toy example works with a minor deprecation warning on @CollectionOfElements.
You might overcame it by replacing it with a newer annotation that supersedes it.

```<code>package com.wladimir.hibernate;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;

import org.hibernate.annotations.CollectionOfElements;

@Entity
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @CollectionOfElements
    @JoinTable
    private Map<String, B> bs = new HashMap<String, B>();

    public A() {
    }

    public Long getId() {
        return id;
    }

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

    public Map<String, B> getBs() {
        return bs;
    }

    public void setBs(Map<String, B> bs) {
        this.bs = bs;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "A [bs=" + bs + ", id=" + id + ", name=" + name + "]";
    }

}

package com.wladimir.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class B {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne
    private C c;

    @ManyToOne
    private A a;

    public B() {
    }

    public Long getId() {
        return id;
    }

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

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "B [a=" + a.getName() + ", c=" + c.getName() + ", id=" + id
                + ", name=" + name + "]";
    }

}

package com.wladimir.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class C {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    public C() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "C [id=" + id + ", name=" + name + "]";
    }
}

package examples.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class PersistenceUtil {
    private static final SessionFactory sessionFactory;

    static {
        Log log = LogFactory.getLog(PersistenceUtil.class);

        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (HibernateException ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw ex;
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

package examples.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;

import com.wladimir.hibernate.A;
import com.wladimir.hibernate.B;
import com.wladimir.hibernate.C;

import java.util.List;

import examples.hibernate.domain.*;

public class Tester{
    private SessionFactory factory;

    public Tester(SessionFactory factory) {
        this.factory = factory;
    }

    @SuppressWarnings("unchecked")
    public void runABC(String operation) {
        Session session = factory.getCurrentSession(); // obtain/start unit of
        // work
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // start transaction

            if ("Create".equals(operation)) {
                A a = new A();
                a.setName("A " + System.nanoTime());

                C c = new C();
                c.setName("C " + System.nanoTime());
                session.save(c);

                B b = new B();
                b.setName("B " + System.nanoTime());

                b.setA(a);
                b.setC(c);

                a.getBs().put(b.getName(), b);

                session.save(b);

                B b2 = new B();
                b2.setName("B " + System.nanoTime());

                b.setA(a);
                b.setC(c);

                a.getBs().put(b.getName(), b);

                session.save(a);

            } else if ("Read".equals(operation)) {
                System.out.println("Reading data set.");
                List<A> as = (List<A>) session.createCriteria(A.class)
                        .addOrder(Order.asc("name")).list();
                for (A a : as) {
                    System.out.println(a);
                }
            }
            tx.commit(); // commit transaction & end unit of work

        } catch (RuntimeException ex) {
            if (tx != null)
                tx.rollback(); // abort transaction
            throw ex;
        }
    }

    // main application loop
    public static void main(String args[]) throws Exception {
        Tester app = new Tester(PersistenceUtil.getSessionFactory());

        String operation = null;
        if (args.length == 1) {
            operation = args[0];
        }

        app.runABC(operation);

    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
this question is similar to this other question I've asked, but slightly different.

I have this:

class A{

  private List bs;

  ...
}

class B{

  private Long id;
  private C c;
  ...
}

class C{

  private Long id;
  private String name;
  ...
}

And I'd like to have this:

class A{

  // the map should have b.c.name as key
  private Map<String,B> bs;

  ...
}

class B{

  private Long id;
  private C c;
  private A a;
  ...
}

class C{

  private Long id;
  private String name;
  ...
}

I don't know if it is clear what I'd like to do, but it is as simple as mapping a one to many relationship to a Map with the name of C as the key of the map and b as the value.

Thanks in advance,
Neuquino

Body:
I have a solution for your bounty. And it REALLY works for me.

This is a toy example works with a minor deprecation warning on @CollectionOfElements.
You might overcame it by replacing it with a newer annotation that supersedes it.

package com.wladimir.hibernate;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;

import org.hibernate.annotations.CollectionOfElements;

@Entity
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @CollectionOfElements
    @JoinTable
    private Map<String, B> bs = new HashMap<String, B>();

    public A() {
    }

    public Long getId() {
        return id;
    }

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

    public Map<String, B> getBs() {
        return bs;
    }

    public void setBs(Map<String, B> bs) {
        this.bs = bs;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "A [bs=" + bs + ", id=" + id + ", name=" + name + "]";
    }

}

package com.wladimir.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class B {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne
    private C c;

    @ManyToOne
    private A a;

    public B() {
    }

    public Long getId() {
        return id;
    }

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

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "B [a=" + a.getName() + ", c=" + c.getName() + ", id=" + id
                + ", name=" + name + "]";
    }

}

package com.wladimir.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class C {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    public C() {
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "C [id=" + id + ", name=" + name + "]";
    }
}

package examples.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class PersistenceUtil {
    private static final SessionFactory sessionFactory;

    static {
        Log log = LogFactory.getLog(PersistenceUtil.class);

        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (HibernateException ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw ex;
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

package examples.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;

import com.wladimir.hibernate.A;
import com.wladimir.hibernate.B;
import com.wladimir.hibernate.C;

import java.util.List;

import examples.hibernate.domain.*;

public class Tester{
    private SessionFactory factory;

    public Tester(SessionFactory factory) {
        this.factory = factory;
    }

    @SuppressWarnings("unchecked")
    public void runABC(String operation) {
        Session session = factory.getCurrentSession(); // obtain/start unit of
        // work
        Transaction tx = null;
        try {
            tx = session.beginTransaction(); // start transaction

            if ("Create".equals(operation)) {
                A a = new A();
                a.setName("A " + System.nanoTime());

                C c = new C();
                c.setName("C " + System.nanoTime());
                session.save(c);

                B b = new B();
                b.setName("B " + System.nanoTime());

                b.setA(a);
                b.setC(c);

                a.getBs().put(b.getName(), b);

                session.save(b);

                B b2 = new B();
                b2.setName("B " + System.nanoTime());

                b.setA(a);
                b.setC(c);

                a.getBs().put(b.getName(), b);

                session.save(a);

            } else if ("Read".equals(operation)) {
                System.out.println("Reading data set.");
                List<A> as = (List<A>) session.createCriteria(A.class)
                        .addOrder(Order.asc("name")).list();
                for (A a : as) {
                    System.out.println(a);
                }
            }
            tx.commit(); // commit transaction & end unit of work

        } catch (RuntimeException ex) {
            if (tx != null)
                tx.rollback(); // abort transaction
            throw ex;
        }
    }

    // main application loop
    public static void main(String args[]) throws Exception {
        Tester app = new Tester(PersistenceUtil.getSessionFactory());

        String operation = null;
        if (args.length == 1) {
            operation = args[0];
        }

        app.runABC(operation);

    }
}


问:
How can i edit the error message box in CF-7?
i had add some extra field on the CF-7 form everything work fine except the respond message box. im getting something like this

https://i.stack.imgur.com/JulGC.png

but i was hoping to get the error message only display next to my "Submit" Button.

is there anyway i can archive that? Im new to wordpress so im not really sure where can i start.

答:
you can use jquery validation. You can easily implement jquery validation in contact form 7

here is sample code for jquery validation.

```<code>$(".wpcf7-form").validate({
    rules: {
       yourname: "required",
     youremail: {
       required: true,
       email: true
      },
    },
       messages: {
        yourname: "Please include your name.",
        youremail: "Please include a valid email address.",
        yourmessage: "Please tell me how I can help you.",

    },
});
</code>```

or PHP code,Link contact form 7

```<code>add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );

function custom_email_confirmation_validation_filter( $result, $tag ) {
if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';

    if ( $your_email != $your_email_confirm ) {
        $result->invalidate( $tag, "Are you sure this is the correct address?" );
    }
}

return $result;
}
</code>```

or may use this plugin. Jquery Validation For Contact Form 7

Hope this wiull helps you.

Body:
you can use jquery validation. You can easily implement jquery validation in contact form 7

here is sample code for jquery validation.

$(".wpcf7-form").validate({
    rules: {
       yourname: "required",
     youremail: {
       required: true,
       email: true
      },
    },
       messages: {
        yourname: "Please include your name.",
        youremail: "Please include a valid email address.",
        yourmessage: "Please tell me how I can help you.",

    },
});

or PHP code,Link contact form 7

add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );

function custom_email_confirmation_validation_filter( $result, $tag ) {
if ( 'your-email-confirm' == $tag->name ) {
    $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
    $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';

    if ( $your_email != $your_email_confirm ) {
        $result->invalidate( $tag, "Are you sure this is the correct address?" );
    }
}

return $result;
}

or may use this plugin. Jquery Validation For Contact Form 7

Hope this wiull helps you.


问:
Best approach for hosting multiple applications on AWS with SSL
I have several applications (nodejs & angular) that I am moving to AWS. I have set up my clients using CloudFront. However, I'm not quite sure how to go about setting up my backends on AWS.

Let's say I have five domains a.com, b.com, d.com, d.com, and e.com

These are small applications so I don't necessarily want to have five different EC2 instances. Currently they are all running on a single EC2 instance on different ports.

I'm not sure how to set up https:// routing to all these instances. For example I need to make requests from my clients to https://a.com, https://b.com and so on.

What is the recommended approach to accomplish a set up like this?

答:
Based on your scenario, you can setup Amazon ECS to run multiple applications. With the newly introduced Amazon Fargate for Amazon ECS and EKS, it allows to run containers without having to manage servers or clusters.

Note: You need to dockerize your applications to run as containers.

You can setup Application Load Balancer(ALB) and CloudFront to configure SSL and to terminate SSL connections. CloudFront can be used outside the ALB to cache static content at edge locations.


问:
Wildcards for filter function in dplyr
I am using dplyr and I would like to filter my dataframe (biotypes) according to sample IDs which are the first column of the data frame, e.g. they look like this:

```<code>ID
chrX.tRNA494-SerAGA
chrX.tRNA636-AlaCGC
mmu_piR_000007
...
</code>```

I want to filter IDs starting with "chr" from IDs starting with "mmu":

```<code>biotype<- biotype %>%
  filter( str_detect (biotype, "^chr") ==TRUE )
biotype
</code>```

Can anyone help please? I am just looking for something like * that allows me to filter all rows that have a string starting with these particular characters ...

答:
I think you were very close already.

```<code>library(stringr)
biotype %>% filter(str_detect(ID,"^chr"))
</code>```

(you need to specify the column name, and == TRUE is superfluous).

Title: Wildcards for filter function in dplyr

Body:
I am using dplyr and I would like to filter my dataframe (biotypes) according to sample IDs which are the first column of the data frame, e.g. they look like this:

ID
chrX.tRNA494-SerAGA
chrX.tRNA636-AlaCGC
mmu_piR_000007
...

I want to filter IDs starting with "chr" from IDs starting with "mmu":

biotype<- biotype %>%
  filter( str_detect (biotype, "^chr") ==TRUE )
biotype

Can anyone help please? I am just looking for something like * that allows me to filter all rows that have a string starting with these particular characters ...

Body:
I think you were very close already.

library(stringr)
biotype %>% filter(str_detect(ID,"^chr"))

(you need to specify the column name, and == TRUE is superfluous).


问:
Need help creating a specific pointcut that utilizes a value from a method annotation
I have the following method

```<code>    @AutoHandling(slot = FunctionalArea.PRE_MAIN_MENU)
    @RequestMapping(method = RequestMethod.GET)
    public String navigation(ModelMap model) {
        logger.debug("navigation");
        ...

            //First time to the Main Menu and ID-Level is ID-1 or greater
            if (!callSession.getCallFlowData().isMainMenuPlayed()
                    && callSession.getCallFlowData().getIdLevel() >= 1) {
                // Call Auto Handling
                logger.info("Call AutoHandling");
                autoHandlingComponent.processAutoHandling();
            }
        ...

        return forward(returnView);
    }
</code>```

Basically what I want to do, is have a pointcut on processAutoHandling()
But in the @After, I need to use the slot() for @AutoHandling

I tried this, but it does not get called

```<code>@Pointcut("execution(* *.processAutoHandling())")
public void processAutoHandleCall() {
    logger.debug("processAutoHandleCall");
}

@Around("processAutoHandleCall() &&" +
        "@annotation(autoHandling) &&" +
        "target(bean) "
)
public Object processAutoHandlingCall(ProceedingJoinPoint jp,
                                      AutoHandling autoHandling,
                                      Object bean)
        throws Throwable {
         ...
</code>```

答:
You can use the wormhole design pattern for this. I am illustrating using AspectJ byte-code based approach and syntax, but you should be able to get the same effect using an explicit ThreadLocal if you are using Spring's proxy-based AOP.</p>

```<code>pointcut navigation(AutoHandling handling) : execution(* navigation(..))
                                             && @annotation(handling);

// Collect whatever other context you need
pointcut processAutoHandleCall() : execution(* *.processAutoHandling());

pointcut wormhole(AutoHandling handling) : processAutoHandleCall()
                                           && cflow(navigation(handling));

after(AutoHandling handling) : wormhole(hanlding) {
   ... you advice code
   ... access the slot using handling.slot()
}
</code>```

Body:
I have the following method

    @AutoHandling(slot = FunctionalArea.PRE_MAIN_MENU)
    @RequestMapping(method = RequestMethod.GET)
    public String navigation(ModelMap model) {
        logger.debug("navigation");
        ...

            //First time to the Main Menu and ID-Level is ID-1 or greater
            if (!callSession.getCallFlowData().isMainMenuPlayed()
                    && callSession.getCallFlowData().getIdLevel() >= 1) {
                // Call Auto Handling
                logger.info("Call AutoHandling");
                autoHandlingComponent.processAutoHandling();
            }
        ...

        return forward(returnView);
    }

Basically what I want to do, is have a pointcut on processAutoHandling()
But in the @After, I need to use the slot() for @AutoHandling

I tried this, but it does not get called

@Pointcut("execution(* *.processAutoHandling())")
public void processAutoHandleCall() {
    logger.debug("processAutoHandleCall");
}

@Around("processAutoHandleCall() &&" +
        "@annotation(autoHandling) &&" +
        "target(bean) "
)
public Object processAutoHandlingCall(ProceedingJoinPoint jp,
                                      AutoHandling autoHandling,
                                      Object bean)
        throws Throwable {
         ...

Body:
You can use the wormhole design pattern for this. I am illustrating using AspectJ byte-code based approach and syntax, but you should be able to get the same effect using an explicit ThreadLocal if you are using Spring's proxy-based AOP.

pointcut navigation(AutoHandling handling) : execution(* navigation(..))
                                             && @annotation(handling);

// Collect whatever other context you need
pointcut processAutoHandleCall() : execution(* *.processAutoHandling());

pointcut wormhole(AutoHandling handling) : processAutoHandleCall()
                                           && cflow(navigation(handling));

after(AutoHandling handling) : wormhole(hanlding) {
   ... you advice code
   ... access the slot using handling.slot()
}


问:
How to get typename defined in derived from base class?
```<code>template <class Derived>
struct Base {
  typedef typename Derived::T T;
};

template <typename T_>
struct Impl : public Base<Impl<T_>> {
  typedef T_ T;
};
</code>```

When initialized this, I got an error of

no type named 'T' in 'Impl'

So, how can I get typename defined in derived from base class?

答:
Find a way to do it, though it is not perfect but does work.

```<code>template <class T>
struct traits;

template <class Derived>
struct Base {
  typedef typename traits<Derived>::T T;
};

template <typename T_>
struct Impl : public Base<Impl<T_>> {
  typedef T_ T;
};

template <typename T_>
struct traits<Impl<T_>> {
  typedef T_ T;
};
</code>```

It is not perfect because in the traits class, I cannot write

```<code>typedef typename Impl<T_>::T T;
</code>```

It is still undefined.

Body:
template <class Derived>
struct Base {
  typedef typename Derived::T T;
};

template <typename T_>
struct Impl : public Base<Impl<T_>> {
  typedef T_ T;
};

When initialized this, I got an error of

no type named 'T' in 'Impl'

So, how can I get typename defined in derived from base class?

Body:
Find a way to do it, though it is not perfect but does work.

template <class T>
struct traits;

template <class Derived>
struct Base {
  typedef typename traits<Derived>::T T;
};

template <typename T_>
struct Impl : public Base<Impl<T_>> {
  typedef T_ T;
};

template <typename T_>
struct traits<Impl<T_>> {
  typedef T_ T;
};

It is not perfect because in the traits class, I cannot write

typedef typename Impl<T_>::T T;

It is still undefined.


问:
Google Map is not displayed after I submitted my app to the Play store
After I submitted my app to play store I noticed that map is not shown, I also noticed this problem is some how common; I tried all possible solutions but none of them have worked for me, the blank map is always displayed after I install/update my app, in some cases I managed to display map in release-apk, I still face the same proplem after I download my app from play store, notice that when map is displayed in release version, it does not display in debug version; some of these solutions are

<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key"/>

and

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/google_maps_key" />

I placed both tags inside application tag and outside application tag in manifest file, still not working.

I used SHA1 key that was generated by android studio and the another one generated me using file.keystore, still not working, I tired different api keys for debug and release apk in google_map_api.xml still not working; I don't know what else I should try.

thanks in advance

答: When you want to upload the app to google play, you must change the HASH KEY and upload.</p>


问:
Django modelformset_factory deleting objects marked by can_delete
Hello I have got question I have made modelformset_factory and in options I have choosen can_delete = True and now I don't know how to delete marked objects as 'DELETE' : True to delete them from database. I was trying to do this in some ways and it didnt work. I was looking for it also in django formsetmodels documentation but this didnt help me. With this option can_delete = True I get additional checkbox in my html page Delete and marking him only prints me in console on print:
{'username': 'sw', 'email': 'a@gmail.com', 'city': 'ss', 'code': 12345, 'id': , 'DELETE': False}

Saving forms to database is working but I dont know how to delete marked forms from database.

I would be very thankful for every help.

I have made modelformset_factory from model in models.py

```<code>class TestModel(models.Model):
username = models.CharField(max_length=120)
email = models.EmailField()
city = models.CharField(max_length=120)
code = models.IntegerField()
#W admin panelu za miast TestModel object bedzie username
def __str__(self):
    return self.username
</code>```

Then I have added in my views.py function:

```<code>def django_modelformset(request):
TestModelFormset = modelformset_factory(TestModel, fields=['username', 'email', "city",
                                                           "code"], extra=1, can_delete=True)
formset = TestModelFormset(request.POST or None)

if formset.is_valid():
    for form in formset:
        print(form)

        print(form.cleaned_data)
        form.save()
context = {"formset": formset}
return render(request, "modelformset.html", context)
</code>```

My modelformset.html looks like this:

```<code><form method="POST" action="">
{% csrf_token %}

{{ formset.management_form}}
{% for form in formset %}
<div>

    {{ form.as_p }}
    <hr/>
</div>
{% endfor %}
<input type="submit" value="Save">
</code>```

答:
I haven't personally had to do this, but from the docs it seems you have a few options.

Call save on the formset instead of each form.

```<code>if formset.is_valid():
    formset.save()
</code>```

If you must loop through each form you could something like this.

```<code>if formset.is_valid():
   for form in formset:
       print(form.cleaned_data)
       if form.cleaned_data["DELETE"]:
           # Do what you want with the form data
           # i.e. get the object from the database and delete it.
       else:
           form.save()
</code>```

Loop through the deleted forms separately.

```<code>if formset.is_valid():
    forms = formset.save(commit=False)
    for object in formset.deleted_objects:
        object.delete()
</code>```

Body:
Hello I have got question I have made modelformset_factory and in options I have choosen can_delete = True and now I don't know how to delete marked objects as 'DELETE' : True to delete them from database. I was trying to do this in some ways and it didnt work. I was looking for it also in django formsetmodels documentation but this didnt help me. With this option can_delete = True I get additional checkbox in my html page Delete and marking him only prints me in console on print:
{'username': 'sw', 'email': 'a@gmail.com', 'city': 'ss', 'code': 12345, 'id': , 'DELETE': False}

Saving forms to database is working but I dont know how to delete marked forms from database.

I would be very thankful for every help.

I have made modelformset_factory from model in models.py

class TestModel(models.Model):
username = models.CharField(max_length=120)
email = models.EmailField()
city = models.CharField(max_length=120)
code = models.IntegerField()
#W admin panelu za miast TestModel object bedzie username
def __str__(self):
    return self.username

Then I have added in my views.py function:

def django_modelformset(request):
TestModelFormset = modelformset_factory(TestModel, fields=['username', 'email', "city",
                                                           "code"], extra=1, can_delete=True)
formset = TestModelFormset(request.POST or None)

if formset.is_valid():
    for form in formset:
        print(form)

        print(form.cleaned_data)
        form.save()
context = {"formset": formset}
return render(request, "modelformset.html", context)

My modelformset.html looks like this:

<form method="POST" action="">
{% csrf_token %}

{{ formset.management_form}}
{% for form in formset %}

    {{ form.as_p }}

{% endfor %}
<input type="submit" value="Save">

Body:
I haven't personally had to do this, but from the docs it seems you have a few options.

Call save on the formset instead of each form.

if formset.is_valid():
    formset.save()

If you must loop through each form you could something like this.

if formset.is_valid():
   for form in formset:
       print(form.cleaned_data)
       if form.cleaned_data["DELETE"]:
           # Do what you want with the form data
           # i.e. get the object from the database and delete it.
       else:
           form.save()

Loop through the deleted forms separately.

if formset.is_valid():
    forms = formset.save(commit=False)
    for object in formset.deleted_objects:
        object.delete()


答:
Do it like this.

/* Responsive design for the desktop  */

/* load normal desktop css */

/* Responsive design for the mobile devices  */
@media (max-width: 480px) {

#hide, #hide2 {

    display:none;
        position:relative;
        margin: 0 auto;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="2">
<tr>
<th>A</th>
<th>B</th>
<th id="hide">C</th>
</tr>

<td>Anna</td>
<td>BVen</td>
<td id="hide2">Crys</td>
</table></code>```

Body:
There are 3 columns in total, for the desktop version, all column will be shown.
For the mobile version, only the first 2 columns will be shown.
Now, for both the desktop and mobile version, 2 columns are shown. The 3rd column is missing for the desktop version. Any thoughs, thankyou

/* Responsive design for the mobile devices  */

#hide,#hide2 {

    display:none;

        position:relative;

        margin: 0 auto;
}

/* Responsive design for the desktop devices  */
@media (min-width: 769px) {

}

A
B
C

Anna
BVen
Crys

Body:
Do it like this.

/* Responsive design for the desktop  */

/* load normal desktop css */

/* Responsive design for the mobile devices  */
@media (max-width: 480px) {

#hide, #hide2 {

    display:none;
        position:relative;
        margin: 0 auto;
}

}

<table border="2">
<tr>
<th>A</th>
<th>B</th>
<th id="hide">C</th>
</tr>

<td>Anna</td>
<td>BVen</td>
<td id="hide2">Crys</td>
</table>


问:
python 3.x I want to write a code that with random
```<code>import random
score=2
heads=1
tails=2

while score>=2:
    a= input("Heads or tails?")
    if random.randint(heads,tails)==a:
        score +=1
        print("Yes it's correct!. Now your score is:",score)

    else:
        score -=1
        print("Fail.now your score is:",score)

print("GAMEOVER You Lose ")
</code>```

Guys I tried to write a code that when input asks to user if he/she writes down heads or tails python gives a random decision or whatever(heads or tails).
But I couldn't manage to do it with strings. what I'am trying to do is I want to write tails for a input and if its true my score will be 2 and it goes till score become 1
BTW I'm sorry about my english

答:
Here is something with a minimal change of your code. The exact method you were trying to perform cannot be done in python without using a datatype.

Here I am using a dictionary called 'dict'. It is basically a key value pair. And uses anything inside double quotes i.e. " " as an index. Syntactically similar to arrays in C++ but not limited to only integer indices.

```<code>import random
score=2
heads=1
tails=2
dict {"Heads":1,"Tails":2,"heads":1,"tails":2} # Handles both lower and upper case

while score>=2:
    a= input("Heads or tails?")
    if random.randint(heads,tails)==dict[a]:
        score +=1
        print("Yes it's correct!. Now your score is:",score)

    else:
        score -=1
        print("Fail.now your score is:",score)

print("GAMEOVER You Lose ")
</code>```

Body:
import random
score=2
heads=1
tails=2

while score>=2:
    a= input("Heads or tails?")
    if random.randint(heads,tails)==a:
        score +=1
        print("Yes it's correct!. Now your score is:",score)

    else:
        score -=1
        print("Fail.now your score is:",score)

print("GAMEOVER You Lose ")

Guys I tried to write a code that when input asks to user if he/she writes down heads or tails python gives a random decision or whatever(heads or tails).
But I couldn't manage to do it with strings. what I'am trying to do is I want to write tails for a input and if its true my score will be 2 and it goes till score become 1
BTW I'm sorry about my english

Body:
Here is something with a minimal change of your code. The exact method you were trying to perform cannot be done in python without using a datatype.

Here I am using a dictionary called 'dict'. It is basically a key value pair. And uses anything inside double quotes i.e. " " as an index. Syntactically similar to arrays in C++ but not limited to only integer indices.

import random
score=2
heads=1
tails=2
dict {"Heads":1,"Tails":2,"heads":1,"tails":2} # Handles both lower and upper case

while score>=2:
    a= input("Heads or tails?")
    if random.randint(heads,tails)==dict[a]:
        score +=1
        print("Yes it's correct!. Now your score is:",score)

    else:
        score -=1
        print("Fail.now your score is:",score)

print("GAMEOVER You Lose ")


问:
Store ssh connections in rails
I have a rails app that needs to communicate with a couple of servers through ssh. I'm using the Net::SSH library and it works great. I would like however to be able to cache/store the ssh connections somehow between requests (something like OpenSSH multiplexing).

So, i can't store them in a key-value store like Memcached or Redis (because ssh connections are not serializable).

I don't want to store them in a session because they are meant to be used by all users (and besides i think it needs to be serializable also).

I managed to get this working with class variables and initiliazer constants. I know that class variables don't replicate between servers (in production), and i'm pretty certain initializer constants also don't. Something like:

initializer:

```<code>SSH = {}
</code>```

model:

```<code>class Server
    def connection
        require 'net/ssh'
        SSH[name] ||= Net::SSH.start(ip, "root", :password => password)
    end
end
</code>```

OpenSSH multiplexing would be great but i'm not sure if i could do that through the Net::SSH ruby library (i'm back to storing the master connection somewhere).

Are there any other solutions? Or if not, which one is the least evil of them all?

答:
To keep the SSH connection up between requests, you'll need to spawn off a background process.  The background process can open up a pipe or some other sort of interprocess communication method, the handle to which you can store in a serializable way.

Note that this is a non-trivial exercise, which is why I've only described it at high-level detail.

Title: Store ssh connections in rails

Body:
I have a rails app that needs to communicate with a couple of servers through ssh. I'm using the Net::SSH library and it works great. I would like however to be able to cache/store the ssh connections somehow between requests (something like OpenSSH multiplexing).

So, i can't store them in a key-value store like Memcached or Redis (because ssh connections are not serializable).

I don't want to store them in a session because they are meant to be used by all users (and besides i think it needs to be serializable also).

I managed to get this working with class variables and initiliazer constants. I know that class variables don't replicate between servers (in production), and i'm pretty certain initializer constants also don't. Something like:

initializer:

SSH = {}

model:

class Server
    def connection
        require 'net/ssh'
        SSH[name] ||= Net::SSH.start(ip, "root", :password => password)
    end
end

OpenSSH multiplexing would be great but i'm not sure if i could do that through the Net::SSH ruby library (i'm back to storing the master connection somewhere).

Are there any other solutions? Or if not, which one is the least evil of them all?


问:
PHP hash_pbkdf2 to javascript

I'm trying to convert the hash_pbkdf2 of PHP to javascript, but their output is not quite the same, I'm using the crypto.pbkdf2Sync of javascript (nodejs) for this.

For this example, the password I've used is: "password"

PHP:

```<code>$iv = hash_pbkdf2("sha256", $password, strlen($password), 1000, 16);
echo "iv: " . $iv . "<br />";
echo "iv length: " . strlen($iv);
</code>```

Output:
iv: 4cf7620724f7b273

  iv length: 16

Javascript:

```<code>var iv = crypto.pbkdf2Sync(password, password.length.toString(), 1000, 16, 'sha256');
console.log(iv.toString('hex'));
console.log(iv.length);
</code>```

Output:
iv: 4cf7620724f7b27347b7765889cf27e1

  iv length: 16

It's very confusing because the output of javascript's pbkdf2 is longer (but you can see the first 16 letters is the same), but their length is the same! Am I missing something on this?

Note:
I can't adjust the PHP code (because that's what they're using), I can only adjust my javascript code (for it to fit to them)

答: The fifth argument to hash_pbkdf2() is $length (16, in your example), but it counts in hexadecimal characters, not bytes. To reproduce that result in Javascript, pass a length of 8, or trim the output to 16 characters after .toString("hex").

Title: PHP hash_pbkdf2 to javascript

Body:
I'm trying to convert the hash_pbkdf2 of PHP to javascript, but their output is not quite the same, I'm using the crypto.pbkdf2Sync of javascript (nodejs) for this.

For this example, the password I've used is: "password"

PHP:

$iv = hash_pbkdf2("sha256", $password, strlen($password), 1000, 16);
echo "iv: " . $iv . "
";
echo "iv length: " . strlen($iv);

Output:
iv: 4cf7620724f7b273

  iv length: 16

Javascript:

var iv = crypto.pbkdf2Sync(password, password.length.toString(), 1000, 16, 'sha256');
console.log(iv.toString('hex'));
console.log(iv.length);

Output:
iv: 4cf7620724f7b27347b7765889cf27e1

  iv length: 16

It's very confusing because the output of javascript's pbkdf2 is longer (but you can see the first 16 letters is the same), but their length is the same! Am I missing something on this?

Note:
I can't adjust the PHP code (because that's what they're using), I can only adjust my javascript code (for it to fit to them)


问:
Set cookie not being detected
I'm running into a problem trying to retrieve a cookie if it is set and if not I want to update it then retrieve it.

To start I have a function that sets a cookie:

```<code>func IndexHandler(w http.ResponseWriter, r *http.Request) {
    ...
    ck := http.Cookie{
        Name: "id",
        Value: 5,
        MaxAge: 60,
    }
}
</code>```

Then in another function I check to see if that cookie exists and if it (throws an error) then I recreate it

```<code>func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        ck := http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }

        http.SetCookie(w, &ck)
        CheckUpdateCookie(w, r)
    }
}
</code>```

This leads to it running into an infinite loop and not recognizing that the cookie has been set again, if I print the err I get http: named cookie not present even though I have set the cookie in the body of the function.

答:
The call to r.Cookie("id") reads a "Cookie" header in the request.

The call to http.SetCookie(w, &ck) adds a "Set-Cookie" header in the response.  The call does not modify the request.

Instead of calling the function recursively to get the cookie (which does not work for the reasons stated above), just use the cookie you have on hand:

```<code>func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        val := &http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }
        http.SetCookie(w, val)
    }
    // val is now set to the cookie.
}
</code>```

It is typical to set the path to "/"  so that the cookie is available on all paths:

```<code>        val := &http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
            Path: "/",
        }
</code>```

Title: Set cookie not being detected

Body:
I'm running into a problem trying to retrieve a cookie if it is set and if not I want to update it then retrieve it.

To start I have a function that sets a cookie:

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    ...
    ck := http.Cookie{
        Name: "id",
        Value: 5,
        MaxAge: 60,
    }
}

Then in another function I check to see if that cookie exists and if it (throws an error) then I recreate it

func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        ck := http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }

        http.SetCookie(w, &ck)
        CheckUpdateCookie(w, r)
    }
}

This leads to it running into an infinite loop and not recognizing that the cookie has been set again, if I print the err I get http: named cookie not present even though I have set the cookie in the body of the function.

Body:
The call to r.Cookie("id") reads a "Cookie" header in the request.

The call to http.SetCookie(w, &ck) adds a "Set-Cookie" header in the response.  The call does not modify the request.

Instead of calling the function recursively to get the cookie (which does not work for the reasons stated above), just use the cookie you have on hand:

func CheckUpdateCookie(w http.ResponseWriter, r *http.Request) {
    val, err := r.Cookie("id")
    if err != nil {
        val := &http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
        }
        http.SetCookie(w, val)
    }
    // val is now set to the cookie.
}

It is typical to set the path to "/"  so that the cookie is available on all paths:

        val := &http.Cookie{
            Name: "id",
            Value: 5,
            MaxAge: 60,
            Path: "/",
        }


问:
C++ mutex in namespace std does not name a type
I'm writing a simple C++ program to demonstrate the use of locks. I am using codeblocks and gnu gcc compiler.

```<code> #include <iostream>
 #include <thread>
 #include <mutex>
 using namespace std;
 int x = 0; // shared variable

 void synchronized_procedure()
 {
    static std::mutex m;
    m.lock();
    x = x + 1;
    if (x < 5)
    {
       cout<<"hello";
    }
    m.unlock();

 }

int main()
{

   synchronized_procedure();
   x=x+2;
   cout<<"x is"<<x;
}
</code>```

I'm getting the following error: mutex in namespace std does not name a type.

Why am I getting this error?
Doesn't the compiler support use of locks?

答:
I got the same error with gcc4.7.7.

After adding "-std=c++0x", it is fixed.

Body:
I'm writing a simple C++ program to demonstrate the use of locks. I am using codeblocks and gnu gcc compiler.

 #include <iostream>
 #include <thread>
 #include <mutex>
 using namespace std;
 int x = 0; // shared variable

 void synchronized_procedure()
 {
    static std::mutex m;
    m.lock();
    x = x + 1;
    if (x < 5)
    {
       cout<<"hello";
    }
    m.unlock();

 }

int main()
{

   synchronized_procedure();
   x=x+2;
   cout<<"x is"<<x;
}

I'm getting the following error: mutex in namespace std does not name a type.

Why am I getting this error?
Doesn't the compiler support use of locks?


问:
Matching regex with keyword in a perl script
perl regex is very powerful while using in text content unfortunately I don't get the output what I have expected with my code by doing wrong matches.

In this matches we have n of matches with MBBS and the keyword practitioner.

Sample Input:

Sample text - There are no statistically significant direct effects of prior behavior on practitioner current crop loss, measured by Mr. Srivatsan MBBS M.D. log of amount of crop loss. Third, although we cover a number and given by Mr. Sankaranarayan MBBS possible explanations for what practitioner determines practitioner of crop loss, it is possible that there may be other unobserved, time-varying household characteristics that influence whether a household experience a crop loss. If that is the case the causality from crop loss to fertility decisions may not hold.

My Code:

```<code>my $txtfile = "sample.txt";

readFileinString($txtfile, \$string);
my $keyword = "practitioner";

if($string=~m/Mr.\s+(\w+)\s+MBBS(.*?)\s+practitioner\s+/i)
{
    print "$&\n";
}
</code>```

Code Output:

```<code>Mr. Srivatsan MBBS M.D. log of amount of crop loss. Third, although we cover a number and given by Mr. Sankaranarayan MBBS possible explanations for what practitioner
</code>```

Expected Output:

```<code>Mr. Sankaranarayan MBBS possible explanations for what practitioner determines practitioner
</code>```

Could someone have any experience doing on this way and provide suggestions please.

答:
(?:(?!STRING).)* is to STRING as [^CHAR]* is to CHAR.

I think you want

```<code>if ($string =~ /(Mr\.\s+(\w+)\s+MBBS(?:(?!MBBS).)*\s+practitioner\s+)/si) {
    print "$1\n";
}
</code>```

You can add to the inner part of (?:(?!MBBS).)*. For example, you might prefer (?:(?!Mr\.|MBBS).)*.

Body:
perl regex is very powerful while using in text content unfortunately I don't get the output what I have expected with my code by doing wrong matches.

In this matches we have n of matches with MBBS and the keyword practitioner.

Sample Input:

Sample text - There are no statistically significant direct effects of prior behavior on practitioner current crop loss, measured by Mr. Srivatsan MBBS M.D. log of amount of crop loss. Third, although we cover a number and given by Mr. Sankaranarayan MBBS possible explanations for what practitioner determines practitioner of crop loss, it is possible that there may be other unobserved, time-varying household characteristics that influence whether a household experience a crop loss. If that is the case the causality from crop loss to fertility decisions may not hold.

My Code:

my $txtfile = "sample.txt";

readFileinString($txtfile, \$string);
my $keyword = "practitioner";

if($string=~m/Mr.\s+(\w+)\s+MBBS(.*?)\s+practitioner\s+/i)
{
    print "$&\n";
}

Code Output:

Mr. Srivatsan MBBS M.D. log of amount of crop loss. Third, although we cover a number and given by Mr. Sankaranarayan MBBS possible explanations for what practitioner

Expected Output:

Mr. Sankaranarayan MBBS possible explanations for what practitioner determines practitioner

Could someone have any experience doing on this way and provide suggestions please.

Body:
(?:(?!STRING).)* is to STRING as [^CHAR]* is to CHAR.

I think you want

if ($string =~ /(Mr\.\s+(\w+)\s+MBBS(?:(?!MBBS).)*\s+practitioner\s+)/si) {
    print "$1\n";
}

You can add to the inner part of (?:(?!MBBS).)*. For example, you might prefer (?:(?!Mr\.|MBBS).)*.


问:
Can't bind to 'dropZones' since it isn't a known property of 'li'
I'm trying to take a component that I built for my app and move parts of it into a stand-alone module.  The component uses ng2-dnd for drag-and-drop support.  It looks like this:

list-editor.component.html

```<code><ul dnd-sortable-container [sortableData]="list" [dropZones]="[id]">
  <li *ngFor="let value of list; index as i"
      dnd-sortable [sortableIndex]="i" [dropZones]="[id]">
    <drag-handle></drag-handle>
    <ng-content></ng-content>
    <action-insert></action-insert>
    <action-delete></action-delete>
  </li>
</ul>
</code>```

I'm missing something apparently, because at run time when parsing the template it is complaining that dropZones is not a property of
.  Notice, it's not complaining about the
, only the
.  Also, note that I took working code and moved it into the module, so it is not something obvious about the component template that is to blame, like a typo.  So I can only assume I have done something wrong in setting up the module.

list-editor.module.ts

```<code>import { NgModule }     from '@angular/core';
import { CommonModule } from '@angular/common';

import { DndModule } from 'ng2-dnd';

import { ListEditorComponent } from './list-editor.component';
import { DragHandleComponent } from './drag-handle/drag-handle.component'
import { ActionComponent }     from './action-button/action.component';
import { InsertComponent }     from './insert-button/insert.component';
import { DeleteComponent }     from './delete-button/delete.component';

@NgModule({
  imports: [
    CommonModule,
    DndModule.forRoot(),
  ],
  declarations: [
    ListEditorComponent,
    ValueComponent,
    DragHandleComponent,
    ActionComponent,
    InsertComponent,
    DeleteComponent
  ],
  exports: [
    ListEditorComponent,
    ValueComponent,
  ]
})
export class ListEditorModule { }
</code>```

I then import it as I do any other module in my app:

app.module.ts

```<code>import { ListEditorModule } from '@module/list-editor/list-editor.module';

@NgModule({
  declarations: [ ... ],
  imports: [ ... , ListEditorModule, ... ],
  ...
})
export class AppModule { ... }
</code>```

And of course, I use it in my app:

```<code><list-editor [list]="theList"><value></list-editor>
</code>```

Am I doing something wrong, or is there a bug in there somewhere?

I just updated to Angular 5.0.5.  The problem is still there.

答:
Just remove [dropZones]   from  li, otherwise it is treating as a input and expecting the li element to have

```<code> <li *ngFor="let value of list; index as i"
      dnd-sortable [sortableIndex]="i" >
</code>```

Body:
I'm trying to take a component that I built for my app and move parts of it into a stand-alone module.  The component uses ng2-dnd for drag-and-drop support.  It looks like this:

list-editor.component.html

    <drag-handle></drag-handle>
    <ng-content></ng-content>
    <action-insert></action-insert>
    <action-delete></action-delete>

I'm missing something apparently, because at run time when parsing the template it is complaining that dropZones is not a property of
.  Notice, it's not complaining about the
, only the
.  Also, note that I took working code and moved it into the module, so it is not something obvious about the component template that is to blame, like a typo.  So I can only assume I have done something wrong in setting up the module.

list-editor.module.ts

import { NgModule }     from '@angular/core';
import { CommonModule } from '@angular/common';

import { DndModule } from 'ng2-dnd';

import { ListEditorComponent } from './list-editor.component';
import { DragHandleComponent } from './drag-handle/drag-handle.component'
import { ActionComponent }     from './action-button/action.component';
import { InsertComponent }     from './insert-button/insert.component';
import { DeleteComponent }     from './delete-button/delete.component';

@NgModule({
  imports: [
    CommonModule,
    DndModule.forRoot(),
  ],
  declarations: [
    ListEditorComponent,
    ValueComponent,
    DragHandleComponent,
    ActionComponent,
    InsertComponent,
    DeleteComponent
  ],
  exports: [
    ListEditorComponent,
    ValueComponent,
  ]
})
export class ListEditorModule { }

I then import it as I do any other module in my app:

app.module.ts

import { ListEditorModule } from '@module/list-editor/list-editor.module';

@NgModule({
  declarations: [ ... ],
  imports: [ ... , ListEditorModule, ... ],
  ...
})
export class AppModule { ... }

And of course, I use it in my app:

<list-editor [list]="theList"><value></list-editor>

Am I doing something wrong, or is there a bug in there somewhere?

I just updated to Angular 5.0.5.  The problem is still there.

Body:
Just remove [dropZones]   from  li, otherwise it is treating as a input and expecting the li element to have

 <li *ngFor="let value of list; index as i"
      dnd-sortable [sortableIndex]="i" >


问:
iPython notebook not working behind VPN
I'm running iPython notebook on my local computer. However, because I am in China, I need to use a VPN (specifically Astrill's OpenWeb protocol) to access most of the internet. On one of my PCs, iPython notebook won't run properly when the VPN is running. For example, when opening my homepage: http://localhost:8888/tree, I see the error message:

```<code>Astrill Error
Connection Closed Gracefully
</code>```

iPython notebook also won't let me open or save workbooks if the VPN is running. Any idea why and how I can fix that?

答:
Try adding localhost to your VPN whitelist. So that the corresponding requests would not be passed to the proxy. If this still does not work, check if you are using global mode of your VPN which might overlook the whitelist config.

whitelist means an address list of direct access, which your VPN would not transfer the corresponding traffic to the proxy address.

Title: iPython notebook not working behind VPN

Body:
I'm running iPython notebook on my local computer. However, because I am in China, I need to use a VPN (specifically Astrill's OpenWeb protocol) to access most of the internet. On one of my PCs, iPython notebook won't run properly when the VPN is running. For example, when opening my homepage: http://localhost:8888/tree, I see the error message:

Astrill Error
Connection Closed Gracefully

iPython notebook also won't let me open or save workbooks if the VPN is running. Any idea why and how I can fix that?


问:
Setting up precision C++
So, i'm attempting to set the precision for input values in my code. I want the values to be printed with two decimal points afterwards of precision though i'm not exactly sure how.

Here's my code.

```<code>#include <iostream>
#include <iomanip>

float uphill, wellD, waterLvl, buckVol;
float buckAscRate, downHill, volume;
float last;
float timeReq;

int scene = 1;

void timeRequired()
{
    std::setw(2);
    std::setprecision(2);

    std::cout << "Scenario " << scene << ":" << std::endl;
    std::cout << "up hill" << "          " << uphill << " sec" << std::endl;
    std::cout << "well diamter" << "          " << wellD << " in" << std::endl;
    std::cout << "water level" << "          " << waterLvl << " in" << std::endl;
    std::cout << "bucket volume" << "          " << buckVol << " cu ft" << std::endl;
    std::cout << "bucket ascent rate" << "          " << buckAscRate << " in/sec" << std::endl;
    std::cout << "down hill" << "          " << downHill << " sec" << std::endl;
    std::cout << "required volume" << "          " << volume << " cu ft" << std::endl;

    timeReq = (uphill + downHill);

    std::cout << "TIME REQUIRED" << "          " << timeReq << " sec" << std::endl;

    std::cout << " " << std::endl;

}

void scenarioCONT()
{
    do
    {
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            uphill = last;
            scenarioCONT();

        }

    } while (last != 0);

}
void scenario()
{
    do
    {
        std::cin >> uphill;
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            timeRequired();
            uphill = last;
            scenarioCONT();

        }
            scene++;
            timeRequired();

    } while (last != 0);

}

int main()
{

    scenario();

    system("pause");
}
</code>```

I've been told to use ionmanip to set the precision, though i'm not 100% on how to do it. Any suggestions?

答:
You can use std::setprecision function. The below example is directly taken from http://www.cplusplus.com/reference/iomanip/setprecision/

```<code>  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
</code>```

Title: Setting up precision C++

Body:
So, i'm attempting to set the precision for input values in my code. I want the values to be printed with two decimal points afterwards of precision though i'm not exactly sure how.

Here's my code.

#include <iostream>
#include <iomanip>

float uphill, wellD, waterLvl, buckVol;
float buckAscRate, downHill, volume;
float last;
float timeReq;

int scene = 1;

void timeRequired()
{
    std::setw(2);
    std::setprecision(2);

    std::cout << "Scenario " << scene << ":" << std::endl;
    std::cout << "up hill" << "          " << uphill << " sec" << std::endl;
    std::cout << "well diamter" << "          " << wellD << " in" << std::endl;
    std::cout << "water level" << "          " << waterLvl << " in" << std::endl;
    std::cout << "bucket volume" << "          " << buckVol << " cu ft" << std::endl;
    std::cout << "bucket ascent rate" << "          " << buckAscRate << " in/sec" << std::endl;
    std::cout << "down hill" << "          " << downHill << " sec" << std::endl;
    std::cout << "required volume" << "          " << volume << " cu ft" << std::endl;

    timeReq = (uphill + downHill);

    std::cout << "TIME REQUIRED" << "          " << timeReq << " sec" << std::endl;

    std::cout << " " << std::endl;

}

void scenarioCONT()
{
    do
    {
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            uphill = last;
            scenarioCONT();

        }

    } while (last != 0);

}
void scenario()
{
    do
    {
        std::cin >> uphill;
        std::cin >> wellD;
        std::cin >> waterLvl;
        std::cin >> buckVol;
        std::cin >> buckAscRate;
        std::cin >> downHill;
        std::cin >> volume;
        std::cin >> last;

        if (uphill <= 1) uphill = 2;
        if (wellD <= 0) wellD = 1;
        if (waterLvl <= 0) waterLvl = 1;
        if (buckVol <= 0) buckVol = 1;
        if (buckAscRate <= 0) buckAscRate = 1;
        if (downHill <= 0) buckAscRate = 1;
        if (volume <= 0) volume = 1;

        if (last > 1)
        {
            timeRequired();
            uphill = last;
            scenarioCONT();

        }
            scene++;
            timeRequired();

    } while (last != 0);

}

int main()
{

    scenario();

    system("pause");
}

I've been told to use ionmanip to set the precision, though i'm not 100% on how to do it. Any suggestions?

Body:
You can use std::setprecision function. The below example is directly taken from http://www.cplusplus.com/reference/iomanip/setprecision/

  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';


问:
Azure B2C AD Redirect to Angular App
I am trying to run this Angular 4 example that uses Azure B2C Active Directory and adal-angular 4.

To run the app, in Azure I created a tenant, registered a the app in AD B2C and added a reply Url of https://localhost:4200.  I then added the app id and tenant to my Angular App.

When I run the app, it correctly redirects to https://login.microsoftonline.com... on load for login. Logging in correctly redirects to https://localhost:4200.

When I log out, there is a problem. The app is redirected to this static logout page which doesn't redirect back to my app.

I tried registering an app in Azure Active Directory (not B2C), moving its config data into my Angular App, and when I run it and a log out it redirects temporarily to this "logging you out" page which redirects back to the app.

The the redirect urls after logout are identical other than the tenant name, only the B2C just dies. This happens in both Chrome and Edge.

I expect that this is not just a difference in functionality between B2C and regular AD. I checked my configurations, but maybe this is something in the Azure portal I missed?

答:
The logout request should include both the "p" and "post_logout_redirect_uri" parameters such as:

```<code>GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/logout?p=b2c_1_sign_up_sign_in&post_logout_redirect_uri=https%3A%2F%2Flocalhost%3A4200%2F
</code>```

If the "post_logout_redirect_uri" parameter isn't specified, then Azure AD B2C displays a generic message.

Title: Azure B2C AD Redirect to Angular App

Body:
The logout request should include both the "p" and "post_logout_redirect_uri" parameters such as:

GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/logout?p=b2c_1_sign_up_sign_in&post_logout_redirect_uri=https%3A%2F%2Flocalhost%3A4200%2F

If the "post_logout_redirect_uri" parameter isn't specified, then Azure AD B2C displays a generic message.


问:
App Engine NO CACHE JSP
I want to disable the cache for a JSP file on my google app engine website.

I have this:

```<code><%
        // Set to expire far in the past.
        response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
%>
</code>```

But the JSP is still in cache. I need to kill the user session and login again in order to reload the JSP code.

How do I disable the cache for a app engine JSP?

答:
It might at that point be too late to change the response headers. They will simply be ignored. You can verify the presence of response headers in a HTTP debugger tool like Firebug.

In the JSP, you need to ensure that they are set before the response is committed (i.e. all headers are already sent; you cannot send another headers afterwards). I.e. ensure that they are in the very top of the JSP file and that no template text is before that piece of scriptlet. Template text may cause a commit of the response. The normal practice, however, is to use a Filter for this.

Implement javax.servlet.Filter wherein doFilter() method look like follows:

```<code>HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache", "no-store", "must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(request, response);
</code>```

Map this in web.xml on an url-pattern of *.jsp and it ought to work.

See also:

Making sure a webpage is not cached, across all browsers

Title: App Engine NO CACHE JSP

Body:
I want to disable the cache for a JSP file on my google app engine website.

I have this:

<%
        // Set to expire far in the past.
        response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
%>

But the JSP is still in cache. I need to kill the user session and login again in order to reload the JSP code.

How do I disable the cache for a app engine JSP?

Body:
It might at that point be too late to change the response headers. They will simply be ignored. You can verify the presence of response headers in a HTTP debugger tool like Firebug.

In the JSP, you need to ensure that they are set before the response is committed (i.e. all headers are already sent; you cannot send another headers afterwards). I.e. ensure that they are in the very top of the JSP file and that no template text is before that piece of scriptlet. Template text may cause a commit of the response. The normal practice, however, is to use a Filter for this.

Implement javax.servlet.Filter wherein doFilter() method look like follows:

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache", "no-store", "must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(request, response);

Map this in web.xml on an url-pattern of *.jsp and it ought to work.

See also:

Making sure a webpage is not cached, across all browsers


问:
How to remove Price from Product Category page?
I want to remove Price from this category page of woocommerce.

I found the single page price code, which is: woocommerce\templates\single-product\price.php

But I can't find the Woocommmerce category pages codes.

I have to remove this price section and add button, which on click will redirect to the next page.

答:
File path

```<code>woocommerce\templates\loop\price.php
</code>```

Remove price code

Body:
File path

woocommerce\templates\loop\price.php

Remove price code


问:
I got this error when install npm
I got this error.

```<code> npm : Depends: node-gyp (>= 0.10.9) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

I have tried many sources. But cant resolve the error. As this error, i have tried to install node-gyp. But at that time it is showing another dependency. So is there any way to install the dependencies at a time ?

答:
Remove the old version of node and npm you have and try using the following steps to install a newer version using node version manager, after that try to install your package. </p>

```<code>//Remove node
sudo apt-get purge --auto-remove nodejs npm

//Remove any leftover files that gives version issues
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp /opt/local/bin/node opt/local/include/node /opt/local/lib/node_modules

//Install nvm, this will install npm 5.4
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

//To uninstall a node version
//nvm uninstall <version>

nvm install <version you want>

nvm use <version you installed>

//check with
node -v
npm -v
</code>```

Title: I got this error when install npm

Body:
I got this error.

 npm : Depends: node-gyp (>= 0.10.9) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I have tried many sources. But cant resolve the error. As this error, i have tried to install node-gyp. But at that time it is showing another dependency. So is there any way to install the dependencies at a time ?

Body:
Remove the old version of node and npm you have and try using the following steps to install a newer version using node version manager, after that try to install your package.

//Remove node
sudo apt-get purge --auto-remove nodejs npm

//Remove any leftover files that gives version issues
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp /opt/local/bin/node opt/local/include/node /opt/local/lib/node_modules

//Install nvm, this will install npm 5.4
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

//To uninstall a node version
//nvm uninstall <version>

nvm install <version you want>

nvm use <version you installed>

//check with
node -v
npm -v