问:
ASP.NET Core - MVC. Drop down populate issue
I'm using vs 2017 and chrome.

I have an ASP.Net Core MVC app. It has a drop down that isn't showing the items correctly. The items displayed should be: Comedy, Western and Romantic.

Here's the debug image. The items shows the array and the text {MvcMovie.Modesl.Genre} and as I click each, the item text shows as I want.

I select the genres from the database and return them as as List and cast it to a SelectList as that is what is it is rendered as HTML a  element with the collection of SelectListItem objects.

However, when I look at the Raw View, I only see the text {MvcMovie.Modesl.Genre} which is what is being shown in the drop down.

I populate the movieGenreVM and return it as a view in the Index action method.

```<code>      public IActionResult Index(string movieGenre, string searchStringEntered)
    {
        // A list of genre objects.
        SelectList genresList;

        // A list of movie objects.
        List<Movie> moviesList;

        // Instantiate the View model.
        var movieGenreVM = new MovieGenreViewModel();

        // Get a list of genres from the database.
        genresList = new SelectList(GetGenres(movieGenre));

        // Get a list of movies from the database.
        moviesList = GetMovies(searchStringEntered);

        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = genresList;

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = moviesList;

        // Passing the MovieGenreViewModel.
        // Return the IActionResult - the Index.cshtml. A view template to generate an HTML response to the browser.
        return View(movieGenreVM);
    }

namespace MvcMovie.Models
{
public class MovieGenreViewModel
{
    // A list of movies.
    public List<Movie> movies;

    // A SelectList containing the list of genres.
    public SelectList genres;

    // Contains the selected genre.
    public string movieGenre { get; set; }
  }
}
</code>```

The genre models is:

```<code>public class Genre
{
    public string MovieGenre { get; set; }

    // Constructor.
    public Genre()
    {
    }

    public Genre(string a_MovieGenre)
    {
        MovieGenre = a_MovieGenre;
    }
}
</code>```

Here's the population of the genre list code:

```<code>    // Create a list of genres.
    private List<Genre> _genre = new List<Genre>();

    public List<Genre> Genre
    {
        get
        {
            return _genre;
        }
    }

    public List<Genre> GetGenres(string movieGenre)
    {
        Boolean errorSw = false;

        // Declare the reader and initialize.
        SqlDataReader GenresDataReader = null;

        try
        {
            // Open the connection.
            dbFunc.OpenDB();

            // Get the list of distinct Genres by executing a stored procedure.
            SqlCommand GenresCmd = new SqlCommand("dbo.SelectGenres", dbFunc.objConn);
            GenresCmd.Parameters.Clear();
            GenresCmd.CommandType = CommandType.StoredProcedure;
            GenresCmd.Parameters.Add("@SearchText", SqlDbType.VarChar).Value = movieGenre;

            // Set the reader.
            GenresDataReader = GenresCmd.ExecuteReader();

            // Loop thru the results returned.
            while (GenresDataReader.Read())
            {
                // Add to the list of genres - creates a new row for the collection.
                Genre.Add(new Genre(GenresDataReader["Genre"].ToString()));
            }
        }
        catch (Exception ex)
        {
            errorSw = true;
        }
        finally
        {
            if (GenresDataReader != null)
            {
                GenresDataReader.Close();
            }

            dbFunc.CloseDB();
        }

        // Return the list of genre objects.
        return Genre;
    }
</code>```

Here's the view:

@model MvcMovie.Models.MovieGenreViewModel

@{
    ViewData["Title"] = "Index";
}

List of Movies

    Create New

<form asp-controller="Movies" asp-action="Index" method="get">

        @* A dropdown. *@
        <select asp-for="movieGenre" asp-items="Model.genres">
            <option value="">All</option>
        </select>

        Title: <input type="text" name="searchStringEntered">

        <input type="submit" value="Filter" />

</form>

@* Shows the list of movies. *@

                @Html.DisplayNameFor(model => model.movies[0].Title)

                @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)

                @Html.DisplayNameFor(model => model.movies[0].Genre)

                @Html.DisplayNameFor(model => model.movies[0].Price)

                @Html.DisplayNameFor(model => model.movies[0].Rating)

        @foreach (var item in Model.movies) {

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

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

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

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

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

                    Edit |
                    Details |
                    Delete

         }

```
</div>
</div>
</p>

<p>This tutorial is using Entity Framework but I am converting it to using ADO.net and stored procedures. The EF version of the drop down works fine.</p>

<p>Here is the the EF versions Index action method. The genre is just the text - no Id associated with it.</p>

```    public async Task<IActionResult> Index(string movieGenre, string searchStringEntered)
    {
        IQueryable<string> genreQuery = from m in _context.Movie
                                        orderby m.Genre
                                        select m.Genre;

        var movies = from m in _context.Movie
                     select m;

        if (!String.IsNullOrEmpty(searchStringEntered))
        {
            movies = movies.Where(s => s.Title.Contains(searchStringEntered));
        }

        if (!String.IsNullOrEmpty(movieGenre))
        {
            movies = movies.Where(x => x.Genre == movieGenre);
        }

        // Instantiate the model.
        var movieGenreVM = new MovieGenreViewModel();

        // The SelectList of genres is created by projecting the distinct genres.
        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = await movies.ToListAsync();

        return View(movieGenreVM);
    }
```

答:
This is an example of how I do it:

```<code>        var items = GetItemsFromDB();
        var vals = new List<SelectListItem> {new SelectListItem {Selected = true, Text = "--Select an Item--", Value = "0"}};

        vals.AddRange(items.Select(item => new SelectListItem
        {
            Selected = false, Text = item.Type, Value = item.Id.ToString()
        }));

        var result = new SelectList(vals, "Value", "Text");
</code>```

As you can see when i convert it to a SelectList I specify the Value and Text as dataValueField and dataTextField.

In your case you need properties for these values and specify them when you "cast it" using the SelectList constructor.

In my view I do this:

```<code><select asp-for="Model.ItemId" asp-items="Model.MyItemSelectList"></select>
</code>```

Where Model.MyItemSelectList can be a List of SelectListItem

Another way to bind it to a collection is like this:

```<code>                                     <select asp-for="Model.MyItemId">
                                        <option value="">-- Select Item --</option>
                                        @{
                                             foreach (var item in Model.MyItems)
                                             {
                                                 <option value="@item.Key">@item.Value</option>
                                             }
                                        }
                                    </select>
