问:
Showing a partial view in a modal popup
I have a partial view called Search.cshtml that I display in /Home/Index.  In this file, I have an HTML form that searches and pulls back /Views/Accounts/Index with the search results.  I want to display those results in the modal popup div that is in the Search view.

When I Click the Search (sumbit input) in the code below I get an empty modal.

I am still a novice when it comes to MVC.  I tried a few different results I found on Stack Overflow, but I haven't been able to find the resolution.  The code below at least gives me a modal pop up, although it is blank.

Am I missing something insanely simple?  I have tried everything in the modal-body below (Html.Action, RenderAction, Partial, RenderPartial) and nothing seems to work.  Also, am I barking up the wrong tree there?

I have a couple screenshots and the code below.

/Home/Index with Search partial view

Empty Search Modal

Search.cshtml

```<code>@model CustomerRelationshipManager.Models.Search

@{ViewBag.Title = "Search";}
@using (Html.BeginForm("Index", "Accounts", new { id = "searchForm" }))
{

<div style="border: solid 1px #ccc; padding: 30px 0 30px 30px; border-radius: 5px;
    width: 325px; margin: auto; display: table;">
    <table>
        <tr>
            <td valign="top">
                Search By:
            </td>
            <td>
                @Html.DropDownList("Search_Type", "Search_Type")
            </td>
        </tr>
        <tr>
            <td valign="top"></td>
            <td>
                @Html.TextBox("Search_String")
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" data-toggle="modal" data-target="#myModal" value="Search" />
            </td>
        </tr>
    </table>
</div>

<div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
                @{Html.Action("Index","Accounts");}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

}

HomeController.cs

```<code>    public ActionResult Search()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Text = "Account Number", Value = "Account_ID" });
        items.Add(new SelectListItem() { Text = "Last Name", Value = "Last_Name" });
        items.Add(new SelectListItem() { Text = "Phone Number", Value = "Phone_Number" });
        ViewBag.Search_Type = items;
        return PartialView();
    }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Search(Search search)
    {

        return PartialView("~/Accounts/Index");
        //return RedirectToAction("Index", "Accounts");
    }
</code>```

AccountController.cs (I want to call Index() from this Controller)

```<code>public ActionResult Index(string Search_Type, string Search_String)
    {
        if (Search_String == null)
        {
            var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact);
            return PartialView(accounts.ToList());
        }
        else
        {
            if (Search_Type == "Account_ID")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact)
                .Where(a => a.Account_ID.ToString() == Search_String);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Last_Name")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Where(b => b.Account_Person.Any(c => c.Person.Last_Name.StartsWith(Search_String)))
                .Include(a => a.Account_Contact)
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Phone_Number")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Contact)
                .Where(b => b.Account_Contact.Any(c => c.Contact.Value == Search_String && c.Contact.Contact_Type.Name.Contains("Phone")))
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else
            {
                var accounts = db.Accounts
                    .Include(a => a.Account_Type)
                    .Include(a => a.Account_Person)
                    .Include(a => a.Account_Address)
                    .Include(a => a.Account_Contact);
                return PartialView(accounts.ToList());
            }
        }
</code>```

Account Index.cshtml (I want to display this in the modal popup)

```<code>@model IEnumerable<CustomerRelationshipManager.Models.Account>

@{
ViewBag.Title = "Home";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>Account #</th>
    <th>Contact Name(s)</th>
    <th>Address</th>
    <th>Contact</th>
</tr>
w2
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Account_ID)
            <span> </span>
        </td>
        <td>
            @foreach (var i in item.Account_Person)
            {
                <span>
                    <b>@Html.DisplayFor(x => i.Person_Type.Name)</b>
                    <br />
                    @Html.DisplayFor(x => i.Person.First_Name)

                    @Html.DisplayFor(x => i.Person.Last_Name)
                </span>
                <br />
            }
        </td>
        <td>
            @foreach (var i in item.Account_Address)
            {
                <span>
                    <b>@Html.DisplayFor(x => i.Address_Type.Name)</b>
                    <br />
                    @Html.DisplayFor(x => i.Address.Address1)
                    <br />
                    @Html.DisplayFor(x => i.Address.Address2)
                    @if (i.Address.Address2 != null)
                    { <br />}
                    @Html.DisplayFor(x => i.Address.City)

                    @Html.DisplayFor(x => i.Address.State)

                    @Html.DisplayFor(x => i.Address.Postal_Code)
                    <br />
                    @Html.DisplayFor(x => i.Address.Country)
                    <br />
                </span>
            }
        </td>
        <td>
            @foreach (var i in item.Account_Contact)
            {
                <span>
                    <b>@Html.DisplayFor(x => i.Contact.Contact_Type.Name)</b>
                    <br />
                    @Html.DisplayFor(x => i.Contact.Value)
                    <br />
                </span>

            }

        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Account_ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.Account_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Account_ID })
        </td>
    </tr>
}
</code>```

答:
With your current code, when user clicks on the submit button, it will do a normal form submit as your submit button is inside a form tag. For your use case, you should be hijacking that normal form submit event using javascript and make an ajax call to your action method where it will use the search_type and search_string parameters to get the filtered data and return a partial view result. This partial view result is the HTML markup you want to display inside the modal dialog. Once your ajax call receives the response from server, update the modal dialog's body content with this response and fire the modal dialog.

```<code>@using (Html.BeginForm("Index", "Accounts", FormMethod.Post, new { id = "searchForm" }))
{
    <div>
        <input type="text" name="Search_String" />
        <input type="submit" id="submit" value="Search" />
    </div>
}
<div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"
                                      data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</code>```

Now have some javascript code, which listen to the submit event on your search form and make stop the normal behavior (normal form submit) and instead do an ajax form submit.

```<code>$(document).ready(function () {

    $('#searchForm').submit(function (e) {
        e.preventDefault();
        var $form = $(this);

        $.post($form.attr("action"), $form.serialize()).done(function (res) {
            $mymodal = $("#myModal");
            //update the modal's body with the response received
            $mymodal.find("div.modal-body").html(res);
            // Show the modal
            $mymodal.modal("show");
        });
    });

});
</code>```

Now you have to make sure that your Index action method returns a partial view (so that it will not execute any layout code, but just that view code).

```<code>[HttpPost]
public ActionResult Index(string Search_Type, string Search_String)
{
    // Your existing filtering code goes here.
    return PartialView(accounts.ToList());
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Showing a partial view in a modal popup

Body:
I have a partial view called Search.cshtml that I display in /Home/Index.  In this file, I have an HTML form that searches and pulls back /Views/Accounts/Index with the search results.  I want to display those results in the modal popup div that is in the Search view.

When I Click the Search (sumbit input) in the code below I get an empty modal.

I am still a novice when it comes to MVC.  I tried a few different results I found on Stack Overflow, but I haven't been able to find the resolution.  The code below at least gives me a modal pop up, although it is blank.

Am I missing something insanely simple?  I have tried everything in the modal-body below (Html.Action, RenderAction, Partial, RenderPartial) and nothing seems to work.  Also, am I barking up the wrong tree there?

I have a couple screenshots and the code below.

/Home/Index with Search partial view

Empty Search Modal

Search.cshtml

@model CustomerRelationshipManager.Models.Search

@{ViewBag.Title = "Search";}
@using (Html.BeginForm("Index", "Accounts", new { id = "searchForm" }))
{

                Search By:

                @Html.DropDownList("Search_Type", "Search_Type")

                @Html.TextBox("Search_String")

                <input type="submit" data-toggle="modal" data-target="#myModal" value="Search" />

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

                @{Html.Action("Index","Accounts");}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

}

HomeController.cs

    public ActionResult Search()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Text = "Account Number", Value = "Account_ID" });
        items.Add(new SelectListItem() { Text = "Last Name", Value = "Last_Name" });
        items.Add(new SelectListItem() { Text = "Phone Number", Value = "Phone_Number" });
        ViewBag.Search_Type = items;
        return PartialView();
    }

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Search(Search search)
    {

        return PartialView("~/Accounts/Index");
        //return RedirectToAction("Index", "Accounts");
    }

AccountController.cs (I want to call Index() from this Controller)

public ActionResult Index(string Search_Type, string Search_String)
    {
        if (Search_String == null)
        {
            var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact);
            return PartialView(accounts.ToList());
        }
        else
        {
            if (Search_Type == "Account_ID")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Address)
                .Include(a => a.Account_Contact)
                .Where(a => a.Account_ID.ToString() == Search_String);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Last_Name")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Where(b => b.Account_Person.Any(c => c.Person.Last_Name.StartsWith(Search_String)))
                .Include(a => a.Account_Contact)
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else if (Search_Type == "Phone_Number")
            {
                var accounts = db.Accounts
                .Include(a => a.Account_Type)
                .Include(a => a.Account_Person)
                .Include(a => a.Account_Contact)
                .Where(b => b.Account_Contact.Any(c => c.Contact.Value == Search_String && c.Contact.Contact_Type.Name.Contains("Phone")))
                .Include(a => a.Account_Address);
                return PartialView(accounts.ToList());
            }
            else
            {
                var accounts = db.Accounts
                    .Include(a => a.Account_Type)
                    .Include(a => a.Account_Person)
                    .Include(a => a.Account_Address)
                    .Include(a => a.Account_Contact);
                return PartialView(accounts.ToList());
            }
        }

