问:
CSS - making div's background image look the same than the background image of HTML page
I have a HTML page with a background image.

```<code>body {
  background-color: #FFFFFF;
  background-image: url(bg_width900px_height675px.jpg);
  background-attachment: fixed;
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</code>```

This works fine when the background image is a beautiful landscape. The left side is darker and the right side a little bit lighter.

I also have a div which is wider than my screen. I would like to use the same background image than the HTML page is using. In fact, background-attachment: fixed; should be used and the background image should look 100% same than the background of my HTML page. In other words, the size has to be same.

Please note that I'm not looking for debugging help. I just do not know if my vision is possible to achieve and create.

Update

Thanks to blizzyb, it seems to me that this is possible. Here is my best code so far:

```

答:
you can define a class that you assign to the div tag.

```<code>.mydiv{
    background-image: url(bg_width900px_height675px.jpg);
}
</code>```

if you have bootstrap you can also add the class .img-responsive which would avoid the image being distorted. Your div tag should look something like this

```<code><div class="img-responsive mydiv">...</div>
</code>```

Body:
I have a HTML page with a background image.

body {
  background-color: #FFFFFF;
  background-image: url(bg_width900px_height675px.jpg);
  background-attachment: fixed;
  background-position: center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

This works fine when the background image is a beautiful landscape. The left side is darker and the right side a little bit lighter.

I also have a div which is wider than my screen. I would like to use the same background image than the HTML page is using. In fact, background-attachment: fixed; should be used and the background image should look 100% same than the background of my HTML page. In other words, the size has to be same.

Please note that I'm not looking for debugging help. I just do not know if my vision is possible to achieve and create.

Update

Thanks to blizzyb, it seems to me that this is possible. Here is my best code so far:

Body:
you can define a class that you assign to the div tag.

.mydiv{
    background-image: url(bg_width900px_height675px.jpg);
}

if you have bootstrap you can also add the class .img-responsive which would avoid the image being distorted. Your div tag should look something like this

<div class="img-responsive mydiv">...</div>


来源: stackexchange

问:
PHP GET parameters - Make parameters with and without space mean same
First of all, sorry if my title isn't so precise.

Is it possible, if yes, how, to make parameters "city=Los%20Angeles" and "city=LosAngeles" same? I have ads website with search by city, and problem is that some ads's city variables contain space (%20), and some don't. That is a problem when searching ads because searching Los Angeles won't show ads with city LosAngeles.

So 1st url needs to show ads from 1st and 2nd url
1st url https://www.mywebsite.com/city-Los%20Angeles/listings.html
2nd url https://www.mywebsite.com/city-LosAngeles/listings.html

If helps, I use smarty template engine.

答:
OK, I did it as Dom C said and It's working, but I somehow forgot to post it.

Thank you all for your answers.

ContentLicense: CC BY-SA 3.0


问:
TypeError when calling document.getElementById
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

```<code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>
  <script>
    document.getElementById("kaptree").innerHTML="TEST";
  </script>
  <body>
     <div id="kaptree"></div>
  </body>
</html>
</code>```

Can anyone help me to open my eyes?

答:
If you move the body section with the DIV setup to the top it works.

It runs sequentially so it can't assign the inner.html before the DIV is defined

Body:
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

Can anyone help me to open my eyes?


问:
Passing data through shaders
How it possible to pass data through shaders, when using vertex, tess. control, tess. evaluation, geometry and fragment shaders. I've tried using interface block this way.

```<code>//vertex shaders
out VS_OUT { ... } vs_out;
</code>```

Than I wrote this code in tessellation control shader:

```<code>in VS_OUT { ... } tc_in;
out TC_OUT { ... } tc_out;
</code>```

So, tesselation control shader called once for every vertex. Does it mean that tc_in must be not array but single variable. I'm not really sure about that because of sneaky gl_InvocationID.

Then things become tough. Tessellation evaluation shader. Something tells me that evaluation shader should take interface block as array.

```<code>in TC_OUT { ... } te_in[];
out TE_OUT { ...  } te_out[];
</code>```

Moving to geometry shader. Geometry shader takes multiple vertices, so, definitely array interface block.

```<code>in TE_OUT  { ... } gs_in[];
out vec3 random_variable;
...
random_variable = gs_in[whatever_index];
</code>```

Seems legit for me, but data didn't come to fragment shader.

I would appreciate any advice.

答:
Tessellation control shaders take the vertices of a patch as modify them in some way, so their input and output is

```<code>in VS_OUT { ... } tc_in[];
out TC_OUT { ... } tc_out[];
</code>```

The control shader gets called for every patch vertex (see which one by using gl_InvocationID), so you usually don't need any loops to implement it.

Tessellation evaluation shaders take these modified vertices and output a single vertex per invocation, thus we have

```<code>in TC_OUT { ... } te_in[];
out TE_OUT { ...  } te_out;
</code>```

Geometry shaders take multiple vertices and may output a different number of vertices, but these are constructed explicitly using EmitVertex and EmitPrimitive, so there is only one output element that has to be filled before each call of EmitVertex:

```<code>in TE_OUT { ... } gs_in[];
out GS_OUT { ... } gs_out;
</code>```

But don't forget to set glPosition in your geometry shader, otherwise OpenGL won't know where to place your vertices.

The interpolated values of gs_out are then passed to the fragment shader.

Title: Passing data through shaders

Body:
How it possible to pass data through shaders, when using vertex, tess. control, tess. evaluation, geometry and fragment shaders. I've tried using interface block this way.

//vertex shaders
out VS_OUT { ... } vs_out;

Than I wrote this code in tessellation control shader:

in VS_OUT { ... } tc_in;
out TC_OUT { ... } tc_out;

So, tesselation control shader called once for every vertex. Does it mean that tc_in must be not array but single variable. I'm not really sure about that because of sneaky gl_InvocationID.

Then things become tough. Tessellation evaluation shader. Something tells me that evaluation shader should take interface block as array.

in TC_OUT { ... } te_in[];
out TE_OUT { ...  } te_out[];

Moving to geometry shader. Geometry shader takes multiple vertices, so, definitely array interface block.

in TE_OUT  { ... } gs_in[];
out vec3 random_variable;
...
random_variable = gs_in[whatever_index];

Seems legit for me, but data didn't come to fragment shader.

I would appreciate any advice.

Body:
Tessellation control shaders take the vertices of a patch as modify them in some way, so their input and output is

in VS_OUT { ... } tc_in[];
out TC_OUT { ... } tc_out[];

The control shader gets called for every patch vertex (see which one by using gl_InvocationID), so you usually don't need any loops to implement it.

Tessellation evaluation shaders take these modified vertices and output a single vertex per invocation, thus we have

in TC_OUT { ... } te_in[];
out TE_OUT { ...  } te_out;

Geometry shaders take multiple vertices and may output a different number of vertices, but these are constructed explicitly using EmitVertex and EmitPrimitive, so there is only one output element that has to be filled before each call of EmitVertex:

in TE_OUT { ... } gs_in[];
out GS_OUT { ... } gs_out;

But don't forget to set glPosition in your geometry shader, otherwise OpenGL won't know where to place your vertices.

The interpolated values of gs_out are then passed to the fragment shader.


问:
Replace every cell in a matrix with the average of adjcent cells
Requirement: Must be done in-place.

For example:

Given matrix

```<code>1, 2, 3
4, 5, 6
7, 8, 9
</code>```

Should replace by the average of its  sum of 3*3 neighbor cells and its own:

```<code>(1+2+4+5)/4,       (2+1+3+4+5+6)/6 ,            (3+2+6+5)/4
(1+2+5+4+7+8)/6,   (1+2+3+4+5+6+7+8+9)/9,       (2+3+5+6+8+9)/6
(4+5+7+8)/4,       (4+5+6+7+8+9)/6,             (5+6+8+9)/4
</code>```

which is:

```<code>All floating number convert to int

3,      3.5(3), 4             3, 3, 4
4.5(4),  5, 5.5(5)  =>        4, 5, 5
6,      6.5(6), 7             6, 6, 7
</code>```

I tried to just iterate over the matrix and update each cell, but I found this will affect the future calculation:

Say I update the original 1 to 3, but when I when I tried to update the original 2, the original 1 becomes 3 now.

Copying the original matrix for calculating average is a workaround but it's a bad idea, Could we achieve that without using that much space?

答:
In most cases, you should just create a copy of the original matrix and use that for calculating the averages. Unless creating a copy of the matrix would use more memory than you have available, the overhead should be negligible.

If you have a really large matrix, you could use a "rolling" backup (in lack of a better term). Let's say you update the cells row-by-row and you are currently in row n. You don't need a backup of row n-2, as those cells are not relevant any more, and neither of row n+1, because those are still the original values. So you can just keep a backup of the previous and the current row. Whenever you advance to the next row, discard the backup of the previous row, move the backup of the current row to previous, and create a backup of the new current row.

Some pseudo-code (not taking any edge-cases into account):

```<code>previous = []  # or whatever works for the first row
for i in len(matrix):
    current = copy(matrix[i])
    for k in len(matrix[i]):
         matrix[i][k] = previous[k-1] + ... + current[k] + ... matrix[i+1][k+1] / 9
    previous = current