</code>```

Where item has Key and Value properties.  The properties can be names whatever you want. In this case "item" has those properties.

Body:
I'm using vs 2017 and chrome.

I have an ASP.Net Core MVC app. It has a drop down that isn't showing the items correctly. The items displayed should be: Comedy, Western and Romantic.

Here's the debug image. The items shows the array and the text {MvcMovie.Modesl.Genre} and as I click each, the item text shows as I want.

I select the genres from the database and return them as as List and cast it to a SelectList as that is what is it is rendered as HTML a  element with the collection of SelectListItem objects.

However, when I look at the Raw View, I only see the text {MvcMovie.Modesl.Genre} which is what is being shown in the drop down.

I populate the movieGenreVM and return it as a view in the Index action method.

      public IActionResult Index(string movieGenre, string searchStringEntered)
    {
        // A list of genre objects.
        SelectList genresList;

        // A list of movie objects.
        List<Movie> moviesList;

        // Instantiate the View model.
        var movieGenreVM = new MovieGenreViewModel();

        // Get a list of genres from the database.
        genresList = new SelectList(GetGenres(movieGenre));

        // Get a list of movies from the database.
        moviesList = GetMovies(searchStringEntered);

        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = genresList;

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = moviesList;

        // Passing the MovieGenreViewModel.
        // Return the IActionResult - the Index.cshtml. A view template to generate an HTML response to the browser.
        return View(movieGenreVM);
    }

namespace MvcMovie.Models
{
public class MovieGenreViewModel
{
    // A list of movies.
    public List<Movie> movies;

    // A SelectList containing the list of genres.
    public SelectList genres;

    // Contains the selected genre.
    public string movieGenre { get; set; }
  }
}

The genre models is:

public class Genre
{
    public string MovieGenre { get; set; }

    // Constructor.
    public Genre()
    {
    }

    public Genre(string a_MovieGenre)
    {
        MovieGenre = a_MovieGenre;
    }
}

Here's the population of the genre list code:

    // Create a list of genres.
    private List<Genre> _genre = new List<Genre>();

    public List<Genre> Genre
    {
        get
        {
            return _genre;
        }
    }

    public List<Genre> GetGenres(string movieGenre)
    {
        Boolean errorSw = false;

        // Declare the reader and initialize.
        SqlDataReader GenresDataReader = null;

        try
        {
            // Open the connection.
            dbFunc.OpenDB();

            // Get the list of distinct Genres by executing a stored procedure.
            SqlCommand GenresCmd = new SqlCommand("dbo.SelectGenres", dbFunc.objConn);
            GenresCmd.Parameters.Clear();
            GenresCmd.CommandType = CommandType.StoredProcedure;
            GenresCmd.Parameters.Add("@SearchText", SqlDbType.VarChar).Value = movieGenre;

            // Set the reader.
            GenresDataReader = GenresCmd.ExecuteReader();

            // Loop thru the results returned.
            while (GenresDataReader.Read())
            {
                // Add to the list of genres - creates a new row for the collection.
                Genre.Add(new Genre(GenresDataReader["Genre"].ToString()));
            }
        }
        catch (Exception ex)
        {
            errorSw = true;
        }
        finally
        {
            if (GenresDataReader != null)
            {
                GenresDataReader.Close();
            }

            dbFunc.CloseDB();
        }

        // Return the list of genre objects.
        return Genre;
    }

Here's the view:

@model MvcMovie.Models.MovieGenreViewModel

@{
    ViewData["Title"] = "Index";
}

List of Movies

    Create New

<form asp-controller="Movies" asp-action="Index" method="get">

        @* A dropdown. *@
        <select asp-for="movieGenre" asp-items="Model.genres">
            <option value="">All</option>
        </select>

        Title: <input type="text" name="searchStringEntered">

        <input type="submit" value="Filter" />

</form>

@* Shows the list of movies. *@

                @Html.DisplayNameFor(model => model.movies[0].Title)

                @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)

                @Html.DisplayNameFor(model => model.movies[0].Genre)

                @Html.DisplayNameFor(model => model.movies[0].Price)

                @Html.DisplayNameFor(model => model.movies[0].Rating)

        @foreach (var item in Model.movies) {

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

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

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

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

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

                    Edit |
                    Details |
                    Delete

         }

This tutorial is using Entity Framework but I am converting it to using ADO.net and stored procedures. The EF version of the drop down works fine.

Here is the the EF versions Index action method. The genre is just the text - no Id associated with it.

    public async Task<IActionResult> Index(string movieGenre, string searchStringEntered)
    {
        IQueryable<string> genreQuery = from m in _context.Movie
                                        orderby m.Genre
                                        select m.Genre;

        var movies = from m in _context.Movie
                     select m;

        if (!String.IsNullOrEmpty(searchStringEntered))
        {
            movies = movies.Where(s => s.Title.Contains(searchStringEntered));
        }

        if (!String.IsNullOrEmpty(movieGenre))
        {
            movies = movies.Where(x => x.Genre == movieGenre);
        }

        // Instantiate the model.
        var movieGenreVM = new MovieGenreViewModel();

        // The SelectList of genres is created by projecting the distinct genres.
        // Sets the models property which is then used in the dropdown of Genres.
        movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());

        // Creates a List object.
        // Movie is populated from the database and used to generate an HTML table of loaded movies.
        movieGenreVM.movies = await movies.ToListAsync();

        return View(movieGenreVM);
    }

Body:
This is an example of how I do it:

        var items = GetItemsFromDB();
        var vals = new List<SelectListItem> {new SelectListItem {Selected = true, Text = "--Select an Item--", Value = "0"}};

        vals.AddRange(items.Select(item => new SelectListItem
        {
            Selected = false, Text = item.Type, Value = item.Id.ToString()
        }));

        var result = new SelectList(vals, "Value", "Text");

As you can see when i convert it to a SelectList I specify the Value and Text as dataValueField and dataTextField.

In your case you need properties for these values and specify them when you "cast it" using the SelectList constructor.

In my view I do this:

<select asp-for="Model.ItemId" asp-items="Model.MyItemSelectList"></select>

Where Model.MyItemSelectList can be a List of SelectListItem

Another way to bind it to a collection is like this:

                                     <select asp-for="Model.MyItemId">
                                        <option value="">-- Select Item --</option>
                                        @{
                                             foreach (var item in Model.MyItems)
                                             {
                                                 <option value="@item.Key">@item.Value</option>
                                             }
                                        }
                                    </select>

Where item has Key and Value properties.  The properties can be names whatever you want. In this case "item" has those properties.


来源: stackexchange

问:
cannot read property 'client_secret' of undefined
I have tried to create a sample program using Node.js, following instructions from https://developers.google.com/google-apps/activity/v1/quickstart/nodejs

I throws an error saying cannot read property 'client_secret' of undefined when trying to run it.

Looking for your valuable suggestions.

Thanks in advance.

答: I had this problem, but I had the wrong type of credentials file. I initially used "Web Server (Nodejs)...", and it had the "web" heading instead of the "installed", but when I did it again, and selected "Windows UI (cmd line)", I got the file with the correct format.</p>

ContentLicense: CC BY-SA 3.0


问:
how to copy a range of cells(n cells) from a column in one sheet and paste it, with a blank cell inserted after every 7(n cells), to another sheet?
how to copy a range of cells(N cells) from a column in one sheet and paste it, with a blank cell inserted after every 7(n cells), to another sheet?
Ex: Given image below

答:
I think it's a pretty easy task and you are making it sound difficult. Here's the code to help you out.

```<code>Sub do_something()
    last_row = ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).End(xlDown).Row

   j = 1
   For i = 1 To last_row

      If i Mod 8 = 0 Then
         j = j + 1
      End If
      Cells(j, 2).Value = Cells(i, 1).Value
      j = j + 1

   Next i
End Sub
</code>```

And as you mentioned in your comment, below code will satisfy your need.

```<code>Sub do_something2()
   last_row = ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).End(xlDown).Row
   j = 1
   i = 1
   Do While i <= last_row
       Worksheets("Sheet2").Range(Worksheets("Sheet2").Cells(j, 1),
       Worksheets("Sheet2").Cells(j + 6, 1)).Value = _
       Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(i, 1),
       Worksheets("Sheet1").Cells(i + 6, 1)).Value

   j = j + 8
   i = i + 7
   Loop
End Sub
</code>```

Body:
I think it's a pretty easy task and you are making it sound difficult. Here's the code to help you out.

Sub do_something()
    last_row = ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).End(xlDown).Row

   j = 1
   For i = 1 To last_row

      If i Mod 8 = 0 Then
         j = j + 1
      End If
      Cells(j, 2).Value = Cells(i, 1).Value
      j = j + 1

   Next i
End Sub

And as you mentioned in your comment, below code will satisfy your need.

Sub do_something2()
   last_row = ThisWorkbook.Worksheets("Sheet1").Cells(1, 1).End(xlDown).Row
   j = 1
   i = 1
   Do While i <= last_row
       Worksheets("Sheet2").Range(Worksheets("Sheet2").Cells(j, 1),
       Worksheets("Sheet2").Cells(j + 6, 1)).Value = _
       Worksheets("Sheet1").Range(Worksheets("Sheet1").Cells(i, 1),
       Worksheets("Sheet1").Cells(i + 6, 1)).Value

   j = j + 8
   i = i + 7
   Loop
End Sub


问:
Are parameters to range() re-evaluated at each iteration of the loop?
If I use functions for range parameters, do they get called every time through?</p>

```<code>for i in range(min(some_list), max(other_list)):
    ...
</code>```

答:
The functions min and max are called before the range object/list is created i.e. argument expressions are evaluated before function call.

Therefore, they are only called once.

Body:
If I use functions for range parameters, do they get called every time through?

for i in range(min(some_list), max(other_list)):
    ...


问:
SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"
I am using windows 8.1 and SQL Server 2012.

I was using an OS account "Manoj" for accessing SQL SERVER with windows authentication.
Recently I have deleted my user account "Manoj" of OS and created a new account with same name "Manoj".

But the system took the new account as "Manoj_2". This change keeps me out from accessing the old databases, I have created.

It says that

The database [dbName] is not accessible. (ObjectExplorer)

whenever I try to access any of the previous DBs I have created.

I used to create new login in SQL Server for "Manoj_2", with default DB as "master". But still the problem persists.

I cannot able to detach the DBs. I am unable to expand the DBs.

Note: In OS, I have admin rights for the "Manoj" account.

Please anybody tell me, what to do? either with OS or with SQL Server

答: In my case, restarting SQL Server Service was enough to resolve the issue.</p>


问:
Django: how to stay DRY using custom querysets with Q object?
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself:

```<code>class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service])
        return self.filter(complex_query)
</code>```

What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation.
I tried something like that, but it raises a ValueError: too many values to unpack (expected 2):

```<code>def displayable(self, service):
    complex_query = Q(self.permanent()) | Q(self.scheduled(service))
    return self.filter(complex_query)
</code>```

Thanks for your help.

答:
Querysets can be combined with bitwise or too:

```<code>class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        return self.permanent() | self.scheduled(service)
</code>```

Body:
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself:

class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service])
        return self.filter(complex_query)

What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation.
I tried something like that, but it raises a ValueError: too many values to unpack (expected 2):

def displayable(self, service):
    complex_query = Q(self.permanent()) | Q(self.scheduled(service))
    return self.filter(complex_query)

Thanks for your help.

Body:
Querysets can be combined with bitwise or too:

class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        return self.permanent() | self.scheduled(service)


问:
HP QC ALM REST API - Defect creation issue
I  am trying to create a new defect. I have to do it using REST API in my C# ASP.Net project. Below is the used URL:

```<code>qcbin/rest/domains/TESTDOMAIN/projects/TESTPROJECT/defects
</code>```

Below is my request body :

```<code><?xml version="1.0" encoding="UTF-8"?>
<Entity Type="defect">
  <Fields>
    <Field Name="priority">
      <Value>3-High</Value>
    </Field>
    <Field Name="description">
      <Value>test description</Value>
    </Field>
    <Field Name="name">
      <Value>test with rest API</Value>
    </Field>
    <Field Name="creation-time">
      <Value>2011-08-16 11:34:08</Value>
    </Field>
  </Fields>
</Entity>
</code>```

I can successfully create the defect only if I do not use creation-time in XML. May I know how to use columns that contain hyphen?

I have written the code on C#. Below is my C# code

```<code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HPALMUrl + "/rest/domains/" + HPALMDomain + "/projects/" + HPALMProject + "/defects/");
request.Method = "POST";
request.Accept = "application/xml";
request.ContentType = "application/xml";
authRequest.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
request.CookieContainer = createSessionRequest.CookieContainer; //Authenticated cookie
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();

string responseText = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
    responseText = "Update completed";
else
    responseText = "Error in update";
</code>```

I am facing this hyphen column problem when updating Test table column also. So, please let me know how to use hyphen contain column

Thanks in advance!

答:
How to approach,

Make a get request to extract all the field names and data format it accepts.

Eg: https://almserver/qcbin/rest/domains/WWT/projects/content/defects/1

Identify the required fields.

Set the request header to XML/JSON according to your payload

Defect Creation in Python

```<code>ALM_USER_NAME = "username"
ALM_PASSWORD = "password"
ALM_DOMAIN = "domain"