Account Index.cshtml (I want to display this in the modal popup)

@model IEnumerable<CustomerRelationshipManager.Models.Account>

@{
ViewBag.Title = "Home";
}

Index

@Html.ActionLink("Create New", "Create")

    Account #
    Contact Name(s)
    Address
    Contact

w2
@foreach (var item in Model)
{

            @Html.DisplayFor(modelItem => item.Account_ID)

            @foreach (var i in item.Account_Person)
            {

                    @Html.DisplayFor(x => i.Person_Type.Name)

                    @Html.DisplayFor(x => i.Person.First_Name)

                    @Html.DisplayFor(x => i.Person.Last_Name)

            }

            @foreach (var i in item.Account_Address)
            {

                    @Html.DisplayFor(x => i.Address_Type.Name)

                    @Html.DisplayFor(x => i.Address.Address1)

                    @Html.DisplayFor(x => i.Address.Address2)
                    @if (i.Address.Address2 != null)
                    {
}
                    @Html.DisplayFor(x => i.Address.City)

                    @Html.DisplayFor(x => i.Address.State)

                    @Html.DisplayFor(x => i.Address.Postal_Code)

                    @Html.DisplayFor(x => i.Address.Country)

            }

            @foreach (var i in item.Account_Contact)
            {

                    @Html.DisplayFor(x => i.Contact.Contact_Type.Name)

                    @Html.DisplayFor(x => i.Contact.Value)

            }

            @Html.ActionLink("Edit", "Edit", new { id = item.Account_ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.Account_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Account_ID })

}

Body:
With your current code, when user clicks on the submit button, it will do a normal form submit as your submit button is inside a form tag. For your use case, you should be hijacking that normal form submit event using javascript and make an ajax call to your action method where it will use the search_type and search_string parameters to get the filtered data and return a partial view result. This partial view result is the HTML markup you want to display inside the modal dialog. Once your ajax call receives the response from server, update the modal dialog's body content with this response and fire the modal dialog.

@using (Html.BeginForm("Index", "Accounts", FormMethod.Post, new { id = "searchForm" }))
{
    <div>
        <input type="text" name="Search_String" />
        <input type="submit" id="submit" value="Search" />
    </div>
}
<div class="modal fade" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"
                                      data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Now have some javascript code, which listen to the submit event on your search form and make stop the normal behavior (normal form submit) and instead do an ajax form submit.

$(document).ready(function () {

    $('#searchForm').submit(function (e) {
        e.preventDefault();
        var $form = $(this);

        $.post($form.attr("action"), $form.serialize()).done(function (res) {
            $mymodal = $("#myModal");
            //update the modal's body with the response received
            $mymodal.find("div.modal-body").html(res);
            // Show the modal
            $mymodal.modal("show");
        });
    });

});

Now you have to make sure that your Index action method returns a partial view (so that it will not execute any layout code, but just that view code).

[HttpPost]
public ActionResult Index(string Search_Type, string Search_String)
{
    // Your existing filtering code goes here.
    return PartialView(accounts.ToList());
}


来源: stackexchange

问:
Finding two associated indexes where the sum of two elements equals a target value
Background:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Question:

I have a list of numbers 1,2,3,4,5. My target value is 8, so I should return indices  2 and 4. My first thought is to write a a double for loop that checks to see if adding two elements from the list will get my target value. Although, when checking to see if there is such a solution, my code returns that there is none.

Here is my code:

```<code>#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);
    list.push_back(5);

    int target = 8;

    string result;
    for(int i = 0; i < list.size(); i++) {
        for(int j = i+1; j < list.size(); j++) {
            if(list[i] + list[j] == target) {
                result = "There is a solution";
            }
            else {
                result = "There is no solution";
            }
        }

    }

    cout << result << endl;

    return 0;
}
</code>```

Perhaps my approach/thinking is plain wrong. Could anyone provide any hints or suggestions to solving this problem?

答:
You're doing this in n^2 time. Solve it in linear time by hashing each element, and checking each element to see if it's complement wrt. the total you're trying to achieve is in the hash.

E.g., for  1,2,3,4,5, with a target of 8

```<code>indx 0, val 1: 7 isn't in the map; H[1] = 0
indx 1, val 2: 6 isn't in the map, H[2] = 1
indx 2, val 3: 5 isn't in the map, H[3] = 2
indx 3, val 4: 4 isn't in the map, H[4] = 3
indx 4, val 5: 3 is in the map. H[3] = 2. Return 2,4
</code>```

Code, as requested (Ruby)

```<code>def get_indices(arr, target)
    value_to_index = {}
    arr.each_with_index do |val, index|
        if value_to_index.has_key?(target - val)
            return [value_to_index[target - val], index]
        end
        value_to_index[val] = index
    end
end

get_indices([1,2,3,4,5], 8)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Background:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Question:

I have a list of numbers 1,2,3,4,5. My target value is 8, so I should return indices  2 and 4. My first thought is to write a a double for loop that checks to see if adding two elements from the list will get my target value. Although, when checking to see if there is such a solution, my code returns that there is none.

Here is my code:

#include <iostream>
#include <vector>
using namespace std;

int main() {

    vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    list.push_back(4);
    list.push_back(5);

    int target = 8;

    string result;
    for(int i = 0; i < list.size(); i++) {
        for(int j = i+1; j < list.size(); j++) {
            if(list[i] + list[j] == target) {
                result = "There is a solution";
            }
            else {
                result = "There is no solution";
            }
        }

    }

    cout << result << endl;

    return 0;
}

Perhaps my approach/thinking is plain wrong. Could anyone provide any hints or suggestions to solving this problem?

Body:
You're doing this in n^2 time. Solve it in linear time by hashing each element, and checking each element to see if it's complement wrt. the total you're trying to achieve is in the hash.

E.g., for  1,2,3,4,5, with a target of 8

indx 0, val 1: 7 isn't in the map; H[1] = 0
indx 1, val 2: 6 isn't in the map, H[2] = 1
indx 2, val 3: 5 isn't in the map, H[3] = 2
indx 3, val 4: 4 isn't in the map, H[4] = 3
indx 4, val 5: 3 is in the map. H[3] = 2. Return 2,4

Code, as requested (Ruby)

def get_indices(arr, target)
    value_to_index = {}
    arr.each_with_index do |val, index|
        if value_to_index.has_key?(target - val)
            return [value_to_index[target - val], index]
        end
        value_to_index[val] = index
    end
end

get_indices([1,2,3,4,5], 8)


问:
Center form in div and styling form
Trying to do a few things ran into a snag. Trying to center the form where it asks for email and there is the 'lets talk' button. It should be centered right underneath the title "Lets get in touch"

I also want to give it a drop shadow however what i have is not working.

It should look like this in the end

here is a fiddle with my code: https://jsfiddle.net/vcx4vm39/

Here is all the css that is effecting the form.

```<code>form{
 display: table;
margin: 0 auto;
}

#forth{
width: 100%

}

input[type=text], select {
width: 400px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
/*     border: 1px solid #ccc; */
border-radius: 30px;
box-sizing: border-box;
font-family: proxima nova;

font-size: 14px;

position: absolute;

-webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);

}