</code>```

(You might also keep a backup of the next row, just so you can use only the backup rows for all the values instead of having to differentiate.)

Body:
Requirement: Must be done in-place.

For example:

Given matrix

1, 2, 3
4, 5, 6
7, 8, 9

Should replace by the average of its  sum of 3*3 neighbor cells and its own:

(1+2+4+5)/4,       (2+1+3+4+5+6)/6 ,            (3+2+6+5)/4
(1+2+5+4+7+8)/6,   (1+2+3+4+5+6+7+8+9)/9,       (2+3+5+6+8+9)/6
(4+5+7+8)/4,       (4+5+6+7+8+9)/6,             (5+6+8+9)/4

which is:

All floating number convert to int

3,      3.5(3), 4             3, 3, 4
4.5(4),  5, 5.5(5)  =>        4, 5, 5
6,      6.5(6), 7             6, 6, 7

I tried to just iterate over the matrix and update each cell, but I found this will affect the future calculation:

Say I update the original 1 to 3, but when I when I tried to update the original 2, the original 1 becomes 3 now.

Copying the original matrix for calculating average is a workaround but it's a bad idea, Could we achieve that without using that much space?

Body:
In most cases, you should just create a copy of the original matrix and use that for calculating the averages. Unless creating a copy of the matrix would use more memory than you have available, the overhead should be negligible.

If you have a really large matrix, you could use a "rolling" backup (in lack of a better term). Let's say you update the cells row-by-row and you are currently in row n. You don't need a backup of row n-2, as those cells are not relevant any more, and neither of row n+1, because those are still the original values. So you can just keep a backup of the previous and the current row. Whenever you advance to the next row, discard the backup of the previous row, move the backup of the current row to previous, and create a backup of the new current row.

Some pseudo-code (not taking any edge-cases into account):

previous = []  # or whatever works for the first row
for i in len(matrix):
    current = copy(matrix[i])
    for k in len(matrix[i]):
         matrix[i][k] = previous[k-1] + ... + current[k] + ... matrix[i+1][k+1] / 9
    previous = current

(You might also keep a backup of the next row, just so you can use only the backup rows for all the values instead of having to differentiate.)


问:
oracle sql row count affected by select clause
While working on a oracle SQL , noticed that adding a column to the selected columns increases the total rows in the result. The query is using multiple subqueries declared using WITH. The join in the final query is a left join. Why is the row count getting impacted?</p>

答:
The only way I can think of to increase the number of result rows by adding a column to the SELECT clause is when using SELECT DISTINCT.

SELECT DISTINCT removes duplicates from the results, so

```
col1   col2
a      b
a      b
a      c
a      c
```

becomes

```
col1   col2
a      b
a      c
```

When adding a column

```
col1   col2   col3
a      b      d
a      b      e
a      c      f
a      c      f
```

becomes

```
col1   col2   col3
a      b      d
a      b      e
a      c      f
```

for instance, which is one row more than before.

Body:
The only way I can think of to increase the number of result rows by adding a column to the SELECT clause is when using SELECT DISTINCT.

SELECT DISTINCT removes duplicates from the results, so

col1   col2
a      b
a      b
a      c
a      c

becomes

col1   col2
a      b
a      c

When adding a column

col1   col2   col3
a      b      d
a      b      e
a      c      f
a      c      f

becomes

col1   col2   col3
a      b      d
a      b      e
a      c      f

for instance, which is one row more than before.


问:
Need help translating a NETLOGO 4.1 model to 6.0.1 (Couldn't find corresponding reader for BUTTON)
I am getting an error message when I open a Netlogo 4.1 model in Netlogo 6.0.1.  It seems to be having problems with graphical user interface elements like buttons:

After clicking OK, I get a blank screen:

Here is what the model looks like in Netlogo 4.1 (this shows what should be displayed:

I looked in the transition guide, but didn't find any relevant information.  I am sure that I can put up Netlogo 4.1 and Netlogo 6.0.1 side by side, copy/paste the code (with updates for the new edition) over from Netlogo 4.1 to Netlogo 6.0.1, and then recreate the GUI components in Netlogo 6.0.1.  But, I am wondering if there isn't a more automated way?  The website I got the model from is Netlogo Bag of Tricks.

答: Try opening it in NetLogo 5.3.1 first. If that auto-conversion works, save the model, then open in 6.0.1.</p>


问:
Hosting-specific code in projects: push to Github too?
Imagine this common scenario: i hacked together a cool project i want to share with the world. So: i put it on Github, and fetch it from Github on my own website so people can see a demo. This also makes updating easy: just push from my local box to Github, fetch on my server.

I'd like to track visitors so i add Google Analytics and maybe some other site-specific stuff (like a global header for all pages on my site) to the project. However, everybody who checks out my project from Github gets all that stuff too.

There are a few solutions to prevent that. I could make a specific 'deployment branch' for my website, but that's cumbersome. I could make some kind of switch in my code (if ip === myip showStats()), but that's ugly.

Another option might be to use githooks, but i haven't got any experience with that.

Any other suggestions? Are people even bothered when getting deployment-specific code like that in their checkouts?

答: Create a configuration file for deployment-specific settings. You could for instance have a conf/defaults.conf for any default settings and let users put any local deployment-specific overrides in conf/local.conf.</p>

ContentLicense: CC BY-SA 2.5


问:
ANTLR AST building problem
I am unable to get AST of

```<code>" risk & factors | concise" | item 503
</code>```

using following grammar

```<code>grammar BoolExpRep;

options {
  output=AST;
}

tokens {
  MultiWordNode;
}

start
  :  exp EOF!
  ;

exp
  :  atom (expRest^)?
  |  '('! exp ')'! (expRest^)?
  ;

expRest
  :  OPER exp -> ^(OPER exp)
  |  '~' WORD exp -> ^('~' WORD exp)
  ;

OPER
  :  '&' | '|' | '!' | '&!' | '|!'
  ;

atom
  :  WORD WORD+ -> ^(MultiWordNode WORD+)
  |  WORD
  |  '"' WORD (OPER? WORD)+ '"' -> ^(MultiWordNode '"' (OPER? WORD)+ '"')
  |  '"' WORD '"'
  ;

WORD
  :  ('a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '*' | '{' | '}' | '_' | '?' | ':'
             | ',' | '/' | '\\')+ ('0'..'9')*
  ;
</code>```

I want to make an AST which should show words and operators in order for

```<code>" risk & factors | concise "
</code>```

i.e. my requirement is something like:

```<code>" risk & factors | concise "
</code>```

instead what i get is :

```<code>" & risk & factors & concise "
</code>```

actually, i am referring to AST under MultiwordNode (or generated at 'atom' level)

it should work something like

```<code>        M u l t i W o r d N o d e
        /   / /  |    \  \      \
       /   / /   |     \  \      \
      " risk & factors | concise  "
</code>```

(sorry for my bad drawing :) )

the problem is that if operator occurs without quotes, it should be the kind of head of its siblings (as it refers in AST). but when it occurs in some text with quotes, it should be captures just like other words...

答:
Using this as atom should do the trick:

```<code>atom
  :  WORD WORD+ -> ^(MultiWordNode WORD+)
  |  WORD
  |  '"' WORD (OPER WORD)+ '"' -> ^(MultiWordNode '"' WORD (OPER WORD)+ '"')
  |  '"' WORD '"'
  ;
</code>```

Title: ANTLR AST building problem

Body:
I am unable to get AST of

" risk & factors | concise" | item 503

using following grammar

grammar BoolExpRep;

options {
  output=AST;
}

tokens {
  MultiWordNode;
}

start
  :  exp EOF!
  ;

exp
  :  atom (expRest^)?
  |  '('! exp ')'! (expRest^)?
  ;

expRest
  :  OPER exp -> ^(OPER exp)
  |  '~' WORD exp -> ^('~' WORD exp)
  ;

OPER
  :  '&' | '|' | '!' | '&!' | '|!'
  ;

atom
  :  WORD WORD+ -> ^(MultiWordNode WORD+)
  |  WORD
  |  '"' WORD (OPER? WORD)+ '"' -> ^(MultiWordNode '"' (OPER? WORD)+ '"')
  |  '"' WORD '"'
  ;

WORD
  :  ('a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '*' | '{' | '}' | '_' | '?' | ':'
             | ',' | '/' | '\\')+ ('0'..'9')*
  ;

I want to make an AST which should show words and operators in order for

" risk & factors | concise "

i.e. my requirement is something like:

" risk & factors | concise "

instead what i get is :

" & risk & factors & concise "

actually, i am referring to AST under MultiwordNode (or generated at 'atom' level)

it should work something like

        M u l t i W o r d N o d e
        /   / /  |    \  \      \
       /   / /   |     \  \      \
      " risk & factors | concise  "

(sorry for my bad drawing :) )

the problem is that if operator occurs without quotes, it should be the kind of head of its siblings (as it refers in AST). but when it occurs in some text with quotes, it should be captures just like other words...

Body:
Using this as atom should do the trick:

atom
  :  WORD WORD+ -> ^(MultiWordNode WORD+)
  |  WORD
  |  '"' WORD (OPER WORD)+ '"' -> ^(MultiWordNode '"' WORD (OPER WORD)+ '"')
  |  '"' WORD '"'
  ;


问:
how do I get a function to return the result of an onclick function?
I am trying to understand how to make something like windows.prompt(), as in, you call is as a function and it gives you the result of the button pressed. IE.

```<code>var a = customPrompt('message', ['buttonName1','buttonName2']);
</code>```

I'm looking for a function like:

```<code>function customPrompt(message, buttonNames){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    for(var i=0;i<buttonNames.length;i++){
        $('#CalertButtons').append($("<div id='CalertButton'>").text(buttonNames[i]));
    }
    Here, the function needs to return which button was clicked.
}
</code>```

The main issue I am having is that if I give the buttons an onclick, then it violates scope, and I can't return from my customPrompt function. but I can't exactly make my entire web page wait until a button is pressed.

答:
The function should be like this:

```<code>function customPrompt(message, buttonNames, callback){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    buttonNames.forEach(function(name, index) {
        var $button = $("<div id='CalertButton'>").text(name).appendTo('#CalertButtons'); // create the button
        $button.on('click', function() {                // when the button is clicked
            // probably destroy the dialog box
            callback(name, index);                      // call the callback passing to it the name and the index of the clicked button
        });
    });
}
</code>```

and then you can use it like this:

```<code>customPrompt("Hello, wolrd!", ["aaa", "bbb"], function(name, index) {
     // if the user clicks the aaa button then: name === 'aaa' and index === 0
     // if the user clicks the bbb button then: name === 'bbb' and index === 1
});
</code>```

Body:
I am trying to understand how to make something like windows.prompt(), as in, you call is as a function and it gives you the result of the button pressed. IE.

var a = customPrompt('message', ['buttonName1','buttonName2']);

I'm looking for a function like:

function customPrompt(message, buttonNames){
    $('body').append($("
").append($("
").text(message)));
    $('#Calert').append($("
"));
    for(var i=0;i<buttonNames.length;i++){
        $('#CalertButtons').append($("
").text(buttonNames[i]));
    }
    Here, the function needs to return which button was clicked.
}

The main issue I am having is that if I give the buttons an onclick, then it violates scope, and I can't return from my customPrompt function. but I can't exactly make my entire web page wait until a button is pressed.

Body:
The function should be like this:

function customPrompt(message, buttonNames, callback){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    buttonNames.forEach(function(name, index) {
        var $button = $("<div id='CalertButton'>").text(name).appendTo('#CalertButtons'); // create the button
        $button.on('click', function() {                // when the button is clicked
            // probably destroy the dialog box
            callback(name, index);                      // call the callback passing to it the name and the index of the clicked button
        });
    });
}

and then you can use it like this:

customPrompt("Hello, wolrd!", ["aaa", "bbb"], function(name, index) {
     // if the user clicks the aaa button then: name === 'aaa' and index === 0
     // if the user clicks the bbb button then: name === 'bbb' and index === 1
});


问:
Posted ViewModel is always NULL
My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?

```<code>public class PaintballWorkerCreateViewModel
{
    public PaintballWorker PaintballWorker { get; set; }
    public PaintballWorkerHourlyRate HourlyRate { get; set; }
}
</code>```

Controller

```<code>public ActionResult Create()
{
    PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
    {
        PaintballWorker = new PaintballWorker(),
        HourlyRate = new PaintballWorkerHourlyRate()
        {
            Date = DateTime.Now
        }
    };
    return View(model);
}