ALM_URL = "https://almserver/qcbin/"
AUTH_END_POINT = ALM_URL + "authentication-point/authenticate"
QC_SESSION_END_POINT = ALM_URL + "rest/site-session"
QC_LOGOUT_END_POINT = ALM_URL + "authentication-point/logout"
ALM_MIDPOINT = ALM_URL + "rest/domains/" + ALM_DOMAIN + "/projects/"

def generate_xml_data(inputdata):
    '''
        Function    :   generateXMLData
        Description :   Generate an xml string
        Parameters  :   Dictionary of variable
    '''
    root = Element('Entity')
    root.set('Type', inputdata['Type'])
    inputdata.pop('Type')
    childs = SubElement(root, 'Fields')

    for key, value in inputdata.iteritems():
        child1 = SubElement(childs, 'Field')
        child1.set('Name', key)
        child2 = SubElement(child1, 'Value')
        child2.text = value
    return tostring(root)

def createdefect():
    '''
        alm defect
    '''
    alm_session = requests.Session()
    # Login
    try:
        res = alm_session.post(AUTH_END_POINT, auth=HTTPBasicAuth(
            ALM_USER_NAME, ALM_PASSWORD))
        if res.status_code == 200:
            print "ALM: Logged in"
        alm_session.post(QC_SESSION_END_POINT)
        alm_session.headers.update({'Accept': 'application/json',
                                    'Content-Type': 'application/xml'})
        # Get all the projects
        res = alm_session.get(ALM_MIDPOINT)

    # Post a New Defect
    defect = dict()
    defect['Type'] = 'defect'
    defect['name'] = 'StackOverflow'
    defect['user-10'] = 'Content'  # User defined field
    defect['severity'] = '1-Low'
    defect['priority'] = '1-Low'
    defect['detected-by'] = 'userid'
    defect['creation-time'] = '2017-11-13'

    # Call the generic method to build the xml data
    defect_payload = generate_xml_data(defect)

    response = alm_session.post(ALM_MIDPOINT + "content/defects", data=defect_payload)
    print response.url

except (KeyboardInterrupt, SystemExit, Exception) as err:
    print "keyboard interrupt"
    print err.message
finally:
    if alm_session:
        res = alm_session.post(QC_LOGOUT_END_POINT)
        if res.status_code == 200:
            print "ALM: Logged out"

if __name__ == "__main__":
    try:
        createdefect()
    except (KeyboardInterrupt, SystemExit):
        print "done with errors"

</code>```

Body:
I  am trying to create a new defect. I have to do it using REST API in my C# ASP.Net project. Below is the used URL:

qcbin/rest/domains/TESTDOMAIN/projects/TESTPROJECT/defects

Below is my request body :

<?xml version="1.0" encoding="UTF-8"?>
<Entity Type="defect">
  <Fields>
    <Field Name="priority">
      <Value>3-High</Value>
    </Field>
    <Field Name="description">
      <Value>test description</Value>
    </Field>
    <Field Name="name">
      <Value>test with rest API</Value>
    </Field>
    <Field Name="creation-time">
      <Value>2011-08-16 11:34:08</Value>
    </Field>
  </Fields>
</Entity>

I can successfully create the defect only if I do not use creation-time in XML. May I know how to use columns that contain hyphen?

I have written the code on C#. Below is my C# code

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HPALMUrl + "/rest/domains/" + HPALMDomain + "/projects/" + HPALMProject + "/defects/");
request.Method = "POST";
request.Accept = "application/xml";
request.ContentType = "application/xml";
authRequest.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
request.CookieContainer = createSessionRequest.CookieContainer; //Authenticated cookie
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();

string responseText = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
    responseText = "Update completed";
else
    responseText = "Error in update";

I am facing this hyphen column problem when updating Test table column also. So, please let me know how to use hyphen contain column

Thanks in advance!

Body:
How to approach,

Make a get request to extract all the field names and data format it accepts.

Eg: https://almserver/qcbin/rest/domains/WWT/projects/content/defects/1

Identify the required fields.

Set the request header to XML/JSON according to your payload

Defect Creation in Python

ALM_USER_NAME = "username"
ALM_PASSWORD = "password"
ALM_DOMAIN = "domain"

ALM_URL = "https://almserver/qcbin/"
AUTH_END_POINT = ALM_URL + "authentication-point/authenticate"
QC_SESSION_END_POINT = ALM_URL + "rest/site-session"
QC_LOGOUT_END_POINT = ALM_URL + "authentication-point/logout"
ALM_MIDPOINT = ALM_URL + "rest/domains/" + ALM_DOMAIN + "/projects/"

def generate_xml_data(inputdata):
    '''
        Function    :   generateXMLData
        Description :   Generate an xml string
        Parameters  :   Dictionary of variable
    '''
    root = Element('Entity')
    root.set('Type', inputdata['Type'])
    inputdata.pop('Type')
    childs = SubElement(root, 'Fields')

    for key, value in inputdata.iteritems():
        child1 = SubElement(childs, 'Field')
        child1.set('Name', key)
        child2 = SubElement(child1, 'Value')
        child2.text = value
    return tostring(root)

def createdefect():
    '''
        alm defect
    '''
    alm_session = requests.Session()
    # Login
    try:
        res = alm_session.post(AUTH_END_POINT, auth=HTTPBasicAuth(
            ALM_USER_NAME, ALM_PASSWORD))
        if res.status_code == 200:
            print "ALM: Logged in"
        alm_session.post(QC_SESSION_END_POINT)
        alm_session.headers.update({'Accept': 'application/json',
                                    'Content-Type': 'application/xml'})
        # Get all the projects
        res = alm_session.get(ALM_MIDPOINT)

    # Post a New Defect
    defect = dict()
    defect['Type'] = 'defect'
    defect['name'] = 'StackOverflow'
    defect['user-10'] = 'Content'  # User defined field
    defect['severity'] = '1-Low'
    defect['priority'] = '1-Low'
    defect['detected-by'] = 'userid'
    defect['creation-time'] = '2017-11-13'

    # Call the generic method to build the xml data
    defect_payload = generate_xml_data(defect)

    response = alm_session.post(ALM_MIDPOINT + "content/defects", data=defect_payload)
    print response.url

except (KeyboardInterrupt, SystemExit, Exception) as err:
    print "keyboard interrupt"
    print err.message
finally:
    if alm_session:
        res = alm_session.post(QC_LOGOUT_END_POINT)
        if res.status_code == 200:
            print "ALM: Logged out"

if __name__ == "__main__":
    try:
        createdefect()
    except (KeyboardInterrupt, SystemExit):
        print "done with errors"


问:
Node.js website with SSL, getting "Refused to connect" error
I've successfully created the SSL certificate and the key for my website via OpenSSL. I uploaded them in a folder on the server. I get no errors when I start the server.

But when I try to load the website in the browser using https://, I get the "refused to connect" error.

Here is the code I am using to create the https server:

```<code>var app = require('../app');
    var debug = require('debug')('gameserver:server');
    const https = require('https');
    const fs = require('fs');

    const options = {
        port: normalizePort(process.env.PORT || '80'),
        key: fs.readFileSync('../keys/key.key'),
        cert: fs.readFileSync('../keys/cert.crt')
    };

    var server = https.createServer(options);
    require('../config/socket')(server);

    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);

    function normalizePort(val) {
        var port = parseInt(val, 10);

        if (isNaN(port)) {
            return val;
        }

        if (port >= 0) {
            return port;
        }

        return false;
    }

    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }

        var bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    }

    function onListening() {
        var addr = server.address();
        var bind = typeof addr === 'string'
            ? 'pipe ' + addr
            : 'port ' + addr.port;
        debug('Listening on ' + bind);
    }
</code>```

Any suggestions?

答:
I managed to fix this. Indeed, it needed to be port 443. Also, in the createServer function I forgot to pass app as a parameter. Here is a working example:</p>

```<code>var app = require('../app');
var debug = require('debug')('gameserver:server');
const https = require('https');
const fs = require('fs');

const options = {
    port: normalizePort(process.env.PORT || '80'),
    key: fs.readFileSync('../keys/key.key'),
    cert: fs.readFileSync('../keys/cert.crt')
};

    var server = https.createServer(options, app).listen(443, function() {
    console.log("Express server listening on port 443");
});
require('../config/socket')(server);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        return val;
    }

    if (port >= 0) {
        return port;
    }

    return false;
}

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}

function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    debug('Listening on ' + bind);
}
</code>```

Body:
I've successfully created the SSL certificate and the key for my website via OpenSSL. I uploaded them in a folder on the server. I get no errors when I start the server.

But when I try to load the website in the browser using https://, I get the "refused to connect" error.

Here is the code I am using to create the https server:

var app = require('../app');
    var debug = require('debug')('gameserver:server');
    const https = require('https');
    const fs = require('fs');

    const options = {
        port: normalizePort(process.env.PORT || '80'),
        key: fs.readFileSync('../keys/key.key'),
        cert: fs.readFileSync('../keys/cert.crt')
    };

    var server = https.createServer(options);
    require('../config/socket')(server);

    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);

    function normalizePort(val) {
        var port = parseInt(val, 10);

        if (isNaN(port)) {
            return val;
        }

        if (port >= 0) {
            return port;
        }

        return false;
    }

    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }

        var bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    }

    function onListening() {
        var addr = server.address();
        var bind = typeof addr === 'string'
            ? 'pipe ' + addr
            : 'port ' + addr.port;
        debug('Listening on ' + bind);
    }

Any suggestions?

Body:
I managed to fix this. Indeed, it needed to be port 443. Also, in the createServer function I forgot to pass app as a parameter. Here is a working example:

var app = require('../app');
var debug = require('debug')('gameserver:server');
const https = require('https');
const fs = require('fs');

const options = {
    port: normalizePort(process.env.PORT || '80'),
    key: fs.readFileSync('../keys/key.key'),
    cert: fs.readFileSync('../keys/cert.crt')
};

    var server = https.createServer(options, app).listen(443, function() {
    console.log("Express server listening on port 443");
});
require('../config/socket')(server);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val) {
    var port = parseInt(val, 10);

    if (isNaN(port)) {
        return val;
    }

    if (port >= 0) {
        return port;
    }

    return false;
}

function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}

function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    debug('Listening on ' + bind);
}


问:
django unique model with one to one relashionship
I have 2 models. each of them can have int_number via one-to-one relashionship with IntNumber model.
So i need to do IntNumber.number unique for them(user and group should not refer same IntNumber). Extra lines are omitted.</p>

```<code>class Group(models.Model):

    int_number = models.OneToOneField(
        IntNumber,
        related_name='int_number',
        on_delete=models.CASCADE,
        )