input[type=submit] {
width: 160px;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 30px;
cursor: pointer;
background-color: #0B315C;
font-family: proxima nova;
font-size: 14px;
font-weight: bold;
position: absolute;
margin: -10px 0px 0px 240px;

}
</code>```

答:
Removed, most of the not necessary code from the fiddle. And you can see it's in the center now.

EDIT: Credit for the box-shadow, goes to the second answer.

@import url('https://fonts.googleapis.com/css?family=Roboto');
@import url('https://fonts.googleapis.com/css?family=Roboto:bold');
@import url('https://fonts.googleapis.com/css?family=Roboto:100');
@import url('https://fonts.googleapis.com/css?family=Roboto:600');
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  top: 0;
  background-image: url('images/bg.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.logo {
  width: 150px;
  fill: white;
  display: block;
  position: relative;
  padding: 23px 0px 0px 50px;
}

.logo svg {
  position: absolute;
  top: 0px;
  right: 0px;
}

#hireus {
  position: absolute;
  top: 0;
  right: 0;
  padding: 3px;
  font-family: proxima nova;
  font-size: 12px;
  text-decoration: none;
  color: white;
  margin: 27px 50px 0px 0px;
  text-decoration: none;
  z-index: 10;
}

.intro {
  height: 100%;
  width: 100%;
  margin: auto;
  display: table;
  /*
 top: 0;
 background-image: url('images/bg.png');
 background-size: cover;
 background-position: center;
    background-repeat: no-repeat;
*/
}

.intro .inner {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
  max-width: none;
}

ul {
  list-style-type: none;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0.8;
  display: table;
  margin: 0;
  width: 100%;
  text-align: center;
  padding: 0
}

li {
  /*
 width: 120px;
 height: 40px;
*/
  margin: 0px 0px;
  display: inline-block;
  padding: 0;
  font-family: proxima nova;
  font-size: 10px;
  text-decoration: none;
}

.new a {
  display: block;
  /*
 width: 120px;
 height: 40px;
*/
  /*  line-height: 40px; */
  text-decoration: none;
  text-align: center;
  color: white;
  /*  margin: 20px 20px; */
  margin: 32px 20px 0px 20px;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
  text-align: center;
  padding-bottom: 7%;
}

.content h1 {
  font-family: proxima nova;
  font-size: 520%;
  font-weight: bold;
  color: white;
  margin: 0;
  padding-bottom: 3px;
}

.content p {
  font-family: proxima nova;
  font-size: 12px;
  font-weight: 100;
  color: white;
  margin: 0 auto;
  max-width: 420px;
  padding-bottom: 25px;
}

.btn {
  font-family: proxima nova;
  font-size: 14px;
  font-weight: bold;
  color: white;
  text-decoration: none;
  border: solid 1px white;
  /*  padding: 10px 100px; */
  border-radius: 60px;
  transition: all 0.5s;
  width: 160px;
  display: inline-block;
  text-align: center;
  padding-top: 13px;
  padding-bottom: 13px;
}

.btn:hover {
  color: #b0ccff;
  border: solid 1px #b0ccff;
}

.btn2 {
  font-family: proxima nova;
  font-size: 14px;
  font-weight: bold;
  color: white;
  text-decoration: none;
  border: solid 1px #0B315C;
  /*  padding: 10px 100px; */
  border-radius: 60px;
  transition: all 0.5s;
  width: 160px;
  background-color: #0B315C;
  display: inline-block;
  text-align: center;
  padding-top: 13px;
  padding-bottom: 13px;
  margin-left: 30px;
  -webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}

.btn2:hover {
  color: #b0ccff;
  border: solid 1px #b0ccff;
}

#scroll {
  color: green;
}

.title {
  font-family: proxima nova;
  font-size: 50px;
  font-weight: 600;
  color: black;
  text-align: center;
  margin-top: 60px;
  padding-bottom: 2px;
}

.subtitle {
  font-family: proxima nova;
  font-size: 12px;
  font-weight: 200;
  color: #9D9D9D;
  text-align: center;
  margin-top: -45px;
  padding-bottom: 2px;
}

#second {
  border-bottom: 1px solid #E6E6E6;
  width: 480px;
  margin: auto;
}

#Layer_1 {
  width: 100px;
  height: 100px;
}

#group2 {}

.whatwedo {
  text-align: center;
  width: 100%;
  margin-top: 100px;
}

.subject {
  text-align: center;
  width: 300px;
  display: inline-block;
  margin: 0px 50px;
}

.subject h2 {
  font-family: proxima nova;
  font-size: 20px;
  font-weight: 600;
  color: black;
  margin-bottom: 12px;
}

.desc {
  font-family: proxima nova;
  font-size: 12px;
  font-weight: 200;
  color: #9D9D9D;
}

.group3 {
  position: relative;
  text-align: center;
  color: white;
  margin-top: 90px;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-family: proxima nova;
  font-size: 24px;
  font-weight: 100;
  color: white;
  width: 550px;
}

form {
  display: table;
  margin: 0 auto;
}

#forth {
  width: 100%
}

input[type=text],
select {
  width: 400px;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  /*     border: 1px solid #ccc; */
  border-radius: 30px;
  box-sizing: border-box;
  font-family: proxima nova;
  font-size: 14px;
  -webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}

input[type=submit] {
  width: 160px;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  background-color: #0B315C;
  font-family: proxima nova;
  font-size: 14px;
  font-weight: bold;
  position: relative;
  bottom: 42px;
  margin: -10px 0px 0px 240px;
}

.email-form {
  width: 400px;
}

.email-form input {
  border: 0;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}

/*--- Media Queries --*/

@media screen and (max-width: 900px) {
  .content {
    padding-bottom: 10%;
  }
  .content h1 {
    font-size: 400%
  }
  .btn {
    font-size: 110%;
    padding: 9px 43px;
  }
}

@media screen and (max-width: 768px) {
  .content {
    padding-bottom: 12%;
  }
  .content h1 {
    font-size: 300%
  }
  .btn {
    font-size: 100%;
    padding: 9px 43px;
  }
}

@media screen and (max-width: 480px) {
  .content {
    padding-bottom: 14%;
  }
  .content h1 {
    font-size: 300%
  }
  .btn {
    font-size: 100%;
    padding: 10px 44px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<div id="forth">
  <h2 class="title">Lets get in touch</h2>
  <form action="mailto:contact@madebylaunchpad.com" method="post" enctype="text/plain" class="email-form">
    <input type="text" name="mail" placeholder="Your email address"><br>
    <input type="submit" value="Lets talk">
  </form>
</div></code>```

```<code>input[type=text], select {
//remove position:absolute;
}

input[type=submit] {
    position:relative;
  bottom:44px;
}
</code>```

Title: Center form in div and styling form

Body:
Trying to do a few things ran into a snag. Trying to center the form where it asks for email and there is the 'lets talk' button. It should be centered right underneath the title "Lets get in touch"

I also want to give it a drop shadow however what i have is not working.

It should look like this in the end

here is a fiddle with my code: https://jsfiddle.net/vcx4vm39/

Here is all the css that is effecting the form.

form{
 display: table;
margin: 0 auto;
}

#forth{
width: 100%

}

input[type=text], select {
width: 400px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
/*     border: 1px solid #ccc; */
border-radius: 30px;
box-sizing: border-box;
font-family: proxima nova;

font-size: 14px;

position: absolute;

-webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
-moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);

}

input[type=submit] {
width: 160px;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 30px;
cursor: pointer;
background-color: #0B315C;
font-family: proxima nova;
font-size: 14px;
font-weight: bold;
position: absolute;
margin: -10px 0px 0px 240px;

}

Body:
Removed, most of the not necessary code from the fiddle. And you can see it's in the center now.

EDIT: Credit for the box-shadow, goes to the second answer.

@import url('https://fonts.googleapis.com/css?family=Roboto');
@import url('https://fonts.googleapis.com/css?family=Roboto:bold');
@import url('https://fonts.googleapis.com/css?family=Roboto:100');
@import url('https://fonts.googleapis.com/css?family=Roboto:600');
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  top: 0;
  background-image: url('images/bg.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.logo {
  width: 150px;
  fill: white;
  display: block;
  position: relative;
  padding: 23px 0px 0px 50px;
}

.logo svg {
  position: absolute;
  top: 0px;
  right: 0px;
}

#hireus {
  position: absolute;
  top: 0;
  right: 0;
  padding: 3px;
  font-family: proxima nova;
  font-size: 12px;
  text-decoration: none;
  color: white;
  margin: 27px 50px 0px 0px;
  text-decoration: none;
  z-index: 10;
}

.intro {
  height: 100%;
  width: 100%;
  margin: auto;
  display: table;
  /*
 top: 0;
 background-image: url('images/bg.png');
 background-size: cover;
 background-position: center;
    background-repeat: no-repeat;
*/
}

.intro .inner {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
  max-width: none;
}

ul {
  list-style-type: none;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0.8;
  display: table;
  margin: 0;
  width: 100%;
  text-align: center;
  padding: 0
}

li {
  /*
 width: 120px;
 height: 40px;
*/
  margin: 0px 0px;
  display: inline-block;
  padding: 0;
  font-family: proxima nova;
  font-size: 10px;
  text-decoration: none;
}

.new a {
  display: block;
  /*
 width: 120px;
 height: 40px;
*/
  /*  line-height: 40px; */
  text-decoration: none;
  text-align: center;
  color: white;
  /*  margin: 20px 20px; */
  margin: 32px 20px 0px 20px;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
  text-align: center;
  padding-bottom: 7%;
}

.content h1 {
  font-family: proxima nova;
  font-size: 520%;
  font-weight: bold;
  color: white;
  margin: 0;
  padding-bottom: 3px;
}

.content p {
  font-family: proxima nova;
  font-size: 12px;
  font-weight: 100;
  color: white;
  margin: 0 auto;
  max-width: 420px;
  padding-bottom: 25px;
}

.btn {
  font-family: proxima nova;
  font-size: 14px;
  font-weight: bold;
  color: white;
  text-decoration: none;
  border: solid 1px white;
  /*  padding: 10px 100px; */
  border-radius: 60px;
  transition: all 0.5s;
  width: 160px;
  display: inline-block;
  text-align: center;
  padding-top: 13px;
  padding-bottom: 13px;
}

.btn:hover {
  color: #b0ccff;
  border: solid 1px #b0ccff;
}

.btn2 {
  font-family: proxima nova;
  font-size: 14px;
  font-weight: bold;
  color: white;
  text-decoration: none;
  border: solid 1px #0B315C;
  /*  padding: 10px 100px; */
  border-radius: 60px;
  transition: all 0.5s;
  width: 160px;
  background-color: #0B315C;
  display: inline-block;
  text-align: center;
  padding-top: 13px;
  padding-bottom: 13px;
  margin-left: 30px;
  -webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}

.btn2:hover {
  color: #b0ccff;
  border: solid 1px #b0ccff;
}

#scroll {
  color: green;
}

.title {
  font-family: proxima nova;
  font-size: 50px;
  font-weight: 600;
  color: black;
  text-align: center;
  margin-top: 60px;
  padding-bottom: 2px;
}