[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
    (...)
}
</code>```

View, even added HiddenFor IDs (which aren't created in GET function in controller).

```<code>@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel

@{
    ViewBag.Title = "Utwórz pracownika";
    Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}

<h2>Dodawanie pracownika</h2>

@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PaintballWorker.Active)
        @Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
        @Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.Date)
        @Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)

        <div class="form-group">
            @Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })

(...)

        <div class="form-group">
            @Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
                @Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Dodaj pracownika" class="btn btn-primary" />
            </div>
        </div>
    </div>
}

<div>
@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })
</div>
</code>```

答:
You are not posting the form correctly. Since the attributes are hidden, they are null by default.

After posting your controller does not see anything since the elements are hidden. Therefore it is null.

Use the extension method @Html.TextboxFor instead. Mvc viewengine will render the textbox and then you can put some values and post them.

you also need to make sure that you have mapped the route correctly in your code.

Title: Posted ViewModel is always NULL

Body:
My ViewModel always returns null and don't know why. Can someone look at my code and check what is wrong here and why my filled model with data from view returns to controller as null?

public class PaintballWorkerCreateViewModel
{
    public PaintballWorker PaintballWorker { get; set; }
    public PaintballWorkerHourlyRate HourlyRate { get; set; }
}

Controller

public ActionResult Create()
{
    PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
    {
        PaintballWorker = new PaintballWorker(),
        HourlyRate = new PaintballWorkerHourlyRate()
        {
            Date = DateTime.Now
        }
    };
    return View(model);
}

[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
    (...)
}

View, even added HiddenFor IDs (which aren't created in GET function in controller).

@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel

@{
    ViewBag.Title = "Utwórz pracownika";
    Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}

Dodawanie pracownika

@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PaintballWorker.Active)
        @Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
        @Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.Date)
        @Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
        @Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)

            @Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })

(...)

            @Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
                @Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })

                <input type="submit" value="Dodaj pracownika" class="btn btn-primary" />

}

@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })


问:
Required bean is not found in Controller - Error during dependency injection
I have a very simple spring boot application with a simple hardcoded service but it is not working and it is giving me Field userService in hello.UserController required a bean of type 'services.UserService' that could not be found error. Here are my Application class, controller and service class. The problem is when I try to inject the userService via @Autowired annotation. I think this is already answered somewhere but I cannot find the relevant answer. Please help me or point me to the right answer. Thanks

Controller

```<code>@RestController
@EnableAutoConfiguration
@RequestMapping("/api")

public class UserController {

public static Logger logger = LoggerFactory.getLogger(UserController.class);

@Autowired
UserService userService;

@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
    List<User> users = userService.getAllUsers();
    if(users.isEmpty()) return new ResponseEntity(HttpStatus.NO_CONTENT);

    return new ResponseEntity<List<User>>(users,HttpStatus.OK);
}
</code>```

}

Application

```<code>@SpringBootApplication(scanBasePackageClasses =
{UserController.class})
@ComponentScan
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

    };
 }

}
</code>```

Service class

```<code>@Service

public class UserService {

List<User> users;

public UserService() {
    this.users = new ArrayList<>();
    users.add(new User(2, "Altaire", 23));
    users.add(new User(3, "Ezio", 21));
    users.add(new User(4, "Enzo", 23));
}

public User getUser(int id) {
    for (User user : users) {
        if (user.getId() == id) {
            return user;
        }
    }
    return null;
}

public List<User> getAllUsers() {
    return users;
}

public void addUser(User user) {
    users.add(user);
}

public void deleteUser(int id) {
    for (User user : users) {
        if (user.getId() == id) {
            users.remove(user);
        }
    }
}

public void updateUser(int id, String name, int age) {
    for (User user : users) {
        if (user.getId() == id) {
            user.setName(name);
            user.setAge(age);
        }
    }
  }
}
</code>```

答:
In the application class you have

```<code>@SpringBootApplication(scanBasePackageClasses =
{UserController.class})
</code>```

You should add the service class as well:

```<code>@SpringBootApplication(scanBasePackageClasses =
{UserController.class,UserService.class})
</code>```

Note that you can also use scanBasePackages and not only explicit classed, e.g.

```<code>@SpringBootApplication(scanBasePackage = {"com.x.y"})
</code>```

Body:
I have a very simple spring boot application with a simple hardcoded service but it is not working and it is giving me Field userService in hello.UserController required a bean of type 'services.UserService' that could not be found error. Here are my Application class, controller and service class. The problem is when I try to inject the userService via @Autowired annotation. I think this is already answered somewhere but I cannot find the relevant answer. Please help me or point me to the right answer. Thanks

Controller

@RestController
@EnableAutoConfiguration
@RequestMapping("/api")

public class UserController {

public static Logger logger = LoggerFactory.getLogger(UserController.class);

@Autowired
UserService userService;

@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
    List<User> users = userService.getAllUsers();
    if(users.isEmpty()) return new ResponseEntity(HttpStatus.NO_CONTENT);

    return new ResponseEntity<List<User>>(users,HttpStatus.OK);
}

}

Application

@SpringBootApplication(scanBasePackageClasses =
{UserController.class})
@ComponentScan
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

    };
 }

}

Service class

@Service

public class UserService {

List<User> users;

public UserService() {
    this.users = new ArrayList<>();
    users.add(new User(2, "Altaire", 23));
    users.add(new User(3, "Ezio", 21));
    users.add(new User(4, "Enzo", 23));
}

public User getUser(int id) {
    for (User user : users) {
        if (user.getId() == id) {
            return user;
        }
    }
    return null;
}

public List<User> getAllUsers() {
    return users;
}

public void addUser(User user) {
    users.add(user);
}

public void deleteUser(int id) {
    for (User user : users) {
        if (user.getId() == id) {
            users.remove(user);
        }
    }
}

public void updateUser(int id, String name, int age) {
    for (User user : users) {
        if (user.getId() == id) {
            user.setName(name);
            user.setAge(age);
        }
    }
  }
}

Body:
In the application class you have

@SpringBootApplication(scanBasePackageClasses =
{UserController.class})

You should add the service class as well:

@SpringBootApplication(scanBasePackageClasses =
{UserController.class,UserService.class})

Note that you can also use scanBasePackages and not only explicit classed, e.g.

@SpringBootApplication(scanBasePackage = {"com.x.y"})


问:
Creating a table by web-scraping using a loop
I'm attempting to webscrape tax-rates.org to get the average tax percentage for each county in Texas. I have a list of 255 counties in an csv file which I import as "TX_counties", it's a single column table. I have to create the URL for each county as a string, so I set d1 to the first cell using [i,1], then concat it into a URL string, perform the scrape, then add +1 to [i] which makes it go to the second cell for the next county name, and the process continues.

The problem is I can't figure out how to store the scrape results into a "growing list" which I then want to make into a table and save to .csv file at the end. I'm only able to scrape one county at a time and then it re-writes over itself.

Any thoughts? (fairly new to R and scraping in general)

```<code>i <- 1
for (i in 1:255) {

  d1 <- as.character(TX_counties[i,1])

  uri.seed <- paste(c('http://www.tax-rates.org/texas/',d1,'_county_property_tax'), collapse='')

  html <- htmlTreeParse(file = uri.seed, isURL=TRUE, useInternalNodes = TRUE)

  avg_taxrate <- sapply(getNodeSet(html, "//div[@class='box']/div/div[1]/i[1]"), xmlValue)

  t1 <- data.table(d1,avg_taxrate)

  i <- i+1

}