class User(AbstractUser):

    int_number = models.OneToOneField(
        IntNumber,
        related_name='int_number',
        on_delete=models.CASCADE,
        )

class IntNumber(models.Model):

    number = models.IntegerField(unique=True)
</code>```

答:
Put user and group as foreign key inside IntNumber so when ever Unique IntNumber is generated you can explicitly assign a user and group to it. </p>

```<code>class IntNumber(models.Model):

    number = models.IntegerField(unique=True)
    user =   models.ForeignKey(User)
    group =  models.ForeignKey(Group)
</code>```

<p>Note: You can add null=True to user and group if you want to generate intNumber only for 1 of them </p>

Body:
I have 2 models. each of them can have int_number via one-to-one relashionship with IntNumber model.
So i need to do IntNumber.number unique for them(user and group should not refer same IntNumber). Extra lines are omitted.

class Group(models.Model):

    int_number = models.OneToOneField(
        IntNumber,
        related_name='int_number',
        on_delete=models.CASCADE,
        )

class User(AbstractUser):

    int_number = models.OneToOneField(
        IntNumber,
        related_name='int_number',
        on_delete=models.CASCADE,
        )

class IntNumber(models.Model):

    number = models.IntegerField(unique=True)

Body:
Put user and group as foreign key inside IntNumber so when ever Unique IntNumber is generated you can explicitly assign a user and group to it.

class IntNumber(models.Model):

    number = models.IntegerField(unique=True)
    user =   models.ForeignKey(User)
    group =  models.ForeignKey(Group)

Note: You can add null=True to user and group if you want to generate intNumber only for 1 of them


问:
How to create specific table in MySQL DB using Hibernate
so following situation:

I am using Hibernate to upload/download data to and from the database, which works fine.

Currently I have two tables, "Parent"(which is the parent) and "Child"(which is the child). I have a OneToMany / ManyToOne relationship. I only upload the parent and the child is automatically uploaded due to cascade.
The Parent.class has a List(Child).

If an entity of "Parent" is changed/updated, I want to move the "old version" into a table called "Parent_OLD" (and of course the child via cascade) and add a time stamp to the old entity.

So the problem I am currently encountering is:
I have tried to solve it by creating a new class "Parent_OLD" which looks exactly like the "Parent" except for the time stamp.
So what I did is: Whenever I upload new data to the DB, I check if the entity already exists and if it does I pass the data via "getters" to "Parent_OLD". This works fine so far, because I only have like 3 attributes I need to pass, but if I end up with more fields, it would be handy to have a different solution to this.

But what does not work is to move the "child_OLD" to the "Child_OLD".
So as mentioned above, the Parent.class has a List(Child).
Child_NEW and Child_OLD actually look exactly alike, because they do not need a time stamp. But due to the Hibernate Annotation on top of the Child.class every entity of Child.class is loaded into "Child"-table.

So I created a Child_OLD.class.
This means:
I have a current Parent entity, with a List(Child).
I want to pass the parent (including the list) to the Parent_OLD entity.

But I cannot cast the List(Child) to List(Child_OLD). I have tried casting it to a list of objects and then to Child_OLD, but this did not work.
Passing the attributes via "getters" is no option as the class has like 60 fields.
I also tried creating an abstract class "Child" but I still did not manage to get it to work.

So I thought it would be amazingly simple if I could tell Hibernate to load certain entities into a different table. So maybe something like an annotation above the CheckIfExistsAndIfItDoesCopyToOldTable-Method. Is this possible?
Or does anyone know how I could solve my problem?

I guess I need to apologize because I do not know how clear I managed to explain my problem.
So sorry for the possibly confusing text and thank you in advance for your ideas!

Edit:
I want to backup the Parent as well as the Child.
But this should happen via cascade if possible.
So, by backing up the Parent, the List with the children should be moved into the Child-BackUp-Table.

答:
Hibernate supports Table Per Concrete class

as you mentioned you will need to "clone" the table with same data adding only time stamp.

you may try this:

```<code>@Entity
@Table(name = "child")
class Child
    // variables ..

@Entity
@Table(name = "child_history")
class Child_OLD extends Child
    // adding time stamp variable

@Entity
@Table(name = "parent")
class Parent
    // variables ..
    List<Child> ..

@Entity
@Table(name = "parent_history")
class Parent_OLD extends Parent
    // adding time stamp variable