.subtitle {
  font-family: proxima nova;
  font-size: 12px;
  font-weight: 200;
  color: #9D9D9D;
  text-align: center;
  margin-top: -45px;
  padding-bottom: 2px;
}

#second {
  border-bottom: 1px solid #E6E6E6;
  width: 480px;
  margin: auto;
}

#Layer_1 {
  width: 100px;
  height: 100px;
}

#group2 {}

.whatwedo {
  text-align: center;
  width: 100%;
  margin-top: 100px;
}

.subject {
  text-align: center;
  width: 300px;
  display: inline-block;
  margin: 0px 50px;
}

.subject h2 {
  font-family: proxima nova;
  font-size: 20px;
  font-weight: 600;
  color: black;
  margin-bottom: 12px;
}

.desc {
  font-family: proxima nova;
  font-size: 12px;
  font-weight: 200;
  color: #9D9D9D;
}

.group3 {
  position: relative;
  text-align: center;
  color: white;
  margin-top: 90px;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-family: proxima nova;
  font-size: 24px;
  font-weight: 100;
  color: white;
  width: 550px;
}

form {
  display: table;
  margin: 0 auto;
}

#forth {
  width: 100%
}

input[type=text],
select {
  width: 400px;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  /*     border: 1px solid #ccc; */
  border-radius: 30px;
  box-sizing: border-box;
  font-family: proxima nova;
  font-size: 14px;
  -webkit-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 20px black rgba(0, 0, 0, 0.5);
}

input[type=submit] {
  width: 160px;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  background-color: #0B315C;
  font-family: proxima nova;
  font-size: 14px;
  font-weight: bold;
  position: relative;
  bottom: 42px;
  margin: -10px 0px 0px 240px;
}

.email-form {
  width: 400px;
}

.email-form input {
  border: 0;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}

/*--- Media Queries --*/

@media screen and (max-width: 900px) {
  .content {
    padding-bottom: 10%;
  }
  .content h1 {
    font-size: 400%
  }
  .btn {
    font-size: 110%;
    padding: 9px 43px;
  }
}

@media screen and (max-width: 768px) {
  .content {
    padding-bottom: 12%;
  }
  .content h1 {
    font-size: 300%
  }
  .btn {
    font-size: 100%;
    padding: 9px 43px;
  }
}

@media screen and (max-width: 480px) {
  .content {
    padding-bottom: 14%;
  }
  .content h1 {
    font-size: 300%
  }
  .btn {
    font-size: 100%;
    padding: 10px 44px;
  }
}

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<div id="forth">
  <h2 class="title">Lets get in touch</h2>
  <form action="mailto:contact@madebylaunchpad.com" method="post" enctype="text/plain" class="email-form">
    <input type="text" name="mail" placeholder="Your email address"><br>
    <input type="submit" value="Lets talk">
  </form>
</div>

input[type=text], select {
//remove position:absolute;
}

input[type=submit] {
    position:relative;
  bottom:44px;
}


问:
numpy/pandas NaN difference confusion
I happened onto this when trying to find the means/sums of non-nan elements in rows of a pandas dataframe. It seems that

```<code>df.apply(np.mean, axis=1)
</code>```

works fine.

However, applying np.mean to a numpy array containing nans returns a nan.

Is this all speced out somewhere? I would not want to get burned down the road...

答:
numpy's mean function first checks whether its input has a mean method, as @EdChum explains in this answer.

When you use df.apply, the input passed to the function is a pandas.Series. Since pandas.Series has a mean method, numpy uses that instead of using its own function. And by default, pandas.Series.mean ignores NaN.

You can access the underlying numpy array by the values attribute and pass that to the function:

```<code>df.apply(lambda x: np.mean(x.values), axis=1)
</code>```

this will use numpy's version.

Title: numpy/pandas NaN difference confusion

Body:
I happened onto this when trying to find the means/sums of non-nan elements in rows of a pandas dataframe. It seems that

df.apply(np.mean, axis=1)

works fine.

However, applying np.mean to a numpy array containing nans returns a nan.

Is this all speced out somewhere? I would not want to get burned down the road...

Body:
numpy's mean function first checks whether its input has a mean method, as @EdChum explains in this answer.

When you use df.apply, the input passed to the function is a pandas.Series. Since pandas.Series has a mean method, numpy uses that instead of using its own function. And by default, pandas.Series.mean ignores NaN.

You can access the underlying numpy array by the values attribute and pass that to the function:

df.apply(lambda x: np.mean(x.values), axis=1)

this will use numpy's version.


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

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

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

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

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

what's an efficient way to do this?

答:
This will give you the data structure to get what you want:

```<code>input = ['A',1,2,3,'B',4,5,'C',6,7,8,9]
letter = None
output = []
for i in input:
    if type(i) is type(''):
        letter = i
    elif type(i) is type(0) and letter is not None:
        output.append((letter, i))
print(output)
</code>```

Output now has a sequence of tuples, paired as you wish. I don't use pandas.

Body:
I have a pandas DataFrame like this:

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

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

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

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

what's an efficient way to do this?

Body:
This will give you the data structure to get what you want:

input = ['A',1,2,3,'B',4,5,'C',6,7,8,9]
letter = None
output = []
for i in input:
    if type(i) is type(''):
        letter = i
    elif type(i) is type(0) and letter is not None:
        output.append((letter, i))
print(output)

Output now has a sequence of tuples, paired as you wish. I don't use pandas.


问:
Why doesn't bar button change back to blue?
I have a '+' button in my main page of my app. It is a UIBarButtonItem. I don't do anything with it in code, only connect it to another view controller in storyboard with segue. The button starts out with its normal blue color. After I dismiss the view controller that was segued to, the bar button item appears gray for some reason. Does anyone know why? Like I said, I do nothing with it in code(nothing connected to the bar button).

EDIT: My main view controller has the '+' bar button, and I segue to a popover. That popover then segues to another controller. When that view controller dismisses, I return straight back to the home screen without actually dismissing the first popover. So, I think it's still a part of the navigation stack. Is this information helpful?

答:
Special thanks to @matt for helping me with this issue.

It seems like this is a bug in iOS, as shown in this answer.


问:
Hide img carousel box if empty
How do I hide the div if the user only select 9 images and what I want is to hide other image div or else it will appear a blank box if no image is added. It is a carousel.</p>

```<code><h2><?php echo $title ?></h2>

<!-- Swiper -->

<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"><img style="width:100%; height:100%" src="
<?php echo $Image_Input_1 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%" src="
<?php echo $Image_Input_2 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_3 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_4 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_5 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_6 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_7 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_8 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_9 ?>"></div>

<div class="swiper-slide"><img style="width:100%; height:100%"
src="<?php echo $Image_Input_10 ?>"></div>
</div>

<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</code>```

答:
Just put your images in array and loop it using foreach

Here's how you do it:

Put your images in array

```<code>$image_inputs = array(
    $Image_Input_1,
    $Image_Input_2,
    $Image_Input_3,
    $Image_Input_4,
    $Image_Input_5,
    $Image_Input_6,
    $Image_Input_7,
    $Image_Input_8,
    $Image_Input_9,
    $Image_Input_10
);
</code>```

And loop it using foreach

```<code><?php foreach($image_inputs as $image):?>
<div class="swiper-slide">
    <img style="width:100%; height:100%; <?php echo (empty($image) ? 'display:none;' : ''); ?> " src="<?php echo $image; ?>">
</div>
<?php endforeach; ?>
</code>```

Here is the whole code

```<code><?php

$image_inputs = array(
    $Image_Input_1,
    $Image_Input_2,
    $Image_Input_3,
    $Image_Input_4,
    $Image_Input_5,
    $Image_Input_6,
    $Image_Input_7,
    $Image_Input_8,
    $Image_Input_9,
    $Image_Input_10
);
?>

<div class="swiper-container">
<div class="swiper-wrapper">

  <?php foreach($image_inputs as $image):?>
  <?php if(empty($image)){ }else{ ?>
  <?php echo '<div class="swiper-slide"><img style="width:100%;
  height:100%" src="'.$image.'"></div>';}  ?>

<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</code>```

Title: Hide img carousel box if empty

Body:
How do I hide the div if the user only select 9 images and what I want is to hide other image div or else it will appear a blank box if no image is added. It is a carousel.

<?php echo $title ?>

<img style="width:100%; height:100%" src="
<?php echo $Image_Input_1 ?>">

<img style="width:100%; height:100%" src="
<?php echo $Image_Input_2 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_3 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_4 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_5 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_6 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_7 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_8 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_9 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_10 ?>">

Body:
Just put your images in array and loop it using foreach

Here's how you do it:

Put your images in array

$image_inputs = array(
    $Image_Input_1,
    $Image_Input_2,
    $Image_Input_3,
    $Image_Input_4,
    $Image_Input_5,
    $Image_Input_6,
    $Image_Input_7,
    $Image_Input_8,
    $Image_Input_9,
    $Image_Input_10
);

And loop it using foreach

<?php foreach($image_inputs as $image):?>
<div class="swiper-slide">
    <img style="width:100%; height:100%; <?php echo (empty($image) ? 'display:none;' : ''); ?> " src="<?php echo $image; ?>">
</div>
<?php endforeach; ?>

Here is the whole code