write.csv(t1,"2015_TX_PropertyTaxes.csv")
</code>```

答:
you should first initialise a list to store the data scraped with each loop. make sure to initialise it before you go into the loop

then, with each iteration, append on to the list before starting the next iteration. see my answer here

Web Scraping in R with loop from data.frame

Body:
I'm attempting to webscrape tax-rates.org to get the average tax percentage for each county in Texas. I have a list of 255 counties in an csv file which I import as "TX_counties", it's a single column table. I have to create the URL for each county as a string, so I set d1 to the first cell using [i,1], then concat it into a URL string, perform the scrape, then add +1 to [i] which makes it go to the second cell for the next county name, and the process continues.

The problem is I can't figure out how to store the scrape results into a "growing list" which I then want to make into a table and save to .csv file at the end. I'm only able to scrape one county at a time and then it re-writes over itself.

Any thoughts? (fairly new to R and scraping in general)

i <- 1
for (i in 1:255) {

  d1 <- as.character(TX_counties[i,1])

  uri.seed <- paste(c('http://www.tax-rates.org/texas/',d1,'_county_property_tax'), collapse='')

  html <- htmlTreeParse(file = uri.seed, isURL=TRUE, useInternalNodes = TRUE)

  avg_taxrate <- sapply(getNodeSet(html, "//div[@class='box']/div/div[1]/i[1]"), xmlValue)

  t1 <- data.table(d1,avg_taxrate)

  i <- i+1

}

write.csv(t1,"2015_TX_PropertyTaxes.csv")


问:
SQL: How to get the element from a delimited string by its index?
I have this function (credit: searchsqlserver):

```<code>CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @List SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
     END
 GO
</code>```

It takes as parameters a string and a delimiter and returns the delimited elements one by one.

```<code>select * from fnSplit('1,22,333', ',')    --   returns 1 22 333
</code>```

I'll confess that I`m new to SQL and I simply can't follow the whole logic behind this function. What I'm trying to achieve is a function that has a third parameter(an index) and returns the element on the position mention by the index. For example:

```<code>select * from fnSplit('1 22 333 444 5555 666', ' ' , 2 ) --  333

select * from fnSplit('1 22 333 444 5555 666', ' ' , 0 ) --  1
</code>```

答:
Using multistatment table-valued UDF with loop to parse string is very inefficient.
 Better approaches: Split strings the right way – or the next best way

Anyway if you want to adapt your function you could set IDENTITY column for table variable and then filter based on third parameter:

```<code>CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
    ,@num INT
 ) RETURNS @List TABLE ( item VARCHAR(8000))
     BEGIN
     DECLARE @ListHelper AS TABLE(id INT IDENTITY(1,1), item VARCHAR(8000));
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @ListHelper SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @ListHelper SELECT @sInputList -- Put the last item in
     INSERT INTO @List
     SELECT item
     FROM @ListHelper
     WHERE id = @num
     RETURN
     END
 GO

select * from fnSplit('1 22 333 444 5555 666', ' ' , 3 );
--333
</code>```

LiveDemo

ContentLicense: CC BY-SA 4.0

Body:
I have this function (credit: searchsqlserver):

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @List SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
     END
 GO

It takes as parameters a string and a delimiter and returns the delimited elements one by one.

select * from fnSplit('1,22,333', ',')    --   returns 1 22 333

I'll confess that I`m new to SQL and I simply can't follow the whole logic behind this function. What I'm trying to achieve is a function that has a third parameter(an index) and returns the element on the position mention by the index. For example:

select * from fnSplit('1 22 333 444 5555 666', ' ' , 2 ) --  333

select * from fnSplit('1 22 333 444 5555 666', ' ' , 0 ) --  1

Body:
Using multistatment table-valued UDF with loop to parse string is very inefficient.
 Better approaches: Split strings the right way – or the next best way

Anyway if you want to adapt your function you could set IDENTITY column for table variable and then filter based on third parameter:

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
    ,@num INT
 ) RETURNS @List TABLE ( item VARCHAR(8000))
     BEGIN
     DECLARE @ListHelper AS TABLE(id INT IDENTITY(1,1), item VARCHAR(8000));
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @ListHelper SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @ListHelper SELECT @sInputList -- Put the last item in
     INSERT INTO @List
     SELECT item
     FROM @ListHelper
     WHERE id = @num
     RETURN
     END
 GO

select * from fnSplit('1 22 333 444 5555 666', ' ' , 3 );
--333

LiveDemo


问:
C++ a class to be used only by another class
I'm building a class (class A) which needs to be able to create a number of instances of another class (class B) in the course of its operation, but class B is only used by a few member functions of class A, and never used outside of the class. How should class B best be defined? Is it practical / reasonable to make it a private member of Class A? Is this the intended purpose of nested classes, or am I parting with the spirit of the construct?

Thanks,
Wyatt

EDIT: On further consideration, I'm not really asking about best practice, as this is for a personal project. I want to include class B as a member of class A from an encapsulation standpoint - it just seems reasonable that a class which is wholly subordinate should in fact be a part of its owning class.

What I'm wondering is whether or not this is a reasonable use-case for nested classes? If not, what is the purpose of nested classes?

答:
You have multiple options :

private inheritance : class A : private B {};

nested class : class A { class B { /* etc */ }; };

Good ol' private member to class B from class A : class A { B b; };

I personally would go with the nested class if you're 100% sure it's not needed outside.


问:
Write vargarg C preprocessor macro which calls some other macro with each of its arguments and more
I need to have meta-information about structures in my code. So, I've code some combination of C structures (to store meta information) and C preprocessor macros to initialize these structures without much of boilerplate code. Now it looks like this (really, I'm storing a lot more information about fields, but this code is enough for my question):

```<code>#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>

struct meta_field {
  const char *name;
  size_t offset;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field fields[];
};

#define META_STRUCT_BEGIN(NAME)               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {
#define META_STRUCT_END()  ,{NULL, 0}}}
#define META_FIELD(NAME)   { .name = "" #NAME, .offset = offsetof(struct CURRENT_META_STRUCT, NAME) }

struct example {
  int i;
  double d;
};

#define CURRENT_META_STRUCT example
META_STRUCT_BEGIN(CURRENT_META_STRUCT)
  META_FIELD(i),
  META_FIELD(d)
META_STRUCT_END();
#undef CURRENT_META_STRUCT
</code>```

It works. But it has a lot of boilerplate still: #define CURRENT_META_STRUCT, usage of CURRENT_META_STRUCT as argument to META_STRUCT_BEGIN(), #undef for CURRENT_META_STRUCT — all of this looks ugly, IMHO.

I know, that it is impossible to define macro by macro (so, META_STRUCT_BEGIN() can not define CURRENT_META_STRUCT). But looking at Branf*ck implementation in C Preprocessor and Boost-PP, I think that it is posisble to implement something which will look like this:

```<code>META_STRUCT(example,
  META_FIELD(i),
  META_FIELD(d)
)
</code>```

But I can not wrap my head around this preprocessor magic.

Could somebody helps me?

I've read https://github.com/orangeduck/CPP_COMPLETE already, but it didn't help.

Also, it was marked as duplicate of this, but problem is I need to add "default" argument to all generated macro "calls".

Here are some sketch, what I want to achieve:

```<code>#define META_FIELD_IMPL(STRUCT, NAME) { .name = "" #NAME, .offset = offsetof(struct STRUCT, NAME) }

#define META_FIELD(NAME)  NAME

#define META_STRUCT(NAME, ... )               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {                               \
      /* Each ARG from __VA_ARGS__ is META_FIELD(x) and                 \
       * I need to call META_FIELD_IMPL(NAME, <Expansion of META_FIELD>) \
       * for each ARG from _VA_ARGS_ here */                            \
      {NULL, 0}                               \
     }}
</code>```

Now in this example there is only one argument for META_FIELD(): NAME, but in real system there are 6 arguments for META_FIELD() and some helper macro which provide "default" values for common cases, so META_FIELD() is necessary and could not be replaced by NAME itself.

And one last complication: such META_STRUCT() could be called as argument to META_FIELD(), because some fields contains pointers to nested meta-structs! Now it is done by declaring named objects for all nested sub-structures, but I want to avoid it too! I understand, that depth of nesting could be limited by some arbitrary constant, it is Ok.

Update: I added this example of what I want to type and what I want to get after preprocessor. I can not figure out how to implement all these macros (marked with /* ??? */). And, yes, I've checked, manually-coded "end result" compiles fine.

```<code>enum meta_type { mt_end, mt_int, mt_string, mt_struct };

struct meta_struct;

struct meta_field {
  const char *name;
  enum meta_type type;
  size_t offset;
  struct meta_struct *child;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field *fields;
};

#define META_STRUCT(NAME, ...)  static struct meta_struct s_meta_##name = { .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}
#define META_FIELD_IMPL0(STRUCT, NAME, TYPE, CHILD) { .name = #NAME, .type = TYPE, .offset = offsetof(STRUCT, NAME), .child = CHILD }
#define META_FIELD_IMPL1(NAME, TYPE, CHILD)  /* ??? */

#define META_FIELD(NAME, TYPE)       META_FIELD_IMPL1(NAME, TYPE, NULL)
#define META_FIELD_SUB(NAME, CHILD)  META_FIELD_IMPL1(NAME, mt_struct, CHILD)
#define META_SUBSTRUCT(NAME, ...)  (struct meta_struct){ .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}

/* Example of "input": */
struct child {
  int i;
};

struct parent {
  int i;
  struct child c;
  const char *s;
};

META_STRUCT(parent,
  META_FIELD(i, mt_int),
  META_FIELD_SUB(c,
    META_SUBSTRUCT(child,
      META_FIELD(i, mt_int)
    )
  ),
  META_FIELD(s, mt_string)
);

/* This should give this */
static struct meta_struct s_meta_parent = {
  .name = "parent",
  .size = sizeof(struct parent),
  .fields = (struct meta_field[]) {
    { .name = "i", .type = mt_int, .offset = offsetof(struct parent, i), .child = NULL },
    { .name = "c", .type = mt_struct, .offset = offsetof(struct parent, c), .child = &(struct meta_struct){
        .name = "child",
        .size = sizeof(struct child),
        .fields = (struct meta_field[]) {
          { .name = "i", .type = mt_int, .offset = offsetof(struct child, i), .child = NULL },
          {NULL, mt_end, 0, NULL}
        }
      }
    },
    { .name = "s", .type = mt_string, .offset = offsetof(struct parent, s), .child = NULL },
    {NULL, mt_end, 0, NULL}
  }
};
</code>```