</code>```

the 2 sub-classes Child_OLD and Parent_OLD will be almost empty..
all you have to implement the base Child and Parent classes,
and in the sub-classes (Child_OLD and Parent_OLD) you will have to create a clone constructors.

the clone constructors will have to preform a deep copy of the object (also for the List..)

to have minimal dates/timestamps manipulations in java, you may use mysql built-in features which gives a default value on insert/update and will save you time instead of managing date variables in java as below:

```<code>/* managed by DB column definition */
@Column(
        name = "SYS_CREATION_DATE",
        insertable=false,
        updatable=false,
        columnDefinition="DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        )
private Date sysCreationDate;
</code>```

pom.xml dependencies i used (not sure if relevant)

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.5</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>1.5.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.11.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.11.Final</version>
</dependency>
</code>```

hope it helps

Body:
Hibernate supports Table Per Concrete class

as you mentioned you will need to "clone" the table with same data adding only time stamp.

you may try this:

@Entity
@Table(name = "child")
class Child
    // variables ..

@Entity
@Table(name = "child_history")
class Child_OLD extends Child
    // adding time stamp variable

@Entity
@Table(name = "parent")
class Parent
    // variables ..
    List<Child> ..

@Entity
@Table(name = "parent_history")
class Parent_OLD extends Parent
    // adding time stamp variable

the 2 sub-classes Child_OLD and Parent_OLD will be almost empty..
all you have to implement the base Child and Parent classes,
and in the sub-classes (Child_OLD and Parent_OLD) you will have to create a clone constructors.

the clone constructors will have to preform a deep copy of the object (also for the List..)

to have minimal dates/timestamps manipulations in java, you may use mysql built-in features which gives a default value on insert/update and will save you time instead of managing date variables in java as below:

/* managed by DB column definition */
@Column(
        name = "SYS_CREATION_DATE",
        insertable=false,
        updatable=false,
        columnDefinition="DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
        )
private Date sysCreationDate;

pom.xml dependencies i used (not sure if relevant)

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.5</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>1.5.7.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.11.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.11.Final</version>
</dependency>

hope it helps


问:
Pumping Windows Messages During Long Operation?
I'm getting the following message on a big operation that I'm running:

The CLR has been unable to transition
  from COM context 0x1fe458 to COM
  context 0x1fe5c8 for 60 seconds. The
  thread that owns the destination
  context/apartment is most likely
  either doing a non pumping wait or
  processing a very long running
  operation without pumping Windows
  messages. This situation generally has
  a negative performance impact and may
  even lead to the application becoming
  non responsive or memory usage
  accumulating continually over time. To
  avoid this problem, all single
  threaded apartment (STA) threads
  should use pumping wait primitives
  (such as CoWaitForMultipleHandles) and
  routinely pump messages during long
  running operations.

How do I send windows messages so that this error will no longer occur on long operations?

答:
I know this was asked years ago, but hoping this will help others down the road. If you don't want to worry about doing a background worker, or pumping messages, a simple workaround is simply updating something on the UI. For example, I have a tool that only I use, so I don't care if it uses the UI thread. So I simply update a textbox.text on the UI to whatever I'm working on. here is a snippet of the code. This is a very hacky, and probably incorrect way to do it professionally, but it works. </p>

```<code>for (int i = 0; i < txtbxURL.LineCount; i++)
{
    mytest.NavigateTo(mytest.strURL);
    mytest.SetupWebDoc(mytest.strURL);
    strOutput = mytest.PullOutPutText(mytest.strURL);
    strOutput = mytest.Tests(strOutput);
    mytest.CheckAlt(mytest.strURL);
    mytest.WriteError(txtbxWriteFile.Text);
    txtblCurrentURL.Text = mytest.strURL;
    //This ^^^ is what is being updated, which keeps the thread from throwing the exception noted above.
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I know this was asked years ago, but hoping this will help others down the road. If you don't want to worry about doing a background worker, or pumping messages, a simple workaround is simply updating something on the UI. For example, I have a tool that only I use, so I don't care if it uses the UI thread. So I simply update a textbox.text on the UI to whatever I'm working on. here is a snippet of the code. This is a very hacky, and probably incorrect way to do it professionally, but it works.

for (int i = 0; i < txtbxURL.LineCount; i++)
{
    mytest.NavigateTo(mytest.strURL);
    mytest.SetupWebDoc(mytest.strURL);
    strOutput = mytest.PullOutPutText(mytest.strURL);
    strOutput = mytest.Tests(strOutput);
    mytest.CheckAlt(mytest.strURL);
    mytest.WriteError(txtbxWriteFile.Text);
    txtblCurrentURL.Text = mytest.strURL;
    //This ^^^ is what is being updated, which keeps the thread from throwing the exception noted above.
}


问:
pagination in html page
I am showing all my products in rows, but the code which I am using shows the result in columns. I am using the datatable pagination, I don't know how I am using pagination in my web site please help me. enter image description here</p>

```<code><table  id="datatables" class="table no-margin">
    <thead >
         <tr>
             <th></th>
         </tr>
    </thead>
    <tbody class="df">
        <?php
            $pr = mysqli_query($link,"select * from product where company_id = '".$company_id."'");
            while($prd = mysqli_fetch_array($pr))
            {
                $price = mysqli_fetch_array(mysqli_query($link,"select * from
                admin_price where p_code = '".$prd['p_code']."'"));
            ?>
        <tr>
    <td>
        <?php echo("<a href='single.php?
            p_code=".$prd['p_code']."'>"); ?>
        <div class="part-secz">
            <img src="<?php echo("images/".$prd['image']); ?>" alt=""/>
            <div class="part-infoz">
                <?php
                    echo("<a class='asd' href='single.php?p_code=".$prd['p_code']."'>");
                ?>
                <h5>
                    <?php echo($prd['p_code']); ?><span>$ <?php echo($price['price']); ?>
                    </span>
                </h5>
                <?php
                    echo("</a>");?>
                    <?php echo("<a class='add-cart' href='single.php p_code=".$prd['p_code']."'>"); ?> Quick View<?php
                    echo("</a>");?>
                    <?php echo("<a class='qck' href='single.php p_code=".$prd['p_code']."'>"); ?>BUY NOW</a><?php
                    echo("</a>");?>
                </div>
            </div>
        </td>
        <div class="clearfix">
        </div>
    </tr>
    <?php
        }
    ?>
</code>```

答:
Basically, your code is a cycle of :

```<code><table  id="datatables" class="table no-margin">
  <thead><tr><th></th></tr></thead>
  <tbody class="df">
    <?php
        $pr = mysqli_query($link,"select * from product where company_id = '".$company_id."'");
        while($prd = mysqli_fetch_array($pr))
        {
     <tr>
      <td>
         {{some display logic}}
      </td>
      <div class="clearfix">
      </div>
 </tr>
 <?php } ?>
</code>```

If you want your products to be in one line fix it, so new row is not created

```<code><table  id="datatables" class="table no-margin">
  <thead><tr><th></th></tr></thead>
  <tbody class="df">
     <tr>
    <?php
        $pr = mysqli_query($link,"select * from product where company_id = '".$company_id."'");
        while($prd = mysqli_fetch_array($pr))
        {

      <td>
         {{some display logic}}
      </td>
      <div class="clearfix">
      </div>
      <?php } ?>
 </tr>
</code>```

Title: pagination in html page

Body:
I am showing all my products in rows, but the code which I am using shows the result in columns. I am using the datatable pagination, I don't know how I am using pagination in my web site please help me. enter image description here

        <?php
            $pr = mysqli_query($link,"select * from product where company_id = '".$company_id."'");
            while($prd = mysqli_fetch_array($pr))
            {
                $price = mysqli_fetch_array(mysqli_query($link,"select * from
                admin_price where p_code = '".$prd['p_code']."'"));
            ?>

        <?php echo(""); ?>

            <img src="<?php echo("images/".$prd['image']); ?>" alt=""/>

                <?php
                    echo("");
                ?>

                    <?php echo($prd['p_code']); ?>$ <?php echo($price['price']); ?>

                <?php
                    echo("");?>
                    <?php echo(""); ?> Quick View<?php
                    echo("");?>
                    <?php echo(""); ?>BUY NOW<?php
                    echo("");?>

    <?php
        }
    ?>

Body:
Basically, your code is a cycle of :

<table  id="datatables" class="table no-margin">
  <thead><tr><th></th></tr></thead>
  <tbody class="df">
    <?php
        $pr = mysqli_query($link,"select * from product where company_id = '".$company_id."'");
        while($prd = mysqli_fetch_array($pr))
        {
     <tr>
      <td>
         {{some display logic}}
      </td>
      <div class="clearfix">
      </div>
 </tr>
 <?php } ?>

If you want your products to be in one line fix it, so new row is not created

<table  id="datatables" class="table no-margin">
  <thead><tr><th></th></tr></thead>
  <tbody class="df">
     <tr>
    <?php
        $pr = mysqli_query($link,"select * from product where company_id = '".$company_id."'");
        while($prd = mysqli_fetch_array($pr))
        {

      <td>
         {{some display logic}}
      </td>
      <div class="clearfix">
      </div>
      <?php } ?>
 </tr>


问:
WPF Navigate through child elements or keep track of dynamically created child elements
I have a TabControl where I create tabs dynamically. I am finding it difficult to change the title of the TabItem.

```<code> <TabControl Name="AttorneysTabControl" Grid.Column="2"  Grid.Row="0">
    <TabControl.Resources>
        <DataTemplate x:Key="AttorneyTabHeader">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Names}" Margin="2,0,0,0" FontSize="16" VerticalAlignment="Center" />
                <Button Width="Auto" UseLayoutRounding="False" BorderBrush="Transparent" Background="Transparent" Click="CloseAttorneysTabButtonClick">
                    <Image Source="/images/close-cross-thin-circular-button/close-cross-thin-circular-button16.png" Height="16"></Image>
                </Button>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="AttorneyTabContent">
            <local:AttorneyDetails></local:AttorneyDetails>
        </DataTemplate>
    </TabControl.Resources>
</code>```

For each TabItem I set a HeaderTemplate from the TabControl.Resources like this;

```<code>newTabItem.HeaderTemplate = (System.Windows.DataTemplate)AttorneysTabControl.FindResource("AttorneyTabHeader");
</code>```

But I don't know how to change the contents of the TabItem header once the template has been set. I have tried using DataContext for the TabItem if that's the way to do it but it did not work, so that I could just use Binding in the template. That will be a lot easier.

答:
You should normally write (first line is your unchanged code):

```<code>newTabItem.HeaderTemplate = (System.Windows.DataTemplate)AttorneysTabControl.FindResource("AttorneyTabHeader");
var tabItemData = new TabItemData() { Name="Initial name"} ;
newTabItem.DataContext = tabItemData;
</code>```

And then once you need to update the tab header:

```<code>tabItemData.Name = "New name".
</code>```

If that didn't work, that'd probably because your TabItemData.Name property doesn't notify of its changes. So make sure that your TabItemData class implements INotifyPropertyChanged and that the Name property notifies. Example:

```<code>public class TabItemData : INotifyPropertyChanged
{
  private string name;
  public string Name
  {
    get { return this.name; }

    set
    {
        if (value != this.name)
        {
            this.name= value;
            NotifyPropertyChanged("Name");
        }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void NotifyPropertyChanged(string propertyName)
  {
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
  }

}
</code>```

In case you're lost I suggest reading the Managing data in a WPF application chapter of my Learn WPF MVVM book.

Body:
I have a TabControl where I create tabs dynamically. I am finding it difficult to change the title of the TabItem.

 <TabControl Name="AttorneysTabControl" Grid.Column="2"  Grid.Row="0">
    <TabControl.Resources>
        <DataTemplate x:Key="AttorneyTabHeader">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Names}" Margin="2,0,0,0" FontSize="16" VerticalAlignment="Center" />
                <Button Width="Auto" UseLayoutRounding="False" BorderBrush="Transparent" Background="Transparent" Click="CloseAttorneysTabButtonClick">
                    <Image Source="/images/close-cross-thin-circular-button/close-cross-thin-circular-button16.png" Height="16"></Image>
                </Button>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="AttorneyTabContent">
            <local:AttorneyDetails></local:AttorneyDetails>
        </DataTemplate>
    </TabControl.Resources>

For each TabItem I set a HeaderTemplate from the TabControl.Resources like this;

newTabItem.HeaderTemplate = (System.Windows.DataTemplate)AttorneysTabControl.FindResource("AttorneyTabHeader");

But I don't know how to change the contents of the TabItem header once the template has been set. I have tried using DataContext for the TabItem if that's the way to do it but it did not work, so that I could just use Binding in the template. That will be a lot easier.

Body:
You should normally write (first line is your unchanged code):

newTabItem.HeaderTemplate = (System.Windows.DataTemplate)AttorneysTabControl.FindResource("AttorneyTabHeader");
var tabItemData = new TabItemData() { Name="Initial name"} ;
newTabItem.DataContext = tabItemData;

And then once you need to update the tab header:

tabItemData.Name = "New name".

If that didn't work, that'd probably because your TabItemData.Name property doesn't notify of its changes. So make sure that your TabItemData class implements INotifyPropertyChanged and that the Name property notifies. Example:

public class TabItemData : INotifyPropertyChanged
{
  private string name;
  public string Name
  {
    get { return this.name; }

    set
    {
        if (value != this.name)
        {
            this.name= value;
            NotifyPropertyChanged("Name");
        }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void NotifyPropertyChanged(string propertyName)
  {
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
  }

}

In case you're lost I suggest reading the Managing data in a WPF application chapter of my Learn WPF MVVM book.


问:
How to remove heading numbers in Jupyter during pdf conversion?
When I use the heading tags (# ##, etc) using markdown, they are always converted to numbered sections during pdf-latex conversion.

How to indicate unnumbered headings in markdown in Jupyter Notebook (IPython)?

I realize this can be done by adding a '*' right next to each section directly in the latex document, but is there any other way to do this?

答: If you have the nb extensions active, you can see the contents on the left hand side.  Just before the contents (but after the title "Contents"), there is a small letter "n". If you press the n, it removes the numbering from the headers.</p>


问:
Compiling project in Windows CMD with MySQL connector Jar
I have a Java project, it consists of 3 Java classes, one .properties file (including MySQL username, password etc), and a mysql-connector-java-5.1.41-bin.jar

My question is how I could include the mysql-connector-java-5.1.41-bin.jar when compiling. For this, I do the following right now: Navigate to my Java project folder in CMD -> javac StartApp.java -> java StartApp. It is running well except that it cannot find mysql-connector-java-5.1.41-bin.jar when using methods that requires it.

I am using Windows 7.

What could I do? Everything else is working when running the Jar except that the connection to the MySQL is not working (since it cannot localize the connector Jar). I am getting desperate so any help is much appreciated!

答:
Just add the cp argument to let java know the class path

lets say you are storing all your jar (mysql-connector-java-5.1.41-bin.jar) under lib folder, use this command:

```<code>java -cp "yourMain.jar;lib/*" StartApp
</code>```

Body:
Just add the cp argument to let java know the class path

lets say you are storing all your jar (mysql-connector-java-5.1.41-bin.jar) under lib folder, use this command:

java -cp "yourMain.jar;lib/*" StartApp


问:
Error: Cannot access file bin/Debug/... because it is being used by another process
When I debug my project, I get following error:

"Unable to copy file "obj\Debug\My Dream.exe" to "bin\Debug\My Dream.exe". The process cannot access the file 'bin\Debug\My Dream.exe' because it is being used by another process."

Using Process Explorer, I see that MyApplication.exe was out but System process still uses it although I stopped debug before.
Whenever I change my code and start debug it is going to happen. If I copy project to USB and debug, it runs OK.

Why? How can I fix this error?

I use Window 7 Professional. With Xp I have never got this error.

答: My problem was dotnet got hung up and whenever VS would try to make a new dll, or access an old one, the dotnet process would latch onto the dll and stop visual studio from cloning the dll. Solution is just to end all dotnet tasks in task manager(it will only actually remove the dead one, if you are trying to end one and it won't shut down, that means it's working).</p>


问:
Clickhouse connection refuse
I have a problem with connection to clickhouse-server by http over 8123 port. All parameters are default.

```<code>Status: Downloaded newer image for yandex/clickhouse-server:latest
Include not found: clickhouse_remote_servers
Include not found: clickhouse_compression
2017.11.09 13:05:37.975332 [ 1 ] <Warning> Application: Logging to console
2017.11.09 13:05:37.978638 [ 1 ] <Information> : Starting daemon with revision 54310
2017.11.09 13:05:37.978733 [ 1 ] <Information> Application: starting up
2017.11.09 13:05:37.979947 [ 1 ] <Debug> Application: rlimit on number of file descriptors is 1048576
2017.11.09 13:05:37.979979 [ 1 ] <Debug> Application: Initializing DateLUT.
2017.11.09 13:05:37.980015 [ 1 ] <Trace> Application: Initialized DateLUT with time zone Zulu'.
2017.11.09 13:05:37.980651 [ 1 ] <Debug> Application: Configuration parameter 'interserver_http_host' doesn't exist or exists and empty. Will use 'c9a1a0a75b97' as replica host.
2017.11.09 13:05:37.980783 [ 1 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/users.xml'
2017.11.09 13:05:37.983605 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.983633 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.984168 [ 1 ] <Information> Application: Loading metadata.
2017.11.09 13:05:37.984738 [ 1 ] <Information> DatabaseOrdinary (default): Total 0 tables.
2017.11.09 13:05:37.984766 [ 1 ] <Information> DatabaseOrdinary (default): Starting up tables.
2017.11.09 13:05:37.984999 [ 1 ] <Debug> Application: Loaded metadata.
2017.11.09 13:05:37.985454 [ 1 ] <Information> Application: Listening http://0.0.0.0:8123
2017.11.09 13:05:37.987644 [ 1 ] <Information> Application: Listening tcp: 0.0.0.0:9000
2017.11.09 13:05:37.987692 [ 1 ] <Information> Application: Listening interserver: 0.0.0.0:9009
2017.11.09 13:05:37.988186 [ 1 ] <Information> Application: Available RAM = 1.95 GiB; physical cores = 4; threads = 4.
2017.11.09 13:05:37.988212 [ 1 ] <Information> Application: Ready for connections.
2017.11.09 13:05:39.980980 [ 2 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/config.xml'
2017.11.09 13:05:39.985393 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_remote_servers
2017.11.09 13:05:39.985462 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_compression

$ curl 'http://localhost:8123/'
curl: (7) Failed to connect to localhost port 8123: Connection refused
</code>```

Please help me to resolve this problem.

答:
UPD

If you don't want to change a network type, a good solution will be to publish a container's port to the host. It can be done with the -p HOST_PORT:CONTAINER_PORT argument. In your case, it would be -p 8123:8123. An example:
docker run -d --name clickhouse-server --ulimit nofile=262144:262144 -p 8123:8123 yandex/clickhouse-server

Original answer

It seems like a docker container is attached to a network you don't have an access to from your host machine. Try to launch an image with --net=host flag. Then, run curl again.

Additional information about docker network types and its abilities can be found in the official documentation

Title: Clickhouse connection refuse

Body:
I have a problem with connection to clickhouse-server by http over 8123 port. All parameters are default.

Status: Downloaded newer image for yandex/clickhouse-server:latest
Include not found: clickhouse_remote_servers
Include not found: clickhouse_compression
2017.11.09 13:05:37.975332 [ 1 ] <Warning> Application: Logging to console
2017.11.09 13:05:37.978638 [ 1 ] <Information> : Starting daemon with revision 54310
2017.11.09 13:05:37.978733 [ 1 ] <Information> Application: starting up
2017.11.09 13:05:37.979947 [ 1 ] <Debug> Application: rlimit on number of file descriptors is 1048576
2017.11.09 13:05:37.979979 [ 1 ] <Debug> Application: Initializing DateLUT.
2017.11.09 13:05:37.980015 [ 1 ] <Trace> Application: Initialized DateLUT with time zone Zulu'.
2017.11.09 13:05:37.980651 [ 1 ] <Debug> Application: Configuration parameter 'interserver_http_host' doesn't exist or exists and empty. Will use 'c9a1a0a75b97' as replica host.
2017.11.09 13:05:37.980783 [ 1 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/users.xml'
2017.11.09 13:05:37.983605 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.983633 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.984168 [ 1 ] <Information> Application: Loading metadata.
2017.11.09 13:05:37.984738 [ 1 ] <Information> DatabaseOrdinary (default): Total 0 tables.
2017.11.09 13:05:37.984766 [ 1 ] <Information> DatabaseOrdinary (default): Starting up tables.
2017.11.09 13:05:37.984999 [ 1 ] <Debug> Application: Loaded metadata.
2017.11.09 13:05:37.985454 [ 1 ] <Information> Application: Listening http://0.0.0.0:8123
2017.11.09 13:05:37.987644 [ 1 ] <Information> Application: Listening tcp: 0.0.0.0:9000
2017.11.09 13:05:37.987692 [ 1 ] <Information> Application: Listening interserver: 0.0.0.0:9009
2017.11.09 13:05:37.988186 [ 1 ] <Information> Application: Available RAM = 1.95 GiB; physical cores = 4; threads = 4.
2017.11.09 13:05:37.988212 [ 1 ] <Information> Application: Ready for connections.
2017.11.09 13:05:39.980980 [ 2 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/config.xml'
2017.11.09 13:05:39.985393 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_remote_servers
2017.11.09 13:05:39.985462 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_compression

$ curl 'http://localhost:8123/'
curl: (7) Failed to connect to localhost port 8123: Connection refused

Please help me to resolve this problem.

ContentLicense: CC BY-SA 4.0


问:
sqlcmd script with spaces in filename
I have a simple SQLCMD script that includes some lines like this:

```<code>/* Load data into Exampletable */
BULK INSERT dbo.Example
    /* NOTE: I've tried single AND double quotes here. */
    FROM "C:\Example Filepath\test.csv"
    WITH
    (
            /* skip the first row containing column names */
            FIRSTROW = 2,
            /* specify how fields are separated */
            FIELDTERMINATOR = '|',
            /* specify how lines end */
            ROWTERMINATOR = '\n'
    )
</code>```

When I run it on the command line, I get an error like this:

Sqlcmd: 'C:\Example': Invalid filename.

I think that having a space in the path is causing the path to be cut off, but I can't figure out a syntax that works. Does anybody have any experience with this?

答:
The error message sounds like sqlcmd cannot find the .sql file.

Try sqlcmd "c:\example filepath\test.sql" from the command prompt.

Strings are quoted with single quotes in TSQL, with double quotes in cmd.

Title: sqlcmd script with spaces in filename

Body:
I have a simple SQLCMD script that includes some lines like this:

/* Load data into Exampletable */
BULK INSERT dbo.Example
    /* NOTE: I've tried single AND double quotes here. */
    FROM "C:\Example Filepath\test.csv"
    WITH
    (
            /* skip the first row containing column names */
            FIRSTROW = 2,
            /* specify how fields are separated */
            FIELDTERMINATOR = '|',
            /* specify how lines end */
            ROWTERMINATOR = '\n'
    )

When I run it on the command line, I get an error like this:

Sqlcmd: 'C:\Example': Invalid filename.

I think that having a space in the path is causing the path to be cut off, but I can't figure out a syntax that works. Does anybody have any experience with this?


问:
Python - ImportError: No module Cloud Dataproc
I am having an issue with Google Cloud Dataproc with the structuring of my python project. I have a number of files which are all in the same folders and which call one another through import. The overall program runs fine locally.

However, when I place it in Google Cloud Dataproc, I have an issue with import. I have tried the answers presented in this Python can't find my module answer but to no effect.

The error is the following:

```<code>from model import PolicyEmergence
ImportError: No module named model
</code>```

I tried to force the path using sys.path.insert(0, 'gs://bucket-name/') but to no avail. I am not sure if this is due to the changing path every time I run the job.

Any help would be welcome, thanks.

答:
You probably want:</p>

```<code>from model import PolicyEmergence
</code>```

Body:
I am having an issue with Google Cloud Dataproc with the structuring of my python project. I have a number of files which are all in the same folders and which call one another through import. The overall program runs fine locally.

However, when I place it in Google Cloud Dataproc, I have an issue with import. I have tried the answers presented in this Python can't find my module answer but to no effect.

The error is the following:

from model import PolicyEmergence
ImportError: No module named model

I tried to force the path using sys.path.insert(0, 'gs://bucket-name/') but to no avail. I am not sure if this is due to the changing path every time I run the job.

Any help would be welcome, thanks.

Body:
You probably want:

from model import PolicyEmergence


问:
Why the integer data types hexadecimal, octal and binary are getting converted to decimal type and then displayed in a browser?
I'm using PHP 7.1.11

I've following PHP code :

```<code><?php
$a = 0123; // an octal number (equivalent to 83 decimal)
$b = 0x1A; // a hexadecimal number (equivalent to 26 decimal)
$c = 0b11111111; // a binary number (equivalent to 255 decimal)

var_dump($a); //Output : int(83) int(26) int(255)
var_dump($b); //Output : int(26) int(255)
var_dump($c); //Output : int(255)
?>
</code>```

My question is why the data contained in integer data types of octal, hexadecimal and binary are getting converted into decimal and then displayed in browser along with the new datatype integer?

Why it's not showing the original values of variables and also not showing their original data type?

Why there is a conversion step and who does this for what reason?

If we take other data types life boolean, float, string nothing like this happen. Everything works as expected then why this weird thing is happening with these integer data types?

答: There's only one kind of (integer) number, and the format of the number is completely unimportant. The values 052, 42 and 0x2A all represent exactly the same value. PHP doesn't remember how a number was created; it doesn't store that information because it's useless information that would only waste space being stored. Binary, octal and hexadecimal notations are mere convenience affordances to allow you to express numbers in the most suited notation for the context; it's all being parsed to an int of the same value and then output in decimal notation by default.

Body:
I'm using PHP 7.1.11

I've following PHP code :

<?php
$a = 0123; // an octal number (equivalent to 83 decimal)
$b = 0x1A; // a hexadecimal number (equivalent to 26 decimal)
$c = 0b11111111; // a binary number (equivalent to 255 decimal)

var_dump($a); //Output : int(83) int(26) int(255)
var_dump($b); //Output : int(26) int(255)
var_dump($c); //Output : int(255)
?>

My question is why the data contained in integer data types of octal, hexadecimal and binary are getting converted into decimal and then displayed in browser along with the new datatype integer?

Why it's not showing the original values of variables and also not showing their original data type?

Why there is a conversion step and who does this for what reason?

If we take other data types life boolean, float, string nothing like this happen. Everything works as expected then why this weird thing is happening with these integer data types?


问:
"Symbol not found" error, (possibly) due to recent upgrade to R2017b?
I'm getting an error when I try to use imerode() from the command line, e.g.

```<code>test=magic([100 100])>200;
imclose(test,strel('disk',10,0));
</code>```

I get this error:

Error using images.internal.morphmex Invalid MEX-file
  '/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64':
  dlopen(/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64,
  6): Symbol not found: _OSAtomicDecrement32Barrier   Referenced from:
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib

  Expected in: /usr/lib/libSystem.B.dylib  in
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib.

Error in images.internal.morphop (line 103)
          B = images.internal.morphmex(mex_method, B, nhood, height, unpacked_M);

Error in imdilate (line 135) B =
  images.internal.morphop(A,se,'dilate',mfilename,varargin{:});

Error in imclose (line 82)
      outputImage = imerode(imdilate(inputImage,se,packopt,M),se,packopt,M);

I'm on OS X 10.9.5, with MATLAB R2017b.
I've checked that morphmex.mexmaci64 is there in the given path (above).
Not sure where /./ refers to, but libcudart.8.0.dylib is in maci64 folder.
Not sure where /usr/lib/... is.

EDIT

I have uninstalled R2017b and installed R2017a (why not, just in case...) and when trying to run the same code, I now get this error (which seems worse...)

       Segmentation violation detected at Mon Nov 13 13:44:29 2017

Configuration:   Crash Decoding      : Disabled - No sandbox or build
  area path   Crash Mode          : continue (default)   Current
  Graphics Driver: Unknown hardware    Current Visual      : Quartz

  Default Encoding    : ISO-8859-1   Deployed            : false   Host
  Name           : eduroam-206-52.nomadic.bris.ac.uk   MATLAB
  Architecture : maci64   MATLAB Entitlement ID: 1803495   MATLAB Root

  : /Applications/MATLAB_R2017a.app   MATLAB Version      : 9.2.0.556344
  (R2017a)   OpenGL              : hardware   Operating System    :
  Darwin 13.4.0 Darwin Kernel Version 13.4.0: Mon Jan 11 18:17:34 PST
  2016; root:xnu-2422.115.15~1/RELEASE_X86_64 x86_64   Processor ID

  : x86 Family 6 Model 69 Stepping 1, GenuineIntel   Virtual Machine

  : Java 1.7.0_75-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit
  Server VM mixed mode   Window System       : Quartz

Fault Count: 2

Abnormal termination: Trace trap

Can upload error file for rest of message (too long to paste here).

Thanks in advance.

答:
Turns out R2017a, b not compatible with OS Mavericks.
Rolled back to R2016a.</p>

Body:
I'm getting an error when I try to use imerode() from the command line, e.g.

test=magic([100 100])>200;
imclose(test,strel('disk',10,0));

I get this error:

Error using images.internal.morphmex Invalid MEX-file
  '/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64':
  dlopen(/Applications/MATLAB_R2017b.app/toolbox/images/images/+images/+internal/morphmex.mexmaci64,
  6): Symbol not found: _OSAtomicDecrement32Barrier   Referenced from:
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib

  Expected in: /usr/lib/libSystem.B.dylib  in
  /Applications/MATLAB_R2017b.app/bin/maci64/./libcudart.8.0.dylib.

Error in images.internal.morphop (line 103)
          B = images.internal.morphmex(mex_method, B, nhood, height, unpacked_M);

Error in imdilate (line 135) B =
  images.internal.morphop(A,se,'dilate',mfilename,varargin{:});

Error in imclose (line 82)
      outputImage = imerode(imdilate(inputImage,se,packopt,M),se,packopt,M);

I'm on OS X 10.9.5, with MATLAB R2017b.
I've checked that morphmex.mexmaci64 is there in the given path (above).
Not sure where /./ refers to, but libcudart.8.0.dylib is in maci64 folder.
Not sure where /usr/lib/... is.

EDIT

I have uninstalled R2017b and installed R2017a (why not, just in case...) and when trying to run the same code, I now get this error (which seems worse...)

       Segmentation violation detected at Mon Nov 13 13:44:29 2017

Configuration:   Crash Decoding      : Disabled - No sandbox or build
  area path   Crash Mode          : continue (default)   Current
  Graphics Driver: Unknown hardware    Current Visual      : Quartz

  Default Encoding    : ISO-8859-1   Deployed            : false   Host
  Name           : eduroam-206-52.nomadic.bris.ac.uk   MATLAB
  Architecture : maci64   MATLAB Entitlement ID: 1803495   MATLAB Root

  : /Applications/MATLAB_R2017a.app   MATLAB Version      : 9.2.0.556344
  (R2017a)   OpenGL              : hardware   Operating System    :
  Darwin 13.4.0 Darwin Kernel Version 13.4.0: Mon Jan 11 18:17:34 PST
  2016; root:xnu-2422.115.15~1/RELEASE_X86_64 x86_64   Processor ID

  : x86 Family 6 Model 69 Stepping 1, GenuineIntel   Virtual Machine

  : Java 1.7.0_75-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit
  Server VM mixed mode   Window System       : Quartz

Fault Count: 2

Abnormal termination: Trace trap

Can upload error file for rest of message (too long to paste here).

Thanks in advance.


问:
Issue in filling color of the polygon drawn on a Map
```<code>private void drawPolygon(List<LocationPointsModel> locationPoints, String fencingColor) {

    mMap.clear();
    PolygonOptions rectOptions = new PolygonOptions();
    rectOptions.strokeColor(Color.parseColor(fencingColor));
    rectOptions.strokeWidth(2);
    String fillcolor = Constants.FILL_COLOR_GEOFENCE + fencingColor.substring(1);//creating opacity less color
    rectOptions.fillColor(Color.parseColor(fillcolor));
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    int size = locationPoints.size();
    for (int i = 0; i < size; i++) {
        LatLng latLng = new LatLng(locationPoints.get(i).getLat(), locationPoints.get(i).getLon());
        latList.add(latLng);
        rectOptions.add(latLng);
    }

    Polygon polygon = mMap.addPolygon(rectOptions);
}
</code>```

In some cases if the polygon lines intersect fill color is not properly rendered.Polygon Fill color Issue. Is that possible to fill polygon with following way. Desired output.

答:
It looks like filling color of self intersecting polygons is not supported by Google Maps Android API.

There is a bug report in the Google issue tracker:

https://issuetracker.google.com/issues/35823225#comment15

The comment #15 posted by Google rep states

We do not support self-intersecting polygons (either the outline or the hole intersecting)

Also the issue with intersecting polygons and filling is mentioned in the documentation. Look at the hollow polygons section

If the hole intersects the outline of the polygon, the polygon will be rendered without any fill.

https://developers.google.com/maps/documentation/android-api/shapes#create_a_hollow_polygon

Looks like polygon intersections and filling are not compatible in Maps Android API.

Body:
private void drawPolygon(List<LocationPointsModel> locationPoints, String fencingColor) {

    mMap.clear();
    PolygonOptions rectOptions = new PolygonOptions();
    rectOptions.strokeColor(Color.parseColor(fencingColor));
    rectOptions.strokeWidth(2);
    String fillcolor = Constants.FILL_COLOR_GEOFENCE + fencingColor.substring(1);//creating opacity less color
    rectOptions.fillColor(Color.parseColor(fillcolor));
    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    int size = locationPoints.size();
    for (int i = 0; i < size; i++) {
        LatLng latLng = new LatLng(locationPoints.get(i).getLat(), locationPoints.get(i).getLon());
        latList.add(latLng);
        rectOptions.add(latLng);
    }

    Polygon polygon = mMap.addPolygon(rectOptions);
}

In some cases if the polygon lines intersect fill color is not properly rendered.Polygon Fill color Issue. Is that possible to fill polygon with following way. Desired output.


问:
Creating index page of posts in Symfony
I am new to Symfony 2.7 and have limited knowledge of php.

I have a system whereby posts are created via the admin resulting in new pages.

I am trying to use these to create an index page showing all the current posts. Eventually this would probably just show title perhaps and i should be able to adjust the view but for now i'm trying to work out how do i get the posts to be got via the controller?

I've looked at the Symfony demo application but can't see how to adjust this to what i have - the annotation routing confuses me a little also as i am using YAML.

Controller

```<code>class PostController extends Controller
{

 /**
 * @param Post $post
 *
 * @return Response
 *
 * @ParamConverter("post", options={"mapping": {"name": "name"}})
 */

    public function viewAction(Post $post)
        {
    return $this->render('MyBundle:Post:view.html.twig', ['post' => $post]);
        }

}
</code>```

Routing

```<code>my_results:
    path: /results/{name}
    methods: [ GET ]
    defaults: { _controller: MyBundle:Post:view }
    requirements:
        name: \w+
</code>```

So far I have add the extra routing...

```<code>my_indexresults:
path: /results
methods: [ GET ]
defaults: { _controller: MyBundle:Post:index }
requirements:
    name: \w+
</code>```

..and i have added to the controller...

```<code>public function indexAction()
{
    $post = $this->getDoctrine()->getRepository('MyBundle:Post')->findAll();

    return $this->render('MyBundle:Post:index.html.twig', array('post' => $post));
}
</code>```

Below is the relevant parts of index.html.twig , containing what I would use a loop of the posts, if i could tie up with the controller

```<code><!DOCTYPE html>
<html lang="en">
<head>
<title="Posts Index">
</head>
<body>
{% block content %}

{% for post in posts %}
        <div id="{{ post }}">{{ post }}</div>
{% endfor %}

{% endblock %}
</body>
</html>
</code>```

..but can't work out how to pull in the posts. If it's possible to tell without looking at the entity, how could I do this please?

答:
I see what your template expects 'posts' variable, but controller sends 'post'. Change array('post' => $post)); to array('posts' => $post));

Also change {{ post }} to {{ post.fieldName }} in template.

Also u don't need any requirements in your 'my_indexresults' route.

Title: Creating index page of posts in Symfony

Body:
I am new to Symfony 2.7 and have limited knowledge of php.

I have a system whereby posts are created via the admin resulting in new pages.

I am trying to use these to create an index page showing all the current posts. Eventually this would probably just show title perhaps and i should be able to adjust the view but for now i'm trying to work out how do i get the posts to be got via the controller?

I've looked at the Symfony demo application but can't see how to adjust this to what i have - the annotation routing confuses me a little also as i am using YAML.

Controller

class PostController extends Controller
{

 /**
 * @param Post $post
 *
 * @return Response
 *
 * @ParamConverter("post", options={"mapping": {"name": "name"}})
 */

    public function viewAction(Post $post)
        {
    return $this->render('MyBundle:Post:view.html.twig', ['post' => $post]);
        }

}

Routing

my_results:
    path: /results/{name}
    methods: [ GET ]
    defaults: { _controller: MyBundle:Post:view }
    requirements:
        name: \w+

So far I have add the extra routing...

my_indexresults:
path: /results
methods: [ GET ]
defaults: { _controller: MyBundle:Post:index }
requirements:
    name: \w+

..and i have added to the controller...

public function indexAction()
{
    $post = $this->getDoctrine()->getRepository('MyBundle:Post')->findAll();

    return $this->render('MyBundle:Post:index.html.twig', array('post' => $post));
}

Below is the relevant parts of index.html.twig , containing what I would use a loop of the posts, if i could tie up with the controller

<!DOCTYPE html>

<title="Posts Index">

{% block content %}

{% for post in posts %}

{{ post }}

{% endfor %}

{% endblock %}

..but can't work out how to pull in the posts. If it's possible to tell without looking at the entity, how could I do this please?


问:
Model Binding in ASHX?
I have a .NET 3.5 webform project and want to add a generic handler (ashx) to accept ajax calls. My current implementation has me parsing out the Request object (ex. Request["param"]) in the handler in order to obtain all querystring values. Is there a better way to do this? I know MVC projects have model binding capabilities and would love to utilze that same feature in a generic handler. Is this possible?

Overall, what is the best way to grab querystring parameters in a generic handler?

答:
Just simply by using Request.QueryString.Get(); you could build the MVC model binding process for web forms, but that isn't available out of the box.  Plus, how many handlers do you write?  If only a few, a complex process like that may be overhead.

HTH.

Title: Model Binding in ASHX?


答:
Just get your  tag outside of while loop</p>

```<code><tr>
 while($prd = mysqli_fetch_array($pr))
   {

<td> Your Values </td>

}
</tr>
</code>```

Title: pagination in html page

Body:
Just get your  tag outside of while loop

<tr>
 while($prd = mysqli_fetch_array($pr))
   {

<td> Your Values </td>

}
</tr>


问:
Simple Input Restriction Issues
I have a program, first I need to enter the command - help, and why choose from 2 commands - exp or sum and so on. At first, help should always be entered, but I can not enter help, but I can enter exp or sum immediately, how do I make a notification so that if I enter exp or sum, the console wrote to me: enter the help command first

My code:

```<code>import utils.Calculator;

import java.util.Scanner;

public class Never {

    public static final String STOP = "-stop";

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter command: for the initial operation of the program, type "help");
        String word = scan.nextLine();

        while (!word.equals(STOP)) {
            switch (word) {

                case "help": {
                    System.out.println("exp - outputs the root of a number");
                    System.out.println("sum - displays the sum of two numbers");
                }
                break;
                case "exp": {
                    long result = Calculator.exp(scan.nextInt());
                    System.out.println(result);
                }
                break;
                case "sum": {
                    System.out.println("Enter first number");
                    int first = scan.nextInt();
                    System.out.println("Enter second number");
                    int second = scan.nextInt();

                    long result = Calculator.sum(first, second);

                    System.out.println(result);

                }
                break;
                default: {
                    System.out.println("Now exit programm");
                }

            }

            word = scan.nextLine();

        }

    }

}
</code>```

答:
Place a do-while loop before your first while loop:

```<code>Scanner scan = new Scanner(System.in);
String word;
do {
    System.out.println("Enter command: for the initial operation of the program, type "help");
    word = scan.nextLine();
} while(!word.equals("help"));

// the rest of the code
</code>```

That way the program checks so many times until the user types in help

Title: Simple Input Restriction Issues

Body:
I have a program, first I need to enter the command - help, and why choose from 2 commands - exp or sum and so on. At first, help should always be entered, but I can not enter help, but I can enter exp or sum immediately, how do I make a notification so that if I enter exp or sum, the console wrote to me: enter the help command first

My code:

import utils.Calculator;

import java.util.Scanner;

public class Never {

    public static final String STOP = "-stop";

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter command: for the initial operation of the program, type "help");
        String word = scan.nextLine();

        while (!word.equals(STOP)) {
            switch (word) {

                case "help": {
                    System.out.println("exp - outputs the root of a number");
                    System.out.println("sum - displays the sum of two numbers");
                }
                break;
                case "exp": {
                    long result = Calculator.exp(scan.nextInt());
                    System.out.println(result);
                }
                break;
                case "sum": {
                    System.out.println("Enter first number");
                    int first = scan.nextInt();
                    System.out.println("Enter second number");
                    int second = scan.nextInt();

                    long result = Calculator.sum(first, second);

                    System.out.println(result);

                }
                break;
                default: {
                    System.out.println("Now exit programm");
                }

            }

            word = scan.nextLine();

        }

    }

}

Body:
Place a do-while loop before your first while loop:

Scanner scan = new Scanner(System.in);
String word;
do {
    System.out.println("Enter command: for the initial operation of the program, type "help");
    word = scan.nextLine();
} while(!word.equals("help"));

// the rest of the code

That way the program checks so many times until the user types in help


问:
Expand environment variable for My Documents
I know I can read environment variables like this:

```<code>Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

However, it would be really helpful to me if I could do something like this:

```<code>Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");
</code>```

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

```<code>Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");
</code>```

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

答:
What exactly are you trying to do? Is there any reason why you can't just use Path.Combine?

```<code>string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string foo = Path.Combine(docs, "Foo");
</code>```

Body:
I know I can read environment variables like this:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

However, it would be really helpful to me if I could do something like this:

Environment.ExpandEnvironmentVariables(@"%MyDocuments%\Foo");

Is there an environement variable that equals SpecialFolder.MyDocuments?

I also tried to do something like this, but this doesn't lead to the expected result:

Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\My Documents\Foo");

This way I ended up with something like @"C:\Users\<MyUser>\My Documents\Foo" but I what I need is @"\\someservername\users$\<MyUser>\My Documents\Foo".

EDIT: My Goal is NOT to hardcode either environment variable nor the part after that.

Any other suggestions?

Body:
What exactly are you trying to do? Is there any reason why you can't just use Path.Combine?

string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string foo = Path.Combine(docs, "Foo");