<?php

$image_inputs = array(
    $Image_Input_1,
    $Image_Input_2,
    $Image_Input_3,
    $Image_Input_4,
    $Image_Input_5,
    $Image_Input_6,
    $Image_Input_7,
    $Image_Input_8,
    $Image_Input_9,
    $Image_Input_10
);
?>

<div class="swiper-container">
<div class="swiper-wrapper">

  <?php foreach($image_inputs as $image):?>
  <?php if(empty($image)){ }else{ ?>
  <?php echo '<div class="swiper-slide"><img style="width:100%;
  height:100%" src="'.$image.'"></div>';}  ?>

<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>


答:
Check out this updated fiddle: https://jsfiddle.net/vcx4vm39/2/

Added the class .email-form to the form and added the following CSS:

```<code>.email-form {
    width: 400px;
}

.email-form input {
    border: 0;
    box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}
</code>```

Title: Center form in div and styling form

Body:
Check out this updated fiddle: https://jsfiddle.net/vcx4vm39/2/

Added the class .email-form to the form and added the following CSS:

.email-form {
    width: 400px;
}

.email-form input {
    border: 0;
    box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
}


问:
Can I optimise this further so that it runs faster?
As you can see in the following pprof output, I have these nested for loops which take most of the time of my program. Source is in golang but code is explained below:

```<code>  8.55mins    1.18hrs     20:   for k := range mapSource {
  4.41mins    1.20hrs     21:           if positions, found := mapTarget[k]; found {
         .          .     22:                   // save all matches
  1.05mins   1.05mins     23:                   for _, targetPos := range positions {
  2.25mins   2.33mins     24:                           for _, sourcePos := range mapSource[k] {
     1.28s     15.78s     25:                                   matches = append(matches, match{int32(targetPos), int32(sourcePos)})
         .          .     26:                           }
         .          .     27:                   }
         .          .     28:           }
         .          .     29:   }
</code>```

At the moment the structures I'm using are 2 map[int32][]int32, targetMap and sourceMap.

These maps contain, for a given key, an array of ints. Now I want to find the keys that match in both maps, and save the combinations of the elements in the arrays.

So for example:

```<code>sourceMap[1] = [3,4]
sourceMap[5] = [9,10]

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

The only key in common is 1 and the result will be [(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]

Is there any possible way (a more appropriate data structure or whatever) that could improve the speed of my program?

In my case, maps can contain somewhere between 1000 and 150000 keys, while the arrays inside are usually pretty small.

EDIT: Concurrency is not an option as this is already being run several times in several threads at the same time.

答:
At first I was thinking:

Calculate keys in common in one batch, and calculate the final slice size.

Make slice with capacity that step 1 calculated.

Append one by one.

Then next structure, but it would not generate final result as array, but all the append work would be just link the node.

```<code>type node struct {
    val    int
    parent *node
    next   *node
    child  *node
}

type tree struct {
    root  *node
    level int
}

var sourceMap map[int]*tree
</code>```

Body:
As you can see in the following pprof output, I have these nested for loops which take most of the time of my program. Source is in golang but code is explained below:

  8.55mins    1.18hrs     20:   for k := range mapSource {
  4.41mins    1.20hrs     21:           if positions, found := mapTarget[k]; found {
         .          .     22:                   // save all matches
  1.05mins   1.05mins     23:                   for _, targetPos := range positions {
  2.25mins   2.33mins     24:                           for _, sourcePos := range mapSource[k] {
     1.28s     15.78s     25:                                   matches = append(matches, match{int32(targetPos), int32(sourcePos)})
         .          .     26:                           }
         .          .     27:                   }
         .          .     28:           }
         .          .     29:   }

At the moment the structures I'm using are 2 map[int32][]int32, targetMap and sourceMap.

These maps contain, for a given key, an array of ints. Now I want to find the keys that match in both maps, and save the combinations of the elements in the arrays.

So for example:

sourceMap[1] = [3,4]
sourceMap[5] = [9,10]

targetMap[1] = [1,2,3]
targetMap[2] = [2,3]
targetMap[3] = [1,2]

The only key in common is 1 and the result will be [(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]

Is there any possible way (a more appropriate data structure or whatever) that could improve the speed of my program?

In my case, maps can contain somewhere between 1000 and 150000 keys, while the arrays inside are usually pretty small.

EDIT: Concurrency is not an option as this is already being run several times in several threads at the same time.

Body:
At first I was thinking:

Calculate keys in common in one batch, and calculate the final slice size.

Make slice with capacity that step 1 calculated.

Append one by one.

Then next structure, but it would not generate final result as array, but all the append work would be just link the node.

type node struct {
    val    int
    parent *node
    next   *node
    child  *node
}

type tree struct {
    root  *node
    level int
}

var sourceMap map[int]*tree


问:
How to add value base on specific character ,also fix with certain digits in R
There is the basic width : xxxx.xxxxxx (4digits before "." 6 digits after".")

Have to add "0" when each side before and after "." is not enough digits.

Use regexr find "[.]" location with combination of str_pad can
fix the first 4 digits but

don't know how to add value after the specific character with fixed digits.
(cannot find a library can count the location from somewhere specified)

Data like this

```<code>> df
         Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402
</code>```

Desired data

```<code>> df
         Category
1      0300.030340
2      3400.040290
3      0700.070110
4      1700.090100
5      0700.070114
6      0700.079100
7      3600.050590
8      4400.040200
</code>```

I am beginner of coding that sometime can't understand some regex like "["
e.t.c .With some explain of them would be super helpful.

Also i have a combination like this :

```<code>df$Category<-ifelse(regexpr("[.]",df$Category)==4,
             paste("0",df1$Category,sep = ""),df$Category)

df$Category<-str_pad(df$Category,11,side = c("right"),pad="0")
</code>```

Desire to know are there is any better way do this , especially count and
return the location from the END until specific character appear.

答:
Using formatC:

```<code>df$Category <- formatC(as.numeric(df$Category), format = 'f', width = 11, flag = '0', digits = 6)
# > df
#      Category
# 1 0300.030340
# 2 3400.040290
# 3 0700.070110
# 4 1700.090100
# 5 0700.070114
# 6 0700.079100
# 7 3600.050590
# 8 4400.040200
</code>```

format = 'f': formating doubles;

width = 11: 4 digits before .  + 1 . + 6 digits after .;

flag = '0': pads leading zeros;

digits = 6: the desired number of digits after the decimal point (format = "f");

Input df seems to be character data.frame:

```<code>structure(list(Category = c("300.030340", "3400.040290", "700.07011",
"1700.0901", "700.070114", "700.0791", "3600.05059", "4400.0402"
)), .Names = "Category", row.names = c(NA, -8L), class = "data.frame")
</code>```

Body:
There is the basic width : xxxx.xxxxxx (4digits before "." 6 digits after".")

Have to add "0" when each side before and after "." is not enough digits.

Use regexr find "[.]" location with combination of str_pad can
fix the first 4 digits but

don't know how to add value after the specific character with fixed digits.
(cannot find a library can count the location from somewhere specified)

Data like this

> df
         Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402

Desired data

> df
         Category
1      0300.030340
2      3400.040290
3      0700.070110
4      1700.090100
5      0700.070114
6      0700.079100
7      3600.050590
8      4400.040200

I am beginner of coding that sometime can't understand some regex like "["
e.t.c .With some explain of them would be super helpful.

Also i have a combination like this :

df$Category<-ifelse(regexpr("[.]",df$Category)==4,
             paste("0",df1$Category,sep = ""),df$Category)

df$Category<-str_pad(df$Category,11,side = c("right"),pad="0")

Desire to know are there is any better way do this , especially count and
return the location from the END until specific character appear.

Body:
Using formatC:

df$Category <- formatC(as.numeric(df$Category), format = 'f', width = 11, flag = '0', digits = 6)
# > df
#      Category
# 1 0300.030340
# 2 3400.040290
# 3 0700.070110
# 4 1700.090100
# 5 0700.070114
# 6 0700.079100
# 7 3600.050590
# 8 4400.040200

format = 'f': formating doubles;

width = 11: 4 digits before .  + 1 . + 6 digits after .;

flag = '0': pads leading zeros;

digits = 6: the desired number of digits after the decimal point (format = "f");

Input df seems to be character data.frame:

structure(list(Category = c("300.030340", "3400.040290", "700.07011",
"1700.0901", "700.070114", "700.0791", "3600.05059", "4400.0402"
)), .Names = "Category", row.names = c(NA, -8L), class = "data.frame")


问:
Where can I implement polymorphism?
Sorry to ask this silly question, I'm new to Java.
I have a super class called Sales Manager, and its subclass are ItemEntry, SupplierEntry, PurchaseRequisition and so on. Can anyone suggest me where to implement the overloading and overriding concept? I mean ya although they are inherited, but Sales Manager and ItemEntry are completely different things isn't?

Unlike the superclass car, subclass Ford, Volkswagen, this only make sense.

Appreciate for you help.

答:
In your example, as Tim said, your model might be better suited using something else than PolyMorphism.

Best to think of PolyMorphism where you want to extend something to be clearer, or more defined.   I prefer the Animals Example..

```<code>Dog -> Pet -> Mammal -> Animal -> Genus -> etc....
</code>```

This allows extending objects to add additional and specific members (properties/methods) that can be shared across that classification.

Where you may have something that may be used across Objects, that is not specific, or always present, to an object, you would use Interfaces.  These allow you to add extra methods (that the user must define when used) that the object implements.

For example...

Not all birds can be pets, so in the previous setup we may choose to use an interface in place of Pet.

```<code>Dog (Implements Pet) -> Mammal -> Animal -> ...
</code>```

So then we could use the same interface on anything else we polymorph, such as a bird.

```<code>Parrot (Implements Pet) -> Bird -> Animal -> ...
</code>```

It's a bit to get your head around at first, so I would suggest playing with some simple examples and go from there.

So for your Sales Manager example, you might use the following setup as they are related...

Sales Manager -> Manager -> Employee -> Person

Your ItemEntry, SupplierEntry, PurchaseRequisition you could use as properties or SalesManager.

Hope that helps

Title: Where can I implement polymorphism?

Body:
In your example, as Tim said, your model might be better suited using something else than PolyMorphism.

Best to think of PolyMorphism where you want to extend something to be clearer, or more defined.   I prefer the Animals Example..

Dog -> Pet -> Mammal -> Animal -> Genus -> etc....

This allows extending objects to add additional and specific members (properties/methods) that can be shared across that classification.

Where you may have something that may be used across Objects, that is not specific, or always present, to an object, you would use Interfaces.  These allow you to add extra methods (that the user must define when used) that the object implements.

For example...

Not all birds can be pets, so in the previous setup we may choose to use an interface in place of Pet.

Dog (Implements Pet) -> Mammal -> Animal -> ...

So then we could use the same interface on anything else we polymorph, such as a bird.

Parrot (Implements Pet) -> Bird -> Animal -> ...

It's a bit to get your head around at first, so I would suggest playing with some simple examples and go from there.

So for your Sales Manager example, you might use the following setup as they are related...

Sales Manager -> Manager -> Employee -> Person

Your ItemEntry, SupplierEntry, PurchaseRequisition you could use as properties or SalesManager.

Hope that helps


问:
Umbraco 7.6.3 backend is slow after installing Forms 6.0.1 with App_Data virtual directory
We've noticed that after installing Forms 6.0.1 on Umbraco 7.6.3 and using a virtual directory for App_Data causes the CMS to run extremely slow.  Some of our clients have load-balanced live environments and have created virtual directories for App_Data, media etc.  We’ve upgraded their site from version 4.8.0 to 7.6.3 and after installing Forms and deploying to a demo environment noticed that the CMS was taking forever to do anything.  We’ve been using a virtual directory for App_Data on various versions of Umbraco for years and never encountered any issues with this approach.

To eliminate that the issue wasn’t due to anything in the upgrade we were able to recreate the problem following these steps:

On a local dev machine installed a new (clean version) of Umbraco 7.6.3.

Setup localhost using IIS to access the site (rather than IIS express).

Created a virtual directory in IIS for App_Data, pointing to a folder outside of the web root for the solution.

The page load time in the CMS averages approx. 750ms at this point.

Installed Forms via the back-office.

The page load time in the CMS once Forms has installed dramatically increases averaging 21 seconds.

If we remove the virtual directory from IIS or setting fcnmode=”disabled” in web.config the CMS is performant again.  From what I’ve read setting fcnmode to disabled will stop file change notifaction, but a downside to this is that the application pool won’t be recycled.  This may be something we have to live with but I’m curious what Forms is doing under the hood that would cause this?  Forms was previously added to the App_Plugin folder rather than App_Data, was there a reason for this?

The Umbraco Log dramatically increases in file size and contains the following:

```<code>2017-06-27 09:37:12,192 [P23168/D99/T80] INFO Umbraco.Core.UmbracoApplicationBase - Application shutdown. Details: ConfigurationChange

_shutDownMessage=CONFIG change
HostingEnvironment initiated shutdown
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
HostingEnvironment caused shutdown

_shutDownStack= at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace)
at System.Web.Configuration.HttpConfigurationSystem.OnConfigurationChanged(Object sender, InternalConfigEventArgs e)
at System.Configuration.Internal.InternalConfigRoot.OnConfigChanged(InternalConfigEventArgs e)
at System.Configuration.BaseConfigurationRecord.OnStreamChanged(String streamname)
at System.Web.DirectoryMonitor.FireNotifications()
at System.Web.Util.WorkItem.CallCallbackWithAssert(WorkItemCallback callback)
at System.Web.Util.WorkItem.OnQueueUserWorkItemCompletion(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
</code>```

答:
I believe the issue is that this file is being read from the physical path instead of the virtual path.
\App_Data\TEMP\formsupdate

If you include this file in both physical and virtual locations this should work around the issue.

I've reported the issue here: http://issues.umbraco.org/issue/CON-1456

Body:
We've noticed that after installing Forms 6.0.1 on Umbraco 7.6.3 and using a virtual directory for App_Data causes the CMS to run extremely slow.  Some of our clients have load-balanced live environments and have created virtual directories for App_Data, media etc.  We’ve upgraded their site from version 4.8.0 to 7.6.3 and after installing Forms and deploying to a demo environment noticed that the CMS was taking forever to do anything.  We’ve been using a virtual directory for App_Data on various versions of Umbraco for years and never encountered any issues with this approach.

To eliminate that the issue wasn’t due to anything in the upgrade we were able to recreate the problem following these steps:

On a local dev machine installed a new (clean version) of Umbraco 7.6.3.

Setup localhost using IIS to access the site (rather than IIS express).

Created a virtual directory in IIS for App_Data, pointing to a folder outside of the web root for the solution.

The page load time in the CMS averages approx. 750ms at this point.

Installed Forms via the back-office.

The page load time in the CMS once Forms has installed dramatically increases averaging 21 seconds.

If we remove the virtual directory from IIS or setting fcnmode=”disabled” in web.config the CMS is performant again.  From what I’ve read setting fcnmode to disabled will stop file change notifaction, but a downside to this is that the application pool won’t be recycled.  This may be something we have to live with but I’m curious what Forms is doing under the hood that would cause this?  Forms was previously added to the App_Plugin folder rather than App_Data, was there a reason for this?

The Umbraco Log dramatically increases in file size and contains the following:

2017-06-27 09:37:12,192 [P23168/D99/T80] INFO Umbraco.Core.UmbracoApplicationBase - Application shutdown. Details: ConfigurationChange

_shutDownMessage=CONFIG change
HostingEnvironment initiated shutdown
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
CONFIG change
HostingEnvironment caused shutdown

_shutDownStack= at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace)
at System.Web.Configuration.HttpConfigurationSystem.OnConfigurationChanged(Object sender, InternalConfigEventArgs e)
at System.Configuration.Internal.InternalConfigRoot.OnConfigChanged(InternalConfigEventArgs e)
at System.Configuration.BaseConfigurationRecord.OnStreamChanged(String streamname)
at System.Web.DirectoryMonitor.FireNotifications()
at System.Web.Util.WorkItem.CallCallbackWithAssert(WorkItemCallback callback)
at System.Web.Util.WorkItem.OnQueueUserWorkItemCompletion(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()


问:
Get data from MySql with RIDE
I'm trying to read data from a MySql database. Everything is correct except when I have to receive words with an accent or the character 'ñ'

I have reviewed the collation of my database. I have it configured in utf8_unicode_ci in the table and in the column.

I use python 2.7.8 and I have tried to decode and unicode and I can not write well the result of the tables. I always get:

Baño -> Ba\xf1o

Lámina -> L\xe1mina

I launch the query from RIDE (1.5.2.1) under Windows 10.

Any ideas?

Thank you.

答:
How are you "receiving" the text?  ñ, when encoded as hex e1 is encoded as latin1.  (Actually any of cp1250, dec8, latin1, latin2, latin5, but probably latin1, since that is the old default for MySQL.)

If you actually have e1 in the client, then tell MySQL that you have latin1.  It is OK to have the database tables set to utf8 -- MySQL will transliterate as you do the stores/fetches.

It would be better to have utf8 everywhere.

Here are my notes on Python:  http://mysql.rjweb.org/doc.php/charcoll#python
Note that that section ends with a link to an issue with the old Python 2.7, which you seem to be using: Flask_SQLAlchemy, MySQL, store Swedish characters å, ä, ö?

Title: Get data from MySql with RIDE


问:
Need help iterating over python dictionary values
I'm working on a program to search through a dictionaries value set and perform a method on values that match a user input. I have to compare and sort these values.

This is the code I'm working with right now

Code for value search and compare (very rough)

```<code>import nation
import pickle

KK = 1000000

pickle_in = open("nationsDict.dat","rb")
d = pickle.load(pickle_in)

k = raw_input("Enter a continent: ")

for value in d.values():
    if k in d.values()[0]:
        print d.values()[0]
</code>```

Code for Nation class

```<code>class Nations:

    KK = 1000000

    def __init__(self, ctry, cont, pop, area):
        self.country = ctry
        self.continent = cont
        self.population = float(pop)
        self.area = float(area)

    def popDensity(self):
        popDensity = (self.population*self.KK) / self.area
        popDensity = str(round(popDensity, 2))
        return popDensity
</code>```

Code for creating pickle dictionary

```<code>import nation
import pickle

i=0
dictUN = {}

with open('UN.txt') as f:
    for line in f:

        """Data get from file"""
        elements = line.strip().split(",")

        n = nation.Nations(elements[0],elements[1],elements[2],elements[3])

        """Density"""
        n.popDensity()
        print "The density of", n.country, "is",n.popDensity(),"people per square mile."

        """Dictionary creation"""
        dictVal = (n.continent, n.population, n.area)
        dictUN.update({n.country: dictVal})

pickle_out = open("nationsDict.dat", "wb")
pickle.dump(dictUN, pickle_out)
pickle_out.close()
</code>```

Here's a snippet from UN.txt

```<code>Mauritania,Africa,3.5,397954
Mauritius,Africa,1.3,787
Mexico,North America,120.3,761606
Micronesia,Australia/Oceania,.11,271
Monaco,Europe,.031,0.76
Mongolia,Asia,3.0,603909
Montenegro,Europe,.65,5019
Morocco,Africa,33.0,172414
</code>```

My problems at this point are pretty contained to the value search and compare. Specifically, my program has to

Allow the user to search a continent (first element in value list)

Perform the method, Nations.popDensity (contained in nation class) on all matching countries

Compare the nations and return the top 5 density values per continent

I would say my one big question is how to handle the search of a dictionary by an element in a value. I've also considered about making a temp dictionary with the continent element as the key, but I'm not sure that would make my life any easier as I have to perform the popDensity method on it.

Any help is appreciated, Thanks!

答:
Glad it was helpful.  I'll add it as an answer, so you can accept it, if you like.

Just as there is list comprehension, there is dictionary comprehension... It's pretty cool stuff! d2 = {k:d[k] for k in d.keys() if <some_elem> in d[k]} would give you a dict with a subset of the original dict that satisfies your requirements. You would have to fill in the <some_elem> in d[k] portion, because I haven't gone through all your code. You said that this is the main Q you have. Hopefully this gives you enough to solve it.

Body:
I'm working on a program to search through a dictionaries value set and perform a method on values that match a user input. I have to compare and sort these values.

This is the code I'm working with right now

Code for value search and compare (very rough)

import nation
import pickle

KK = 1000000

pickle_in = open("nationsDict.dat","rb")
d = pickle.load(pickle_in)

k = raw_input("Enter a continent: ")

for value in d.values():
    if k in d.values()[0]:
        print d.values()[0]

Code for Nation class

class Nations:

    KK = 1000000

    def __init__(self, ctry, cont, pop, area):
        self.country = ctry
        self.continent = cont
        self.population = float(pop)
        self.area = float(area)

    def popDensity(self):
        popDensity = (self.population*self.KK) / self.area
        popDensity = str(round(popDensity, 2))
        return popDensity

Code for creating pickle dictionary

import nation
import pickle

i=0
dictUN = {}

with open('UN.txt') as f:
    for line in f:

        """Data get from file"""
        elements = line.strip().split(",")

        n = nation.Nations(elements[0],elements[1],elements[2],elements[3])

        """Density"""
        n.popDensity()
        print "The density of", n.country, "is",n.popDensity(),"people per square mile."

        """Dictionary creation"""
        dictVal = (n.continent, n.population, n.area)
        dictUN.update({n.country: dictVal})

pickle_out = open("nationsDict.dat", "wb")
pickle.dump(dictUN, pickle_out)
pickle_out.close()

Here's a snippet from UN.txt

Mauritania,Africa,3.5,397954
Mauritius,Africa,1.3,787
Mexico,North America,120.3,761606
Micronesia,Australia/Oceania,.11,271
Monaco,Europe,.031,0.76
Mongolia,Asia,3.0,603909
Montenegro,Europe,.65,5019
Morocco,Africa,33.0,172414

My problems at this point are pretty contained to the value search and compare. Specifically, my program has to

Allow the user to search a continent (first element in value list)

Perform the method, Nations.popDensity (contained in nation class) on all matching countries

Compare the nations and return the top 5 density values per continent

I would say my one big question is how to handle the search of a dictionary by an element in a value. I've also considered about making a temp dictionary with the continent element as the key, but I'm not sure that would make my life any easier as I have to perform the popDensity method on it.

Any help is appreciated, Thanks!


问:
packed vs unpacked vectors in system verilog
Looking at some code I'm maintaining in System Verilog I see some signals that are defined like this:

```<code>node [range_hi:range_lo]x;
</code>```

and others that are defined like this:

```<code>node y[range_hi:range_lo];
</code>```

I understand that x is defined as packed, while y is defined as unpacked.  However, I have no idea what that means.

What is the difference between packed and unpacked vectors in System Verilog?

Edit: Responding to @Empi's answer, why should a hardware designer who's writing in SV care about the internal representation of the array?  Are there any times when I shouldn't or can't use packed signals?

答:
Unpacked arrays will give you more compile time error checking than packed arrays.

I see unpacked arrays on the port definitions of modules for this reason.  The compiler will error if the dimensions of the signal are not exactly the same as the port with unpacked arrays.  With packed arrays it will normally just go ahead and wire things the best it can, not issuing an error.

OwnerDisplayName: Nathan Fellman

ContentLicense: CC BY-SA 2.5

Body:
Looking at some code I'm maintaining in System Verilog I see some signals that are defined like this:

node [range_hi:range_lo]x;

and others that are defined like this:

node y[range_hi:range_lo];

I understand that x is defined as packed, while y is defined as unpacked.  However, I have no idea what that means.

What is the difference between packed and unpacked vectors in System Verilog?

Edit: Responding to @Empi's answer, why should a hardware designer who's writing in SV care about the internal representation of the array?  Are there any times when I shouldn't or can't use packed signals?

LastEditorDisplayName: Nathan Fellman


问:
No rule to make target `/Makefile', needed by `Makefile'
I'm trying to 'make' using a pretty simple makefile. My makefile is named 'Makefile' so I'm simply using the command 'make'.

I get this strange error:

make: *** No rule to make target `/Makefile', needed by `Makefile'.  Stop.

If, however, I use
make -f "full-path-to-makefile" it actually does run (with odd consequences...). I should say that I'm running all this from the directory where the Makefile lies, of course.

I'm working on Mac OSX, using tcsh.

Edit:

I'm working in the LLVM framework, trying to compile a pass function and this is  the associated makefile:

```
LEVEL = ../../../
LIBRARYNAME = FunctionName
LOADABLE_MODULE = 1
include $(LEVEL)/Makefile.common
```

Any ideas will be appreciated :)