答:
How about using __VA_ARGS__? Codesnip below accepts maximize 4 fields but you can expands to 5, 6 or more by copy and paste some line of codes (refer here for more detail).

Header file:

```<code>#define META_FIELD1(st,x1) { .name = #x1, .offset = offsetof(struct st, x1) }
#define META_FIELD2(st,x1,x2) META_FIELD1(st,x1), META_FIELD1(st, x2)
#define META_FIELD3(st,x1,x2,x3) META_FIELD1(st,x1), META_FIELD2(st,x2,x3)
#define META_FIELD4(st,x1,x2,x3,x4) META_FIELD1(st,x1), META_FIELD3(st,x2,x3,x4)
#define META_FIELD(st, ...)     META_FIELD4(st, ##__VA_ARGS__) // limit to 4

#define META_STRUCT(st, ...) \
    static struct meta_struct meta_struct_##st = { \
        .name = #st, \
        .size = sizeof(struct st), \
        .fields = { \
            META_FIELD(st, ##__VA_ARGS__) \
        } \
    } \
</code>```

C file:

```<code>struct sample {
    int i;
    double d;
    const char *test;
    float t;
};

META_STRUCT(sample, i, d, test, t);

/*
 *
 */
int main(int argc, char** argv) {
    printf("struct %s { %s, %s, %s, %s } \n",
            meta_struct_sample.name,
            meta_struct_sample.fields[0].name,
            meta_struct_sample.fields[1].name,
            meta_struct_sample.fields[2].name,
            meta_struct_sample.fields[3].name);

    return (EXIT_SUCCESS);
}
</code>```

Output should be: struct sample { i, i, test, t }

Body:
I need to have meta-information about structures in my code. So, I've code some combination of C structures (to store meta information) and C preprocessor macros to initialize these structures without much of boilerplate code. Now it looks like this (really, I'm storing a lot more information about fields, but this code is enough for my question):

#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>

struct meta_field {
  const char *name;
  size_t offset;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field fields[];
};

#define META_STRUCT_BEGIN(NAME)               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {
#define META_STRUCT_END()  ,{NULL, 0}}}
#define META_FIELD(NAME)   { .name = "" #NAME, .offset = offsetof(struct CURRENT_META_STRUCT, NAME) }

struct example {
  int i;
  double d;
};

#define CURRENT_META_STRUCT example
META_STRUCT_BEGIN(CURRENT_META_STRUCT)
  META_FIELD(i),
  META_FIELD(d)
META_STRUCT_END();
#undef CURRENT_META_STRUCT

It works. But it has a lot of boilerplate still: #define CURRENT_META_STRUCT, usage of CURRENT_META_STRUCT as argument to META_STRUCT_BEGIN(), #undef for CURRENT_META_STRUCT — all of this looks ugly, IMHO.

I know, that it is impossible to define macro by macro (so, META_STRUCT_BEGIN() can not define CURRENT_META_STRUCT). But looking at Branf*ck implementation in C Preprocessor and Boost-PP, I think that it is posisble to implement something which will look like this:

META_STRUCT(example,
  META_FIELD(i),
  META_FIELD(d)
)

But I can not wrap my head around this preprocessor magic.

Could somebody helps me?

I've read https://github.com/orangeduck/CPP_COMPLETE already, but it didn't help.

Also, it was marked as duplicate of this, but problem is I need to add "default" argument to all generated macro "calls".

Here are some sketch, what I want to achieve:

#define META_FIELD_IMPL(STRUCT, NAME) { .name = "" #NAME, .offset = offsetof(struct STRUCT, NAME) }

#define META_FIELD(NAME)  NAME

#define META_STRUCT(NAME, ... )               \
  static struct meta_struct s_meta_##NAME = { \
    .name = "" #NAME,                         \
    .size = sizeof(struct NAME),              \
    .fields = {                               \
      /* Each ARG from __VA_ARGS__ is META_FIELD(x) and                 \
       * I need to call META_FIELD_IMPL(NAME, <Expansion of META_FIELD>) \
       * for each ARG from _VA_ARGS_ here */                            \
      {NULL, 0}                               \
     }}

Now in this example there is only one argument for META_FIELD(): NAME, but in real system there are 6 arguments for META_FIELD() and some helper macro which provide "default" values for common cases, so META_FIELD() is necessary and could not be replaced by NAME itself.

And one last complication: such META_STRUCT() could be called as argument to META_FIELD(), because some fields contains pointers to nested meta-structs! Now it is done by declaring named objects for all nested sub-structures, but I want to avoid it too! I understand, that depth of nesting could be limited by some arbitrary constant, it is Ok.

Update: I added this example of what I want to type and what I want to get after preprocessor. I can not figure out how to implement all these macros (marked with /* ??? */). And, yes, I've checked, manually-coded "end result" compiles fine.

enum meta_type { mt_end, mt_int, mt_string, mt_struct };

struct meta_struct;

struct meta_field {
  const char *name;
  enum meta_type type;
  size_t offset;
  struct meta_struct *child;
};

struct meta_struct {
  const char *name;
  size_t size;
  struct meta_field *fields;
};

#define META_STRUCT(NAME, ...)  static struct meta_struct s_meta_##name = { .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}
#define META_FIELD_IMPL0(STRUCT, NAME, TYPE, CHILD) { .name = #NAME, .type = TYPE, .offset = offsetof(STRUCT, NAME), .child = CHILD }
#define META_FIELD_IMPL1(NAME, TYPE, CHILD)  /* ??? */

#define META_FIELD(NAME, TYPE)       META_FIELD_IMPL1(NAME, TYPE, NULL)
#define META_FIELD_SUB(NAME, CHILD)  META_FIELD_IMPL1(NAME, mt_struct, CHILD)
#define META_SUBSTRUCT(NAME, ...)  (struct meta_struct){ .name = #NAME, .size = sizeof(struct NAME), .fileds = (struct meta_field[]){ /* ??? */, {NULL, mt_end, 0, NULL}}}

/* Example of "input": */
struct child {
  int i;
};

struct parent {
  int i;
  struct child c;
  const char *s;
};

META_STRUCT(parent,
  META_FIELD(i, mt_int),
  META_FIELD_SUB(c,
    META_SUBSTRUCT(child,
      META_FIELD(i, mt_int)
    )
  ),
  META_FIELD(s, mt_string)
);

/* This should give this */
static struct meta_struct s_meta_parent = {
  .name = "parent",
  .size = sizeof(struct parent),
  .fields = (struct meta_field[]) {
    { .name = "i", .type = mt_int, .offset = offsetof(struct parent, i), .child = NULL },
    { .name = "c", .type = mt_struct, .offset = offsetof(struct parent, c), .child = &(struct meta_struct){
        .name = "child",
        .size = sizeof(struct child),
        .fields = (struct meta_field[]) {
          { .name = "i", .type = mt_int, .offset = offsetof(struct child, i), .child = NULL },
          {NULL, mt_end, 0, NULL}
        }
      }
    },
    { .name = "s", .type = mt_string, .offset = offsetof(struct parent, s), .child = NULL },
    {NULL, mt_end, 0, NULL}
  }
};

Body:
How about using __VA_ARGS__? Codesnip below accepts maximize 4 fields but you can expands to 5, 6 or more by copy and paste some line of codes (refer here for more detail).

Header file:

#define META_FIELD1(st,x1) { .name = #x1, .offset = offsetof(struct st, x1) }
#define META_FIELD2(st,x1,x2) META_FIELD1(st,x1), META_FIELD1(st, x2)
#define META_FIELD3(st,x1,x2,x3) META_FIELD1(st,x1), META_FIELD2(st,x2,x3)
#define META_FIELD4(st,x1,x2,x3,x4) META_FIELD1(st,x1), META_FIELD3(st,x2,x3,x4)
#define META_FIELD(st, ...)     META_FIELD4(st, ##__VA_ARGS__) // limit to 4

#define META_STRUCT(st, ...) \
    static struct meta_struct meta_struct_##st = { \
        .name = #st, \
        .size = sizeof(struct st), \
        .fields = { \
            META_FIELD(st, ##__VA_ARGS__) \
        } \
    } \

C file:

struct sample {
    int i;
    double d;
    const char *test;
    float t;
};

META_STRUCT(sample, i, d, test, t);

/*
 *
 */
int main(int argc, char** argv) {
    printf("struct %s { %s, %s, %s, %s } \n",
            meta_struct_sample.name,
            meta_struct_sample.fields[0].name,
            meta_struct_sample.fields[1].name,
            meta_struct_sample.fields[2].name,
            meta_struct_sample.fields[3].name);

    return (EXIT_SUCCESS);
}

Output should be: struct sample { i, i, test, t }


问:
How do I create new columns with pandas by combining rows with a particular value?
I have a dataframe with two "categories" of information. One category is repeated across multiple rows, and the other is specific to each row.

It looks something like this:

```<code>City State Industry Pay Hours
15   10    1        20  40
15   10    2        30  25
20   10    1        25  30
20   10    2        50  80
</code>```

I want it to look like:

```<code>City State Industry1Pay Industry1Hours Industry2Pay Industry2Hours
15   10    20           40             30           25
20   10    25           30             50           80
</code>```

This is a simplified version because the full table is much too long to fit up there. There are 8 columns in place of city and state, and 2 additional columns to pay and hours. In addition, each row should contain 4 industries for now (it will be 5 once that data comes in).