答:
It's not a complete answer, but what you are seeing is gmake not finding the Makefile it is told to include, and thus it is trying to remake it and failing because it can't find a recipe for it either.

However, the Makefile snippet you posted does not produce the error message you are seeing, so I think the problem is inside the Makefile.common file. Look for include statements which reference a $(some variable expansion)/Makefile and work backwards from there. You can also try to run gmake with the -d option and follow the processing based on the output.

Body:
I'm trying to 'make' using a pretty simple makefile. My makefile is named 'Makefile' so I'm simply using the command 'make'.

I get this strange error:

make: *** No rule to make target `/Makefile', needed by `Makefile'.  Stop.

If, however, I use
make -f "full-path-to-makefile" it actually does run (with odd consequences...). I should say that I'm running all this from the directory where the Makefile lies, of course.

I'm working on Mac OSX, using tcsh.

Edit:

I'm working in the LLVM framework, trying to compile a pass function and this is  the associated makefile:

LEVEL = ../../../
LIBRARYNAME = FunctionName
LOADABLE_MODULE = 1
include $(LEVEL)/Makefile.common

Any ideas will be appreciated :)


问:
data integration practice key field handling
Seeking thoughts and advice in addressing a customer request.  We're working in an existing database that contains primary keys but no foreign keys, which won't change.

The request is for us to integrate data from outside sources which
may contain duplicate values in the data.

The data is from a records-management system, so key id values will
increase with each record collected.

The key fields, for the most part, are decimal(22,0).

This is a daily ETL load of a relatively small amount of data, so
performance isn't the most important concern.

Is it better to prefix, suffix, or use some other strategy to create unique key values that can be traced back to the source?

For instance, if the max existing value were 123456789, is it a good idea to prefix 100000 for external site A, 110000 for external site B, etc?   We've batted a few ideas about as a team and there seems to be pro's and con's with everything we can think of.  Not seeing much guidance on the web.

Thanks in advance for any ideas!

答:
Generally it's better to have a separate field tracking whether the data is from A or B which is either part of your primary key or a supplementary index/constraint where you use a surrogate identity/auto-increment field as the primary key.

Among other things, this makes it easier to later do things like table partitioning or conditional indexes.


问:
How to check if letter in a string appear in another string in the same order

I would love to check if the letters from a text appear in another text in the same order.

```<code>text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False
</code>```

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

答:
One way to do it would be to avoid iterating through each letter of the word.

```<code>if any(text in name for text in text_collection):
    print(text)
</code>```

This would check the whole string of text against a string in name. This is assuming that text_collection has more than one entry. Otherwise just use if any(text in name): See the official documentation of any here.

Body:
I would love to check if the letters from a text appear in another text in the same order.

text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