I am really struggling with how to do this. The dataset is from a project conducted in Stata, so the columns are mostly floats and need to stay that way for when I send it in.

The closest I think I've gotten is

```<code>wage = wage.pivot_table(index='cityid', columns='Industry').rename_axis(None)
wage.columns = wage.columns.map('_'.join)
</code>```

but I get an error because you can't join a float to a string, and I suspect that this will not work the way I'm hoping it will regardless.

So far I've looked at quite a few stackoverflow questions, as well as:
https://hackernoon.com/reshaping-data-in-python-fa27dda2ff77
http://nikgrozev.com/2015/07/01/reshaping-in-pandas-pivot-pivot-table-stack-and-unstack-explained-with-pictures/
and two others I am unable to link to because I haven't used stackoverflow very much

I'm really struggling with this, and would appreciate any help, even a link to a good tutorial to wrap my head around this. It seems like a really simple task but for the life of me I can't figure out how to do it without just manually moving stuff around in Excel.

I apologize in advance if this is a duplicate - I looked around a lot but I might be missing something obvious because I'm not sure what this is called beyond reshaping.

答:
Here's how to use pivot

```<code>In [38]: df.pivot_table(index=['City', 'State'],
                        columns='Industry',
                        values=['Pay', 'Hours'])
Out[38]:
           Pay     Hours
Industry     1   2     1   2
City State
15   10     20  30    40  25
20   10     25  50    30  80
</code>```

To flatten the pivot and add column names.

```<code>In [94]: dff = df.pivot_table(index=['City', 'State'], columns='Industry',
                              values=['Pay', 'Hours'])

In [95]: cols = ['Industry%s%s' % x for x in zip(dff.columns.get_level_values(1),
                                                 dff.columns.get_level_values(0))]

In [96]: cols
Out[96]: ['Industry1Pay', 'Industry2Pay', 'Industry1Hours', 'Industry2Hours']

In [97]: dff.columns = cols

In [98]: dff.reset_index()
Out[98]:
   City  State  Industry1Pay  Industry2Pay  Industry1Hours  Industry2Hours
0    15     10            20            30              40              25
1    20     10            25            50              30              80
</code>```

Body:
I have a dataframe with two "categories" of information. One category is repeated across multiple rows, and the other is specific to each row.

It looks something like this:

City State Industry Pay Hours
15   10    1        20  40
15   10    2        30  25
20   10    1        25  30
20   10    2        50  80

I want it to look like:

City State Industry1Pay Industry1Hours Industry2Pay Industry2Hours
15   10    20           40             30           25
20   10    25           30             50           80

This is a simplified version because the full table is much too long to fit up there. There are 8 columns in place of city and state, and 2 additional columns to pay and hours. In addition, each row should contain 4 industries for now (it will be 5 once that data comes in).

I am really struggling with how to do this. The dataset is from a project conducted in Stata, so the columns are mostly floats and need to stay that way for when I send it in.

The closest I think I've gotten is

wage = wage.pivot_table(index='cityid', columns='Industry').rename_axis(None)
wage.columns = wage.columns.map('_'.join)

but I get an error because you can't join a float to a string, and I suspect that this will not work the way I'm hoping it will regardless.

So far I've looked at quite a few stackoverflow questions, as well as:
https://hackernoon.com/reshaping-data-in-python-fa27dda2ff77
http://nikgrozev.com/2015/07/01/reshaping-in-pandas-pivot-pivot-table-stack-and-unstack-explained-with-pictures/
and two others I am unable to link to because I haven't used stackoverflow very much

I'm really struggling with this, and would appreciate any help, even a link to a good tutorial to wrap my head around this. It seems like a really simple task but for the life of me I can't figure out how to do it without just manually moving stuff around in Excel.

I apologize in advance if this is a duplicate - I looked around a lot but I might be missing something obvious because I'm not sure what this is called beyond reshaping.

Body:
Here's how to use pivot

In [38]: df.pivot_table(index=['City', 'State'],
                        columns='Industry',
                        values=['Pay', 'Hours'])
Out[38]:
           Pay     Hours
Industry     1   2     1   2
City State
15   10     20  30    40  25
20   10     25  50    30  80

To flatten the pivot and add column names.

In [94]: dff = df.pivot_table(index=['City', 'State'], columns='Industry',
                              values=['Pay', 'Hours'])

In [95]: cols = ['Industry%s%s' % x for x in zip(dff.columns.get_level_values(1),
                                                 dff.columns.get_level_values(0))]

In [96]: cols
Out[96]: ['Industry1Pay', 'Industry2Pay', 'Industry1Hours', 'Industry2Hours']

In [97]: dff.columns = cols

In [98]: dff.reset_index()
Out[98]:
   City  State  Industry1Pay  Industry2Pay  Industry1Hours  Industry2Hours
0    15     10            20            30              40              25
1    20     10            25            50              30              80


问:
Java - Is it possible to call an interface method on a any object?
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.

Now object B, wants to run a method in object X, without knowing what class it is.

Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.

But lets say i have something like this:

```<code>public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}
</code>```

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

答:
Now object B, wants to run a method in object X, without knowing what class it is.

Simply doesn't make sense. In order to invoke a method, you need to know its name and the expected parameters. In that sense, class B needs some knowledge. Thus, you would/could do something like

```<code>if (parentX instanceof ClassA) {
 ( (ClassA) parentX ) . someAMethod(bla, blub);
}
if (parentX instanceof InterfaceC) {
 ( (InterfaceC) parentX ) . someCMethod(bla, blub);
}
</code>```

In that sense: you might use an interface here; but classes work as well. The key thing is: you need a certain piece of information; otherwise you are simply stuck.

The only other alternative is to look into reflection - then you would not need to know the specific type; as you can inspect parentX to find out which methods could be called on that object. But reflection is A) an advanced concept and b) intricate in its usage.

Body:
Lets say I have Object X and Object B. X is an object of a random class, which in turn creates B, and passes itself on to be stored as a variable in object B.

Now object B, wants to run a method in object X, without knowing what class it is.

Is it possible to call a method in any object, and if a method with that name exist, it runs, and if not, it doesn't. I assume some try/catch can work around that part.

But lets say i have something like this:

public class ObjectB {

  public Object parentX;

  public ObjectB(Object x) {
    parentX = x;
  }

  public void anyMethod() {
    x.runMyMethod();
  }
}

In another program I worked with, this was possible with interfaces, and therefore have an idea that it is possible with Java too. However, i cant seem to find the way to set this up. So if the above was the case, how would it be set up, such that ObjectB can call the method on all the classes in my program if that was what i wanted?

Body:
Now object B, wants to run a method in object X, without knowing what class it is.

Simply doesn't make sense. In order to invoke a method, you need to know its name and the expected parameters. In that sense, class B needs some knowledge. Thus, you would/could do something like

if (parentX instanceof ClassA) {
 ( (ClassA) parentX ) . someAMethod(bla, blub);
}
if (parentX instanceof InterfaceC) {
 ( (InterfaceC) parentX ) . someCMethod(bla, blub);
}

In that sense: you might use an interface here; but classes work as well. The key thing is: you need a certain piece of information; otherwise you are simply stuck.

The only other alternative is to look into reflection - then you would not need to know the specific type; as you can inspect parentX to find out which methods could be called on that object. But reflection is A) an advanced concept and b) intricate in its usage.


问:
Native iOS navigation on React-Native View Component button press
I have a simple React-Native componentReactNativeMasterView with a button I want to use for native navigation.

in ReactNativeMasterView:

```<code>var MasterViewController = NativeModules.MasterViewController
</code>```

then the button calls:

```<code>MasterViewController.buttonEvent()
</code>```

I have a basic Obj-C view controller called MasterViewController

In MasterViewController.h:

```<code>@interface MasterViewController : UIViewController <RCTBridgeModule>
</code>```

And in MasterViewController.m
I have a reference to the react native view in my storyboard:

```<code>@property (weak, nonatomic) IBOutlet RNMasterView *reactViewWrapper;
</code>```

and native module and method look like this:

```<code>RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(buttonEvent) {

    RCTLogInfo(@"Button Pressed");

    UIViewController *detail = [[UIViewController alloc]init];

    UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    dispatch_async(dispatch_get_main_queue(), ^{
        [rootViewController showViewController:detail sender:self];
    });

}
</code>```

It almost works too...

Sadly the transition takes me to a black screen, and when i inspect the view hierarchy it looks like UITransitionView is just presenting an empty View I can actually navigate back from this state too.

Anyone have any ideas how to make this work?

UPDATE:

I can make it work with a UIAlertController:

```<code>UIAlertController * alert = [UIAlertController
                             alertControllerWithTitle:name
                             message:param
                             preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
    NSLog(@"Cancel");
}];

[alert addAction:cancelAction];

UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
dispatch_async(dispatch_get_main_queue(), ^{
    [rootViewController presentViewController:alert animated: YES completion: nil];
});
</code>```

that appears to work as intended.

答:
It's black because you're initializing a viewController programmatically and push it UIViewController *detail = [[UIViewController alloc]init];.

Try this:

```<code>UIViewController *detail = [[UIViewController alloc] init];
detail.view.backgroundColor = [UIColor whiteColor];
</code>```

EDIT

You shouldn't really be initializing view controllers like that unless you need to. You should be using storyboards for creating view controllers and laying out the views and then presenting them onto a UINavigationViewController. Here is a good tutorial.

Body:
I have a simple React-Native componentReactNativeMasterView with a button I want to use for native navigation.

in ReactNativeMasterView:

var MasterViewController = NativeModules.MasterViewController

then the button calls:

MasterViewController.buttonEvent()

I have a basic Obj-C view controller called MasterViewController

In MasterViewController.h:

@interface MasterViewController : UIViewController <RCTBridgeModule>

And in MasterViewController.m
I have a reference to the react native view in my storyboard:

@property (weak, nonatomic) IBOutlet RNMasterView *reactViewWrapper;

and native module and method look like this:

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(buttonEvent) {

    RCTLogInfo(@"Button Pressed");

    UIViewController *detail = [[UIViewController alloc]init];

    UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    dispatch_async(dispatch_get_main_queue(), ^{
        [rootViewController showViewController:detail sender:self];
    });

}

It almost works too...

Sadly the transition takes me to a black screen, and when i inspect the view hierarchy it looks like UITransitionView is just presenting an empty View I can actually navigate back from this state too.

Anyone have any ideas how to make this work?

UPDATE:

I can make it work with a UIAlertController:

UIAlertController * alert = [UIAlertController
                             alertControllerWithTitle:name
                             message:param
                             preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
    NSLog(@"Cancel");
}];

[alert addAction:cancelAction];

UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
dispatch_async(dispatch_get_main_queue(), ^{
    [rootViewController presentViewController:alert animated: YES completion: nil];
});

that appears to work as intended.

Body:
It's black because you're initializing a viewController programmatically and push it UIViewController *detail = [[UIViewController alloc]init];.

Try this:

UIViewController *detail = [[UIViewController alloc] init];
detail.view.backgroundColor = [UIColor whiteColor];

EDIT

You shouldn't really be initializing view controllers like that unless you need to. You should be using storyboards for creating view controllers and laying out the views and then presenting them onto a UINavigationViewController. Here is a good tutorial.


问:
Can I use approxPolyDP to improve the people detection?
Can I use approxPolyDP to improve the people detection?

I am trying to detect people using BackgroundSubtractorMOG2. So after I  receive the foreground of the image I obtain all the contours of the image using this function:

```<code>Imgproc.findContours(contourImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
</code>```

I iterate each element of contours variable and if the contour has a specified contour area => it's a person

My question is if I can detect the people shapes better ussing approxPolyDP.

Is it possible? If so can you tell me how?

I already used  CLOSE morphological operation before finding counturs

答:
My question is if I can detect the people shapes better ussing approxPolyDP.

Although "better" is somewhat ambiguous, you could improve your classification by using that method. From the docs we can see:

The functions approxPolyDP approximate a curve or a polygon with another curve/polygon with less vertices so that the distance between them is less or equal to the specified precision.

That "precision" refers to the epsilon parameter, which stands for the "maximum distance between the original curve and its approximation" (also from the docs). It is basically an accuracy parameter obtained from the arc length (the lower the more precise the contour will be).

We can see from this tutorial that a way to achieve this is:

```<code>epsilon = 0.1*cv2.arcLength(contour,True)
approx = cv2.approxPolyDP(contour,epsilon,True)
</code>```

resulting in a better approximation for the contour. In the example in that tutorial they achieve an optimal contour using 1% of arc length, although you should carefully select this percentage for your specific situation.

By using these procedures you will surely obtain higher precision on your contour areas, which will better enable you to correctly classify people from other objects that have similar areas. You will also have to modify your classification criterion (the >= some_area) accordingly to correctly discriminate between people and non-people objects now that you have a more precise area.

Body:
Can I use approxPolyDP to improve the people detection?

I am trying to detect people using BackgroundSubtractorMOG2. So after I  receive the foreground of the image I obtain all the contours of the image using this function:

Imgproc.findContours(contourImg, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);

I iterate each element of contours variable and if the contour has a specified contour area => it's a person

My question is if I can detect the people shapes better ussing approxPolyDP.

Is it possible? If so can you tell me how?

I already used  CLOSE morphological operation before finding counturs

Body:
My question is if I can detect the people shapes better ussing approxPolyDP.

Although "better" is somewhat ambiguous, you could improve your classification by using that method. From the docs we can see:

The functions approxPolyDP approximate a curve or a polygon with another curve/polygon with less vertices so that the distance between them is less or equal to the specified precision.

That "precision" refers to the epsilon parameter, which stands for the "maximum distance between the original curve and its approximation" (also from the docs). It is basically an accuracy parameter obtained from the arc length (the lower the more precise the contour will be).

We can see from this tutorial that a way to achieve this is:

epsilon = 0.1*cv2.arcLength(contour,True)
approx = cv2.approxPolyDP(contour,epsilon,True)

resulting in a better approximation for the contour. In the example in that tutorial they achieve an optimal contour using 1% of arc length, although you should carefully select this percentage for your specific situation.

By using these procedures you will surely obtain higher precision on your contour areas, which will better enable you to correctly classify people from other objects that have similar areas. You will also have to modify your classification criterion (the >= some_area) accordingly to correctly discriminate between people and non-people objects now that you have a more precise area.


问:
Why must I import before I can call a module
I am new to Python and am not sure why you must import before you can call a module or function. Does anyone have an answer to this? And thanks in advance. An example would look like:</p>

```<code>import random
randomNum = random.randint(0,1)
</code>```

答: You must import a module in Python before you use a method from it because otherwise, the interpreter doesn't know what to do when you call a method from said module. Some functions in python, like print() can be called without importing any modules, but for others like random.randint(), the module isn't imported by default, so you need to import it before use.

Body:
I am new to Python and am not sure why you must import before you can call a module or function. Does anyone have an answer to this? And thanks in advance. An example would look like:

import random
randomNum = random.randint(0,1)


问:
Numbering of groups in select (Oracle)
I have a following example - table with name, department and country. I need to create a select statement that lists all records and assigns unique number to each group of department and country (column Group in the example):

```<code>Name   Department   Country   Group
====== ============ ========= =====
James  HR           UK        1
John   HR           UK        1
Alice  Finance      UK        2
Bob    Finance      DE        3
Frank  Finance      DE        3
</code>```

I thought of some select with analytic function but I found only row_number() over (partition by department, country) which numbers records inside the group and not groups themselves. Do you have any idea how to solve this problem? Thank you!

答:
Its a bit clunky, but you could do a a sub query ( or in this case using the with clause ) on the table to get the distinct department per country then get the rownum from that.

```<code>set echo on

DROP TABLE TESTXX

 DROP TABLE TESTXX succeeded.
CREATE
    TABLE TESTXX
    (
      NAME       VARCHAR2 ( 10 )
    , DEPARTMENT VARCHAR2 ( 15 )
    , COUNTRY    VARCHAR2 ( 2 )
    )

CREATE  succeeded.
INSERT INTO TESTXX VALUES
    ( 'James', 'HR', 'UK'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'John', 'HR', 'UK'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Alice', 'FI', 'UK'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Bob', 'FI', 'DE'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Frank', 'FI', 'DE'
    )

1 rows inserted
</code>```

.

```<code>WITH
    X AS
    (SELECT
        XX.*
      , ROWNUM R
      FROM
        (SELECT
            DEPARTMENT
          , COUNTRY
          FROM
            TESTXX
          GROUP BY
            COUNTRY
          , DEPARTMENT
          ORDER BY
            COUNTRY DESC
          , DEPARTMENT DESC
        ) XX
    )
  SELECT
      T.*
    , X.R
    FROM
      TESTXX T
    INNER JOIN X
    ON
      T.DEPARTMENT  = X.DEPARTMENT
      AND T.COUNTRY = X.COUNTRY
    ORDER BY
      T.COUNTRY DESC
    , T.DEPARTMENT DESC

NAME       DEPARTMENT      COUNTRY R
---------- --------------- ------- ----------------------
James      HR              UK      1
John       HR              UK      1
Alice      FI              UK      2
Bob        FI              DE      3
Frank      FI              DE      3

5 rows selected
</code>```

Title: Numbering of groups in select (Oracle)

Body:
I have a following example - table with name, department and country. I need to create a select statement that lists all records and assigns unique number to each group of department and country (column Group in the example):

Name   Department   Country   Group
====== ============ ========= =====
James  HR           UK        1
John   HR           UK        1
Alice  Finance      UK        2
Bob    Finance      DE        3
Frank  Finance      DE        3

I thought of some select with analytic function but I found only row_number() over (partition by department, country) which numbers records inside the group and not groups themselves. Do you have any idea how to solve this problem? Thank you!

Body:
Its a bit clunky, but you could do a a sub query ( or in this case using the with clause ) on the table to get the distinct department per country then get the rownum from that.

set echo on

DROP TABLE TESTXX

 DROP TABLE TESTXX succeeded.
CREATE
    TABLE TESTXX
    (
      NAME       VARCHAR2 ( 10 )
    , DEPARTMENT VARCHAR2 ( 15 )
    , COUNTRY    VARCHAR2 ( 2 )
    )

CREATE  succeeded.
INSERT INTO TESTXX VALUES
    ( 'James', 'HR', 'UK'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'John', 'HR', 'UK'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Alice', 'FI', 'UK'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Bob', 'FI', 'DE'
    )

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Frank', 'FI', 'DE'
    )

1 rows inserted

.

WITH
    X AS
    (SELECT
        XX.*
      , ROWNUM R
      FROM
        (SELECT
            DEPARTMENT
          , COUNTRY
          FROM
            TESTXX
          GROUP BY
            COUNTRY
          , DEPARTMENT
          ORDER BY
            COUNTRY DESC
          , DEPARTMENT DESC
        ) XX
    )
  SELECT
      T.*
    , X.R
    FROM
      TESTXX T
    INNER JOIN X
    ON
      T.DEPARTMENT  = X.DEPARTMENT
      AND T.COUNTRY = X.COUNTRY
    ORDER BY
      T.COUNTRY DESC
    , T.DEPARTMENT DESC

NAME       DEPARTMENT      COUNTRY R
---------- --------------- ------- ----------------------
James      HR              UK      1
John       HR              UK      1
Alice      FI              UK      2
Bob        FI              DE      3
Frank      FI              DE      3

5 rows selected


问:
How to shut down the host from within the container?
I'm writing a UPS monitoring console application that will automatically shut down the server when the UPS battery reaches a predefined level of charge during a power outage.