Body:
One way to do it would be to avoid iterating through each letter of the word.

if any(text in name for text in text_collection):
    print(text)

This would check the whole string of text against a string in name. This is assuming that text_collection has more than one entry. Otherwise just use if any(text in name): See the official documentation of any here.


问:
Pandas Pivot Table- aggfunc to get subtotals on a multi-Index?
I have a simple dataframe with an index I need to group on- continent:

```<code> country   continent   value1   value2   value3
 uk        eu               1        9        2
 us        na               8       39        0
 spain     eu               3        9        0
 mexico    na               2        7        8
 japan     asia             9        9        2
 china     asia             2        8        6
</code>```

All I'm looking to do is create a dataframe that creates rows for continents and incorporates their subtotals as a value, and then adds Grand total at the end and incorporates the totals for each column.

```<code> Row Labels    Sum of value1   Sum of value2   Sum of value3
 asia                     11              17               8
 china                     2               8               6
 japan                     9               9               2
 eu                        4              18               2
 spain                     3               9               0
 uk                        1               9               2
 na                       10              46               8
 mexico                    2               7               8
 us                        8              39               0
 Grand Total              25              81              18
</code>```

This is my code, and for some reason I can only get the grand total with the aggfunc, not subtotals as well.

```<code>pd.pivot_table(mergedcpt, index=['continent','spread_Bucket'],aggfunc=np.sum, margins=True)

  eu      uk     1    9    2
          us        8   39    0
  na     spain     3    9    0
         mexico    2    7    8
  asia   japan     9    9    2
         china     2    8    6
  all             25   81   18
</code>```

What am I getting wrong? Appreciate the help- I know previous pandas versions incorporated rows you could aggregate, but I don't know how to do this in the new version. Appreciate the help.

答:
There is no quick one-liner for what you are trying to do.  You can create a new data frame by grouping on the continents, append the original data frame, and sort the values to get the order you want.</p>

```<code>import pandas as pd

df = pd.DataFrame(
    {'continent': ['eu', 'na', 'eu', 'na', 'asia', 'asia'],
     'country': ['uk', 'us', 'spain', 'mexico', 'japan', 'china'],
     'value1': [1, 8, 3, 2, 9, 2],
     'value2': [9, 39, 9, 7, 9, 8],
     'value3': [2, 0, 0, 8, 2, 6]})

g = df.groupby(['continent','continent']).sum()
g.index.set_names('Row Label', level=-1, inplace=True)
gt = pd.DataFrame([g.sum()], columns=g.columns,
    index=pd.MultiIndex.from_tuples([('~','Grand Total')]))
df2 = g.append(gt).reset_index()
out = ( df2.append(df.rename(columns={'country': 'Row Label'})
                     .sort_values(['continent', 'Row Label']))
           .sort_values('continent')
           .drop('continent', axis=1)
           .rename(columns={'value1': 'Sum of value1',
                            'value2': 'Sum of value2',
                            'value3': 'Sum of value3'})
           .reset_index(drop=True) )
out
# returns:
     Row Label  Sum of value1  Sum of value2  Sum of value3
0         asia             11             17              8
1        china              2              8              6
2        japan              9              9              2
3           eu              4             18              2
4        spain              3              9              0
5           uk              1              9              2
6           na             10             46              8
7       mexico              2              7              8
8           us              8             39              0
9  Grand Total             25             81             18
</code>```

Body:
I have a simple dataframe with an index I need to group on- continent:

 country   continent   value1   value2   value3
 uk        eu               1        9        2
 us        na               8       39        0
 spain     eu               3        9        0
 mexico    na               2        7        8
 japan     asia             9        9        2
 china     asia             2        8        6

All I'm looking to do is create a dataframe that creates rows for continents and incorporates their subtotals as a value, and then adds Grand total at the end and incorporates the totals for each column.

 Row Labels    Sum of value1   Sum of value2   Sum of value3
 asia                     11              17               8
 china                     2               8               6
 japan                     9               9               2
 eu                        4              18               2
 spain                     3               9               0
 uk                        1               9               2
 na                       10              46               8
 mexico                    2               7               8
 us                        8              39               0
 Grand Total              25              81              18

This is my code, and for some reason I can only get the grand total with the aggfunc, not subtotals as well.

pd.pivot_table(mergedcpt, index=['continent','spread_Bucket'],aggfunc=np.sum, margins=True)

  eu      uk     1    9    2
          us        8   39    0
  na     spain     3    9    0
         mexico    2    7    8
  asia   japan     9    9    2
         china     2    8    6
  all             25   81   18

What am I getting wrong? Appreciate the help- I know previous pandas versions incorporated rows you could aggregate, but I don't know how to do this in the new version. Appreciate the help.

Body:
There is no quick one-liner for what you are trying to do.  You can create a new data frame by grouping on the continents, append the original data frame, and sort the values to get the order you want.

import pandas as pd

df = pd.DataFrame(
    {'continent': ['eu', 'na', 'eu', 'na', 'asia', 'asia'],
     'country': ['uk', 'us', 'spain', 'mexico', 'japan', 'china'],
     'value1': [1, 8, 3, 2, 9, 2],
     'value2': [9, 39, 9, 7, 9, 8],
     'value3': [2, 0, 0, 8, 2, 6]})

g = df.groupby(['continent','continent']).sum()
g.index.set_names('Row Label', level=-1, inplace=True)
gt = pd.DataFrame([g.sum()], columns=g.columns,
    index=pd.MultiIndex.from_tuples([('~','Grand Total')]))
df2 = g.append(gt).reset_index()
out = ( df2.append(df.rename(columns={'country': 'Row Label'})
                     .sort_values(['continent', 'Row Label']))
           .sort_values('continent')
           .drop('continent', axis=1)
           .rename(columns={'value1': 'Sum of value1',
                            'value2': 'Sum of value2',
                            'value3': 'Sum of value3'})
           .reset_index(drop=True) )
out
# returns:
     Row Label  Sum of value1  Sum of value2  Sum of value3
0         asia             11             17              8
1        china              2              8              6
2        japan              9              9              2
3           eu              4             18              2
4        spain              3              9              0
5           uk              1              9              2
6           na             10             46              8
7       mexico              2              7              8
8           us              8             39              0
9  Grand Total             25             81             18


问:
Hive doesn't read latest HDFS file data until I close OutputStream
I use Spark Streaming to append data to HDFS file. For each batch, I write data and then call hsync to make sure data is persistent.

When execute hadoop fs -cat command, I can see my update is persistent, however if I execute select count(*) from table in Hive, the total count will not change until I close the OutputStream.

Also I noticed, when execute hadoop fs -ls command, HDFS file last modification time and file size will not change until close the OutputStream.

How it happens? Is there a way to let Hive read new data but don't close OutputStream?

Edited@20180811

I guess the problem is, before file closed, the file size is not sync to namenode. when MR job launched, it get the file size from namenode which is not the actual size, and tell MR job the read the size, so the new appended data are not read.
Is there config properties to avoid this?

答: The reason is when init MR job, client will get file length from name node and calculate file split. When file is not close, file length is not sync to name node, so client don't know there is new data. I customize file input format to verify this problem, @  https://github.com/yantzu/hendeavour</p>


问:
css transition and jquery animation conflict

I use the following css code to put transition in all my site

```<code>*{
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;}
</code>```

In part of the site, i have a title and when click in it must show the hidden content. In this case i use the following jquery code.

```<code>jQuery(".title").click(function () {

    jQuery(".content").slideToggle(300);

});
</code>```

the opening animation is not smoothly

I put a code example here
https://jsfiddle.net/304u3ogv/

Someone know why happen this stuck effect?

P.S.: sorry about my bad English.

答:
Simply add transition: none; to #content in the CSS

See this updated fiddle https://jsfiddle.net/304u3ogv/1/

Body:
I use the following css code to put transition in all my site

*{
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
transition: all 0.3s ease;}

In part of the site, i have a title and when click in it must show the hidden content. In this case i use the following jquery code.

jQuery(".title").click(function () {

    jQuery(".content").slideToggle(300);

});

the opening animation is not smoothly

I put a code example here
https://jsfiddle.net/304u3ogv/

Someone know why happen this stuck effect?

P.S.: sorry about my bad English.


答:
You can check if the $Image_Input_10 has value. If none, then hide the div. See my code below which is added on your swiper-container div</p>

```<code> <div class="swiper-container" <?php if(isset($Image_Input_10)){ echo 'style="display:none;"';} ?>>
</code>```

Title: Hide img carousel box if empty

Body:
How do I hide the div if the user only select 9 images and what I want is to hide other image div or else it will appear a blank box if no image is added. It is a carousel.

<?php echo $title ?>

<img style="width:100%; height:100%" src="
<?php echo $Image_Input_1 ?>">

<img style="width:100%; height:100%" src="
<?php echo $Image_Input_2 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_3 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_4 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_5 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_6 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_7 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_8 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_9 ?>">

<img style="width:100%; height:100%"
src="<?php echo $Image_Input_10 ?>">

Body:
You can check if the $Image_Input_10 has value. If none, then hide the div. See my code below which is added on your swiper-container div

 <div class="swiper-container" <?php if(isset($Image_Input_10)){ echo 'style="display:none;"';} ?>>