I'd like to run this within a container if possible, as NUT (Network UPS Tools) is notoriously difficult to get working on a Windows system. I've configured it once, on bare metal, and I wish not to have to endure that pain a second time, or worse, a third. (But that's another discussion for another day.)

Back to today: how may I send a system shutdown command to the container's host? I've tried simply shutdown /s /t 0, but that shuts down the container. I need to reach the host.

--NOTE TO CLOSE VOTERS--

This question is not off-topic. Note this Q&A, for one example, which currently bears upvotes numbering well over 2,000. There isn't a single programming concept mentioned in the question.

Docker is a tool used by developers. So its subject matter is very relevant on this forum. Run a quick query on the docker tag and you'll see what I mean.

答:
psshutdown \\host -u ... -p ... should do the trick, assuming you are able / willing to store credentials with sufficient permissions in the container.

See https://technet.microsoft.com/en-us/sysinternals/psshutdown.aspx for more details and a download link.

Edit: I leave this here for documenting an approach that doesn't work because of changes in the way Windows handles security. Follow InteXXs link provided below, it clearly describes what would be necessary to get psshutdown working again and which security risks this brings.


问:
Unet. Multiplayer Vehicles
I am currently developing multiplayer fps shooter, and i am stuck on vehicles.

i tried these "ClientRpc" stuff, "Command" and etc. So Player has Controll script, and this script has function OnControllerColliderHit, so if this happens i call void Disable();

in this method, i disable all colliders and some components i don't need like: shooting, moving, camera etc...

basically all i need is: Disable some player components when he gets
  in car. script works perfectly in singleplayer, but in multiplayer it
  looks really weird.

I have also asked this on Unity answers, but didn't get any: http://answers.unity3d.com/questions/1235436/ (scripts are there)

ps(if you'll need some more info or scripts for me to post, just comment. )

答:
I think the problem is that you are only enabling/disabling components in the server. Commands are called on the server only, so you might want to use RPC to do the same in the clients.</p>

```<code> void Update()
 {
     //if there is driver in car then we can controll it. (it's a paradox for me, if there is driver and i am passanger i also can controll it lol.)
     if(hasDriver)
     {
         GetComponent<carController>().enabled = true;
     }
     else
     {
         GetComponent<carController>().enabled = false;
     }
 }

 //command function for sitting. in car.
 [Command]
 public void CmdSit(string _player)
 {
     //i increase how many people are in car
     sitPlayers++;

     cam.enabled = true;
     //find player who sat there.
     GameObject player = GameObject.Find(_player);

     //i think you will get it >>
     if (hasDriver)
     {
         player.transform.parent = Sitter.transform;
         player.transform.position = Sitter.transform.position;
         cam.GetComponent<AudioListener>().enabled = true;

     }
     else
     {
         player.transform.parent = Driver.transform;
         hasDriver = true;
         cam.GetComponent<AudioListener>().enabled = true;
         player.transform.position = Driver.transform.position;
     }

     RpcSit(_player, hasDriver);

 }

[ClientRpc]
public void RpcSit(string _player, bool _driver)
{
     cam.enabled = true;
     //find player who sat there.
     GameObject player = GameObject.Find(_player);

     //i think you will get it >>
     if (_driver)
     {
         player.transform.parent = Sitter.transform;
         player.transform.position = Sitter.transform.position;
         cam.GetComponent<AudioListener>().enabled = true;
     }
     else
     {
         player.transform.parent = Driver.transform;
         cam.GetComponent<AudioListener>().enabled = true;
         player.transform.position = Driver.transform.position;
     }
}
</code>```

Title: Unet. Multiplayer Vehicles

Body:
I think the problem is that you are only enabling/disabling components in the server. Commands are called on the server only, so you might want to use RPC to do the same in the clients.

 void Update()
 {
     //if there is driver in car then we can controll it. (it's a paradox for me, if there is driver and i am passanger i also can controll it lol.)
     if(hasDriver)
     {
         GetComponent<carController>().enabled = true;
     }
     else
     {
         GetComponent<carController>().enabled = false;
     }
 }

 //command function for sitting. in car.
 [Command]
 public void CmdSit(string _player)
 {
     //i increase how many people are in car
     sitPlayers++;

     cam.enabled = true;
     //find player who sat there.
     GameObject player = GameObject.Find(_player);

     //i think you will get it >>
     if (hasDriver)
     {
         player.transform.parent = Sitter.transform;
         player.transform.position = Sitter.transform.position;
         cam.GetComponent<AudioListener>().enabled = true;

     }
     else
     {
         player.transform.parent = Driver.transform;
         hasDriver = true;
         cam.GetComponent<AudioListener>().enabled = true;
         player.transform.position = Driver.transform.position;
     }

     RpcSit(_player, hasDriver);

 }

[ClientRpc]
public void RpcSit(string _player, bool _driver)
{
     cam.enabled = true;
     //find player who sat there.
     GameObject player = GameObject.Find(_player);

     //i think you will get it >>
     if (_driver)
     {
         player.transform.parent = Sitter.transform;
         player.transform.position = Sitter.transform.position;
         cam.GetComponent<AudioListener>().enabled = true;
     }
     else
     {
         player.transform.parent = Driver.transform;
         cam.GetComponent<AudioListener>().enabled = true;
         player.transform.position = Driver.transform.position;
     }
}


问:
TypeError when calling document.getElementById
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

```<code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>
  <script>
    document.getElementById("kaptree").innerHTML="TEST";
  </script>
  <body>
     <div id="kaptree"></div>
  </body>
</html>
</code>```

Can anyone help me to open my eyes?

答:
Because your JS code is called before HTML.

Solution 1: Add JS right before  tag

Example:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

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

<p><strong>Solution 2:</strong> Execute JS code inside <code>window.load</code> function</p>

<p><strong>Example:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

    <script>
    window.onload = (function(){
      document.getElementById("kaptree").innerHTML+="TEST";
    });

  </script>

  </head>

  <body>
     <div id="kaptree"></div>
  </body>

</html></code>```

Body:
the following code should display the word Test...but instead the message TypeError: document.getElementById(...) is displayed.
I can't figure out why:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

Can anyone help me to open my eyes?

Body:
Because your JS code is called before HTML.

Solution 1: Add JS right before </body> tag

Example:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>
  </head>

  <body>
     <div id="kaptree"></div>
  </body>
    <script>

    document.getElementById("kaptree").innerHTML+="TEST";
  </script>
</html>

Solution 2: Execute JS code inside window.load function

Example:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Testtree</title>

    <script>
    window.onload = (function(){
      document.getElementById("kaptree").innerHTML+="TEST";
    });

  </script>

  </head>

  <body>
     <div id="kaptree"></div>
  </body>

</html>


问:
find() not working in C++ Header
I have a vector in my Header file, and I'm trying to do a bool function that returns the find() function, but it is giving me an error.

```<code>vector<string> reservedWord{
....
....
....
};
</code>```

bool function

```<code>bool isReservedWord(string str)
{
   return find(reservedWord.begin(), reservedWord.end(), str) != reservedWord.end();
}
</code>```

I tried it both without the last != reservedWord.end) and also without.

The errors given are these:

```<code>||=== Build: Release in compilers (compiler: GNU GCC Compiler) ===|
E:\University\compilers\reservedWords.h||In function 'bool isReservedWord(std::string)':|
E:\University\compilers\reservedWords.h|40|error: no matching function for call to 'find(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::string&)'|
E:\University\compilers\reservedWords.h|40|note: candidate is:|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\streambuf_iterator.h|371|note: template<class _CharT2> typename __gnu_cxx::__enable_if<std::__is_char<_CharT2>::__value, std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> > >::__type std::find(std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >, std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >, const _CharT2&)|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\streambuf_iterator.h|371|note:   template argument deduction/substitution failed:|
E:\University\compilers\reservedWords.h|40|note:   '__gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >' is not derived from 'std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >'|
E:\University\compilers\reservedWords.h|41|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
</code>```

答:
I got the same compilation error when <string> was included but <algorithm> was not. In that case the compiler only sees the declaration of

```<code>std::find(std::istreambuf_iterator<_CharT>, std::istreambuf_iterator<_CharT>, const _CharT2&)
</code>```

and quits with this error.

To fix this, add

```<code>#include <algorithm>
</code>```

Title: find() not working in C++ Header

Body:
I have a vector in my Header file, and I'm trying to do a bool function that returns the find() function, but it is giving me an error.

vector<string> reservedWord{
....
....
....
};

bool function

bool isReservedWord(string str)
{
   return find(reservedWord.begin(), reservedWord.end(), str) != reservedWord.end();
}

I tried it both without the last != reservedWord.end) and also without.

The errors given are these:

||=== Build: Release in compilers (compiler: GNU GCC Compiler) ===|
E:\University\compilers\reservedWords.h||In function 'bool isReservedWord(std::string)':|
E:\University\compilers\reservedWords.h|40|error: no matching function for call to 'find(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::string&)'|
E:\University\compilers\reservedWords.h|40|note: candidate is:|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\streambuf_iterator.h|371|note: template<class _CharT2> typename __gnu_cxx::__enable_if<std::__is_char<_CharT2>::__value, std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> > >::__type std::find(std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >, std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >, const _CharT2&)|
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\streambuf_iterator.h|371|note:   template argument deduction/substitution failed:|
E:\University\compilers\reservedWords.h|40|note:   '__gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >' is not derived from 'std::istreambuf_iterator<_CharT2, std::char_traits<_CharT> >'|
E:\University\compilers\reservedWords.h|41|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

Body:
I got the same compilation error when <string> was included but <algorithm> was not. In that case the compiler only sees the declaration of

std::find(std::istreambuf_iterator<_CharT>, std::istreambuf_iterator<_CharT>, const _CharT2&)

and quits with this error.

To fix this, add

#include <algorithm>