问:
Sudoku Backtracking with Solution Counter
Background

I've implemented a sudoku-solver algorithm (backtracking) that looks like this:

```<code>//Backtracking-Algorithm
public static boolean solver(int[][] board) {
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            if (board[i][j] == 0) {
                for (int n = 1; n < 10; n++) {
                    if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
                        board[i][j] = n;
                        if (!solver(board)) {
                            board[i][j] = 0;
                        } else {
                            return true;
                        }
                    }
                }
                return false;
            }
        }
    }
    return true;
}
</code>```

This solution is working fine (it can solve sudokus).

What I try to achieve

I now want to achieve that the algorithm tells me, whether there is only one solution or more solutions.

What I've tried

I tried to achieve my goal, by changing the return type to an int and count the possible solutions (stops at 2, because if there are two solutions, I can say there are "multiple" solutions). So basically, I just want to know whether there is no, one, or many solution(s):

```<code>// Backtracking-Algorithm
public int solver(int[][] board, int count) { //Starts with count = 0
  if (count < 2) {
    for (int i = 0; i < GRID_SIZE; i++) {
      for (int j = 0; j < GRID_SIZE; j++) {
        /*
         * Only empty fields will be changed
         */
        if (board[i][j] == EMPTY) {
          /*
           * Try all numbers between 1 and 9
           */
          for (int n = 1; n <= GRID_SIZE; n++) {
            /*
             * Is number n safe?
             */
            if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
              board[i][j] = n;
              if (solver(board, count) > count) {
                count++;
              } else {
                board[i][j] = 0;
              }
            }
          }
          return count;
        }
      }
    }
    return count + 1;
  }
  return count;
}
</code>```

The problem is that count always goes to "1" and then the algorithm stops.

Question

What changes in the code are necessary to make it work?

答:
Thanks to this answer by Aziz Sonawalla, I think I figured it out.

The following implementation was able to solve the uniquely solveable sudoku given here. Also the algorithm is now able to solve sudokus with more than one solution (example) and recognize that there is more than one solution. If this is the case, the program will give only one of the possible solutions.

The code looks like this:

```<code>// Backtracking-Algorithm
public int[][] board2 = new int[GRID_SIZE][GRID_SIZE];

public int solver(int[][] board, int count) { // Starts with count = 0

    for (int i = 0; i < GRID_SIZE; i++) { //GRID_SIZE = 9

      for (int j = 0; j < GRID_SIZE; j++) {

        /*
         * Only empty fields will be changed
         */

        if (board[i][j] == EMPTY) { //EMPTY = 0

          /*
           * Try all numbers between 1 and 9
           */

          for (int n = 1; n <= GRID_SIZE && count < 2; n++) {

            /*
             * Is number n safe?
             */
            if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {

              board[i][j] = n;
              int cache = solver(board, count);
              if (cache > count) {
                count = cache;
                for (int k = 0; k < board.length; k++) {
                  for (int l = 0; l < board.length; l++) {
                    if (board[k][l] != EMPTY) {
                      board2[k][l] = board[k][l];
                    }

                  }
                }

                board[i][j] = EMPTY;

              } else {
                board[i][j] = EMPTY;
              }

            }
          }
          return count;
        }
      }
    }
    return count + 1;
}
</code>```

The solution is saved in the array board2 now.

This implementation is working as intended (as far as I know). If you find any mistakes, please leave a comment.

Body:
Background

I've implemented a sudoku-solver algorithm (backtracking) that looks like this:

//Backtracking-Algorithm
public static boolean solver(int[][] board) {
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            if (board[i][j] == 0) {
                for (int n = 1; n < 10; n++) {
                    if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
                        board[i][j] = n;
                        if (!solver(board)) {
                            board[i][j] = 0;
                        } else {
                            return true;
                        }
                    }
                }
                return false;
            }
        }
    }
    return true;
}

This solution is working fine (it can solve sudokus).

What I try to achieve

I now want to achieve that the algorithm tells me, whether there is only one solution or more solutions.

What I've tried

I tried to achieve my goal, by changing the return type to an int and count the possible solutions (stops at 2, because if there are two solutions, I can say there are "multiple" solutions). So basically, I just want to know whether there is no, one, or many solution(s):

// Backtracking-Algorithm
public int solver(int[][] board, int count) { //Starts with count = 0
  if (count < 2) {
    for (int i = 0; i < GRID_SIZE; i++) {
      for (int j = 0; j < GRID_SIZE; j++) {
        /*
         * Only empty fields will be changed
         */
        if (board[i][j] == EMPTY) {
          /*
           * Try all numbers between 1 and 9
           */
          for (int n = 1; n <= GRID_SIZE; n++) {
            /*
             * Is number n safe?
             */
            if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
              board[i][j] = n;
              if (solver(board, count) > count) {
                count++;
              } else {
                board[i][j] = 0;
              }
            }
          }
          return count;
        }
      }
    }
    return count + 1;
  }
  return count;
}

The problem is that count always goes to "1" and then the algorithm stops.

Question

What changes in the code are necessary to make it work?

Body:
Thanks to this answer by Aziz Sonawalla, I think I figured it out.

The following implementation was able to solve the uniquely solveable sudoku given here. Also the algorithm is now able to solve sudokus with more than one solution (example) and recognize that there is more than one solution. If this is the case, the program will give only one of the possible solutions.

The code looks like this:

// Backtracking-Algorithm
public int[][] board2 = new int[GRID_SIZE][GRID_SIZE];

public int solver(int[][] board, int count) { // Starts with count = 0

    for (int i = 0; i < GRID_SIZE; i++) { //GRID_SIZE = 9

      for (int j = 0; j < GRID_SIZE; j++) {

        /*
         * Only empty fields will be changed
         */

        if (board[i][j] == EMPTY) { //EMPTY = 0

          /*
           * Try all numbers between 1 and 9
           */

          for (int n = 1; n <= GRID_SIZE && count < 2; n++) {

            /*
             * Is number n safe?
             */
            if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {

              board[i][j] = n;
              int cache = solver(board, count);
              if (cache > count) {
                count = cache;
                for (int k = 0; k < board.length; k++) {
                  for (int l = 0; l < board.length; l++) {
                    if (board[k][l] != EMPTY) {
                      board2[k][l] = board[k][l];
                    }

                  }
                }

                board[i][j] = EMPTY;

              } else {
                board[i][j] = EMPTY;
              }

            }
          }
          return count;
        }
      }
    }
    return count + 1;
}

The solution is saved in the array board2 now.

This implementation is working as intended (as far as I know). If you find any mistakes, please leave a comment.


来源: stackexchange

问:
How to create a switch/case statement with div id as the case parameter?
I'm trying to create a dropdown list that will show different results based on the dropdown selected. Here's my minimal example for reproduction:

let elem = document.getElementById("dropdown");
elem.onchange = function(){
  if /*this is where I'm stuck. And on the following code. I want to say if the dropdown id = 1,
  then show div option1_result*/
    let hiddenDiv = document.getElementById("option1_result");
    hiddenDiv.style.display = (this.value == "") ? "none":"block";
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
Please select the dropdown:
</p>
<select id = "dropdown">
  <option id = "1" class = "selected"> option 1</option>
  <option id = "2" class = "selected"> option 2</option>
</select>

<div class = "result">
  <div class = "option1_result" style="display:none;">
    <p>
      Option 1 Result!
      <button href="#">
      See More
      </button>
    </p>
  </div>
  <div class = "option2_result" style = "display:none;">
    <p>
      Option 2 result
      <button href="#">
      More about opt 2
      </button>
    </p>
  </div>
</div></code>```

Ideally I'd like to do this where

```<code>case (1):
  hiddenDiv.style.display = "block";
</code>```

But I'm not sure that will work in this instance.

JSFiddle

答:
The id attribute is for uniquely identifying an element in the document. It's not intended to convey the value of a select option. For that, you want to use the value attribute:

```<code><select id="dropdown">
  <option value="1" class="selected">option 1</option>
  <option value="2" class="selected">option 2</option>
</select>
</code>```

Once you have a value for your options, you can check for what the selected value is like this:

```<code>if (elem.value === '1') {
  // ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a dropdown list that will show different results based on the dropdown selected. Here's my minimal example for reproduction:

let elem = document.getElementById("dropdown");
elem.onchange = function(){
  if /*this is where I'm stuck. And on the following code. I want to say if the dropdown id = 1,
  then show div option1_result*/
    let hiddenDiv = document.getElementById("option1_result");
    hiddenDiv.style.display = (this.value == "") ? "none":"block";
};

Please select the dropdown:

<select id = "dropdown">
  <option id = "1" class = "selected"> option 1</option>
  <option id = "2" class = "selected"> option 2</option>
</select>

      Option 1 Result!
      <button href="#">
      See More
      </button>

      Option 2 result
      <button href="#">
      More about opt 2
      </button>

Ideally I'd like to do this where

case (1):
  hiddenDiv.style.display = "block";

But I'm not sure that will work in this instance.

JSFiddle

Body:
The id attribute is for uniquely identifying an element in the document. It's not intended to convey the value of a select option. For that, you want to use the value attribute:

<select id="dropdown">
  <option value="1" class="selected">option 1</option>
  <option value="2" class="selected">option 2</option>
</select>

Once you have a value for your options, you can check for what the selected value is like this:

if (elem.value === '1') {
  // ...
}


问:
How to prevent blurry scrollbar on Windows Chrome after transform scale?
I'm facing a weird issue while trying to scale an HTML element. As demonstrated in this codepen, I want the element to appear scaled down (transform: scale(0.1)), then animate itself and scale up to its full size (transform: scale(1)). The element is a big list limited in height using overflow: auto;, which means a scrollbar is displayed.

My issue is that the scrollbar arrows are not scaled up correctly compared to the rest of the elements, which makes them extremely blurry and unrecognizable to the user. This only seems to happen on Windows (10) when using Chrome. cf screenshot below

I haven't been able to find any one on the Web talking about this issue, and it seems a bit confounding to me as it doesn't seem to be an edge case, and it is pretty simple to reproduce.

Thanks in advance for any advice :)

答:
Turning my comment into a proper answer:

Slowing down the animation, you can see that the graphics engine of W10 Chrome and Edge (use the same code base since Edge March 2020) simply skip certain scrollbar 'paints' during the animation and only show the thumb whilst scaling...

W10 Firefox does the scaling as expected, however.

This is browser internal code, so I predict a lot of work ahead to circumvent the problem as you need to dive into browser developement and check per browser (HTML/CSS) how to avoid the behaviour.

Would that be worth your time and effort?


问:
Gitlab Option to create branch/merge request for issue automatically
Is there an option in GitLab which enables feature branch/merge request creation by default whenever an issue is created?

I know it is possible to create them manually by clicking that fancy button on the issue page, but let's face it, we're lazy...

答:
I don't think that option already exists - as you mentioned there is the fancy button but I don't think there is a way to click it automatically if you will.

One drawback of this would be that every issue, even those you may not end up implementing, would get a branch.

Could you open an issue to discuss this possibility?


问:
How do I get a volatile function argument working?
I am completely unexperienced in C++, I use C all the time. In my recent hobby project I need to mix in a C++ library with my C code thus forcing me to have a C++ main.cpp.

I am right now meddling my C code to compile as C++. This even works pretty well except for one problem I simply cannot solve.

This is an interrupt service incrementing my unix time variable every second and also doing a conversion into spli-up time format afterwards. Since this happens in an interrupt I set the variables as volatile.

```<code>volatile time_t UNIX_TIME = 0;
volatile struct tm TIME_CUR_LOCALTIME;

if (htim == &htim2){
    UNIX_TIME++;
    TIME_CUR_LOCALTIME = *localtime(&UNIX_TIME);
}
</code>```

From library time.h:

```<code>struct tm *localtime (const time_t *_timer);
</code>```

With gcc this compiles flawless.

g++ is a different story. It gives me the error:

error: passing 'volatile tm' as 'this' argument discards qualifiers [-fpermissive]

I tried multiple casts and stuff, the only way this starts working by itself is when I drop both volatile qualifiers. But I don't want that.

What is the correct way to get this working? I am out of ideas.

答:
Neither the C Standard nor the C++ Standard makes any attempt to distinguish between objects which will be modified in ways a compiler would have no reason to expect, those which will only be written in ways the compiler understands but might also be read in ways it would have no reason to expect, and those which, while declared volatile, will in fact never be accessed in ways the compiler wouldn't expect (the latter situation may arise with libraries that will sometimes be used in systems where things are accessed via outside means and sometimes used in systems where they aren't).  All non-atomic objects that may be accessed in ways the compiler wouldn't expect must be qualified volatile, and because--from the Standard's point of view--all objects that are qualified volatile might be read or written in arbitrary outside means, any access to such an object without a volatile qualifier invokes Undefined Behavior, without regard for whether any outside access actually occurs.  The authors of the Standard probably recognized that since people wishing to sell compilers would handle such cases sensibly without regard for whether they are required to do so, there was no need for the Standard to address such cases.  Not all compiler writers, however, are bound by that principle.

The best way to achieve the behavior at issue here would probably be to copy UNIX_TIME to a couple of ordinary objects, ensuring that they match and repeating the read attempts if not, and then pass the address of that to any functions that would need the address of an object holding the time.  As noted elsewhere, one should avoid functions like localtime that use static buffers, use a function like localtime_r, but what's important if one wants to shut up the compiler is to copy the object somewhere else before use.

Body:
I am completely unexperienced in C++, I use C all the time. In my recent hobby project I need to mix in a C++ library with my C code thus forcing me to have a C++ main.cpp.

I am right now meddling my C code to compile as C++. This even works pretty well except for one problem I simply cannot solve.

This is an interrupt service incrementing my unix time variable every second and also doing a conversion into spli-up time format afterwards. Since this happens in an interrupt I set the variables as volatile.

volatile time_t UNIX_TIME = 0;
volatile struct tm TIME_CUR_LOCALTIME;

if (htim == &htim2){
    UNIX_TIME++;
    TIME_CUR_LOCALTIME = *localtime(&UNIX_TIME);
}

From library time.h:

struct tm *localtime (const time_t *_timer);

With gcc this compiles flawless.

g++ is a different story. It gives me the error:

error: passing 'volatile tm' as 'this' argument discards qualifiers [-fpermissive]

I tried multiple casts and stuff, the only way this starts working by itself is when I drop both volatile qualifiers. But I don't want that.

What is the correct way to get this working? I am out of ideas.


问:
Telerik RadAsyncUpload after validation file missing
May I ask about How to keep the file after validation for Telerik RadAsync Upload.

```<code><telerik:RadScriptManager runat="server" ID="RadScriptManager"></telerik:RadScriptManager>
<telerik:RadAsyncUpload RenderMode="Lightweight" runat="server" ID="RadAsyncUpload1"></telerik:RadAsyncUpload>
</code>```

I had put the Ajax settings, but its not work.

```<code><telerik:RadAjaxManager runat="server" ID="RadAjaxManager1">

            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadAsyncUpload1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadAsyncUpload1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>

            </AjaxSettings>
        </telerik:RadAjaxManager>
</code>```

答:
Here is the client validation function of the validator:

```<code><telerik:RadAsyncUpload ID="RadAsyncUpload2" runat="server" Skin="Outlook" MultipleFileSelection="Automatic"></telerik:RadAsyncUpload>

<asp:CustomValidator runat="server" ID="CustomValidator1" ClientValidationFunction="validateUpload2"
    ErrorMessage="This is Required Field" ForeColor="Red"></asp:CustomValidator>
<script type="text/javascript">

    function validateUpload2(sender, args) {
        var upload = $find("<%=RadAsyncUpload2.ClientID%>");
        args.IsValid = upload.getUploadedFiles().length != 0;
    }
</script>
</code>```

Here is the server validation function of the validator:

```<code>protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
   args.IsValid = (RadAsyncUpload2.UploadedFiles.Count == 0);
}
</code>```

Body:
May I ask about How to keep the file after validation for Telerik RadAsync Upload.

<telerik:RadScriptManager runat="server" ID="RadScriptManager"></telerik:RadScriptManager>
<telerik:RadAsyncUpload RenderMode="Lightweight" runat="server" ID="RadAsyncUpload1"></telerik:RadAsyncUpload>

I had put the Ajax settings, but its not work.

<telerik:RadAjaxManager runat="server" ID="RadAjaxManager1">

            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadAsyncUpload1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadAsyncUpload1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>

            </AjaxSettings>
        </telerik:RadAjaxManager>

Body:
Here is the client validation function of the validator:

<telerik:RadAsyncUpload ID="RadAsyncUpload2" runat="server" Skin="Outlook" MultipleFileSelection="Automatic"></telerik:RadAsyncUpload>

<asp:CustomValidator runat="server" ID="CustomValidator1" ClientValidationFunction="validateUpload2"
    ErrorMessage="This is Required Field" ForeColor="Red"></asp:CustomValidator>
<script type="text/javascript">

    function validateUpload2(sender, args) {
        var upload = $find("<%=RadAsyncUpload2.ClientID%>");
        args.IsValid = upload.getUploadedFiles().length != 0;
    }
</script>

Here is the server validation function of the validator:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
   args.IsValid = (RadAsyncUpload2.UploadedFiles.Count == 0);
}


问:
How to print a dictionary in tabular form and alphabetically?
I have a dictionary and wish to print in tabular form with the first header as "code" and second as "name" and then sorted alphabetically.

i have currently:

```<code> import json
 q = my_dict() #which is the dictionary
 d = json.dumps(q)
 print(d)
</code>```

output:

```<code>"GEL": "Georgian Lari",
"BOB": "Bolivian Boliviano",
"ZAR": "South African Rand",
</code>```

Which is the wrong way round and i am not sure how to insert columns titles. Sorting by Alphabetical order would also help me a lot!

```<code>Name                   Code
"Bolivian Boliviano"   "BOB"
"Georgian Lari"        "GEL"
"South African Rand"   "Zar"
</code>```

Something like this is what im looking for.

答:
Here is how I would do it:</p>

```<code>import pandas as pd

pd.DataFrame(d)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dictionary and wish to print in tabular form with the first header as "code" and second as "name" and then sorted alphabetically.

i have currently:

 import json
 q = my_dict() #which is the dictionary
 d = json.dumps(q)
 print(d)

output:

"GEL": "Georgian Lari",
"BOB": "Bolivian Boliviano",
"ZAR": "South African Rand",

Which is the wrong way round and i am not sure how to insert columns titles. Sorting by Alphabetical order would also help me a lot!

Name                   Code
"Bolivian Boliviano"   "BOB"
"Georgian Lari"        "GEL"
"South African Rand"   "Zar"

Something like this is what im looking for.

Body:
Here is how I would do it:

import pandas as pd

pd.DataFrame(d)


问:
How to send messages between a web client and a JADE multi-agent system?
I am working on a JADE project and I want to build a React app to interact with my agents.

I would like to send messages to specific agents from my web client using REST. I know that it is possible to send POST requests, but what the body should look like ?

答:
take a look at these https://www.iro.umontreal.ca/~vaucher/Agents/Jade/primer2.html and https://jade.tilab.com/doc/tutorials/JADEAdmin/startJade.html.

You may one to create the agents using pure java and invoke it from the UI using React via REST or MVC.


问:
Can't change background color in OpenGL
I've just started to experiment with OpenGL (using freeglut and GLEW). I can get a window to pop up, but nothing gets drawn to it, I can't even get it to change background color.

Here's what the main function looks like:

int
main(int argc, char **argv)
{
  GLenum err;

  /* Initialize GLUT library */
  glutInit(&argc, argv);

  /* Set window mode */
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);

  /* Choose OpenGL version */
  glutInitContextVersion(3, 3);

  /* Choose OpenGL profile */
  glutInitContextFlags(GLUT_CORE_PROFILE);

  /* Create a GLUT window */
  glutCreateWindow("OpenGL 2D");

  /* Initialize GLEW library */
  glewExperimental = GL_TRUE;
  err = glewInit();
  if(err != GLEW_OK) {
    printf("Cannot initialize GLEW: %s\n",
       glewGetErrorString(err));
    return 1;
  }

  /* WORKAROUND: Ignore all GLEW errors */
  while(glGetError() != GL_NO_ERROR)
    ;

  (void) printf("OpenGL vendor: \"%s\"\n"
        "       renderer: \"%s\"\n"
        "       version: \"%s\"\n"
        "       SL version: \"%s\"\n",
        glGetString(GL_VENDOR),
        glGetString(GL_RENDERER),
        glGetString(GL_VERSION),
        glGetString(GL_SHADING_LANGUAGE_VERSION));

  /* Set up callback function for "reshape" event */
  printf("Setting callback functions\n");
  glutReshapeFunc(canvas_reshape);

  /* Set up callback function for "display" event */
  glutDisplayFunc(canvas_display);

  /* Set up callback function for "keyboard" event */
  glutKeyboardFunc(canvas_keyboard);

  /* Set up callback function for "timer" event */
  glutTimerFunc(30, canvas_timer, 0);

  /* Initialize OpenGL */
  init();

  /* Choose the window's position */
  glutPositionWindow(100, 100);

  /* Choose the window's size */
  glutReshapeWindow(800, 600);

  /* Start main loop */
  printf("Entering main loop\n");
  glutMainLoop();

  return 0;
}
```

<p>Here's what init looks like:</p>

<pre class="lang-c prettyprint-override"><code>init()
{
  const GLchar *vertex_shader_source[] = {
    "#version 330 core\n",
    "\n",
    "layout(location=0) in vec4 position;\n",
    "out vec4 color;\n",
    "uniform mat4 viewtrans;\n",
    "\n",
    "void\n",
    "main()\n",
    "{\n",
    "  gl_Position = viewtrans * position;\n"
    "  color =  vec4(1.0, 1.0, 1.0, 1.0);\n"
    "}\n" };
  const GLchar *fragment_shader_source[] = {
    "#version 330 core\n",
    "in vec4 color;\n",
    "layout(location=0) out vec4 fcolor;\n",
    "void\n",
    "main()\n",
    "{\n",
    "  fcolor = color;\n",
    "}\n" };
  char compiler_log[LOGSIZE];

  /* Obtain an unused name for our vertex array */
  printf("Creating vertex array\n");
  glGenVertexArrays(1, &vertex_array);
  check_error("glGenVertexArrays");

  /* Tell OpenGL to use the new vertex array */
  glBindVertexArray(vertex_array);
  check_error("glBindVertexArray");

  /* Obtain an unused name for our vertex buffer */
  printf("Creating vertex buffer\n");
  glGenBuffers(1, &vertex_buffer);
  check_error("glGenBuffers");

  /* Tell OpenGL to use the new vertex buffer as the
   * vertex array */
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
  check_error("glBindBuffer");

  /* We want to get two coordinates from the vertex buffer and
   * feed them as the first parameter to the vertex shader */
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 2, 0);

  /* Create vertex shader */
  printf("Creating vertex shader\n");
  vertex_shader = glCreateShader(GL_VERTEX_SHADER);
  check_error("glCreateShader");

  /* Assign vertex shader source code */
  glShaderSource(vertex_shader, sizeof(vertex_shader_source) / sizeof(GLchar *),
         vertex_shader_source, 0);
  check_error("glShaderSource");

  /* Compile vertex shader */
  glCompileShader(vertex_shader);
  check_error("glCompileShader");

  /* Get compiler log *//* Set up callback function for "timer" event */
  glGetShaderInfoLog(vertex_shader, LOGSIZE, 0, compiler_log);
  printf("  Compiler log: \"%s\"\n", compiler_log);

  /* Create fragment shader */
  printf("Creating fragment shader\n");
  fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
  check_error("glCreateShader");

  /* Assign fragment shader source code */
  glShaderSource(fragment_shader, sizeof(fragment_shader_source) / sizeof(GLchar *),
         fragment_shader_source, 0);
  check_error("glShaderSource");

  /* Compile fragment shader */
  glCompileShader(fragment_shader);
  check_error("glCompileShader");

  /* Get compiler log */
  glGetShaderInfoLog(fragment_shader, LOGSIZE, 0, compiler_log);
  printf("  Compiler log: \"%s\"\n", compiler_log);

  /* Create shader program */
  printf("Creating shader program\n");
  shader_program = glCreateProgram();
  check_error("glCreateProgram");

  /* Attach vertex shader */
  glAttachShader(shader_program, vertex_shader);
  check_error("glAttachShader");

  /* Attach fragment shader */
  glAttachShader(shader_program, fragment_shader);
  check_error("glAttachShader");

  /* Link shader program */
  glLinkProgram(shader_program);
  check_error("glLinkProgram");

  /* Get linker log */
  glGetProgramInfoLog(shader_program, LOGSIZE, 0, compiler_log);
  printf("  Linker log: \"%s\"\n", compiler_log);

  /* Get location of "viewtrans" matrix */
  viewtrans = glGetUniformLocation(shader_program, "viewtrans");
  check_error("glGetUniformLocation");

  /* Tell OpenGL to use the new shader program */
  glUseProgram(shader_program);

  /* Choose background color */
  glClearColor(1.0, 0.0, 1.0, 0.0);
}
</code>```

Here's what I use to draw:

static void
canvas_display()
{
  glClearColor(0.0, 0.0, 0.0, 0.0);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
```

<p>This is all based off of a tutorial. What actually happens is something like a 300 x 300 white window shows up, gets reshaped into a 800 x 600 black window, BUT with still a 300 x 300 white square in the middle or in a corner, whose pixels (partially) turn black when resizing the window such that (part of) the square disappears (either manually or through code). I've also written code to draw triangles, but that doesn't work either, as one might expect. But here's the code for that anyway:</p>

<pre class="lang-c prettyprint-override"><code>static void
canvas_display()
{
    glClearColor(0.0, 0.0, 0.0, 0.0);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    GLfloat vertices[] =
    { 0.0, 0.0,
      0.5, 0.5,
      0.5, 0.0 };

    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT) * 2, vertices);

    glDrawArrays(GL_TRIANGLES, 0, 3);
}
</code>```

答:
Do not continuously specify the new vertex array objects. Create 1 Vertex Array Object at initialization. The vertex array is contained in the Vertex Buffer Object. When a named buffer object is bound to the ARRAY_BUFFER target, then the last parameter of glVertexAttribPointer is treated as a byte offset into the buffer object's data store. Thus the offset has to be NULL:

void init()
{
    // [...]

    GLfloat vertices[] =
    { 0.0, 0.0,
      0.5, 0.5,
      0.5, 0.0 };

    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT) * 2, NULL);
}
```

<p>Ensure that the program is installed and the VAO is bound when the geometry is drawn. By default the values of uniforms are initialized by zero. At least you have to set the Identity matrix then matrix uniform <code>viewtrans</code>.<br>
Since you use double buffering (<code>GLUT_DOUBLE</code>), you have to swaps the buffers of the current window after drawing all the geometry by <code>glutSwapBuffers</code></p>

<pre class="lang-cpp prettyprint-override"><code>void canvas_display()
{
    glClearColor(1.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(shader_program);
    GLfloat identity_mat[] = { 1,0,0,0,  0,1,0,0, 0,0,1,0, 0,0,0,1 };
    glUniformMatrix4fv(viewtrans, 1, GL_FALSE, identity_mat);

    glBindVertexArray(vertex_array);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glutSwapBuffers();
    glutPostRedisplay();
}
</code>```

Title: Can't change background color in OpenGL

Body:
I've just started to experiment with OpenGL (using freeglut and GLEW). I can get a window to pop up, but nothing gets drawn to it, I can't even get it to change background color.

Here's what the main function looks like:

int
main(int argc, char **argv)
{
  GLenum err;

  /* Initialize GLUT library */
  glutInit(&argc, argv);

  /* Set window mode */
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);

  /* Choose OpenGL version */
  glutInitContextVersion(3, 3);

  /* Choose OpenGL profile */
  glutInitContextFlags(GLUT_CORE_PROFILE);

  /* Create a GLUT window */
  glutCreateWindow("OpenGL 2D");

  /* Initialize GLEW library */
  glewExperimental = GL_TRUE;
  err = glewInit();
  if(err != GLEW_OK) {
    printf("Cannot initialize GLEW: %s\n",
       glewGetErrorString(err));
    return 1;
  }

  /* WORKAROUND: Ignore all GLEW errors */
  while(glGetError() != GL_NO_ERROR)
    ;

  (void) printf("OpenGL vendor: \"%s\"\n"
        "       renderer: \"%s\"\n"
        "       version: \"%s\"\n"
        "       SL version: \"%s\"\n",
        glGetString(GL_VENDOR),
        glGetString(GL_RENDERER),
        glGetString(GL_VERSION),
        glGetString(GL_SHADING_LANGUAGE_VERSION));

  /* Set up callback function for "reshape" event */
  printf("Setting callback functions\n");
  glutReshapeFunc(canvas_reshape);

  /* Set up callback function for "display" event */
  glutDisplayFunc(canvas_display);

  /* Set up callback function for "keyboard" event */
  glutKeyboardFunc(canvas_keyboard);

  /* Set up callback function for "timer" event */
  glutTimerFunc(30, canvas_timer, 0);

  /* Initialize OpenGL */
  init();

  /* Choose the window's position */
  glutPositionWindow(100, 100);

  /* Choose the window's size */
  glutReshapeWindow(800, 600);

  /* Start main loop */
  printf("Entering main loop\n");
  glutMainLoop();

  return 0;
}

Here's what init looks like:

init()
{
  const GLchar *vertex_shader_source[] = {
    "#version 330 core\n",
    "\n",
    "layout(location=0) in vec4 position;\n",
    "out vec4 color;\n",
    "uniform mat4 viewtrans;\n",
    "\n",
    "void\n",
    "main()\n",
    "{\n",
    "  gl_Position = viewtrans * position;\n"
    "  color =  vec4(1.0, 1.0, 1.0, 1.0);\n"
    "}\n" };
  const GLchar *fragment_shader_source[] = {
    "#version 330 core\n",
    "in vec4 color;\n",
    "layout(location=0) out vec4 fcolor;\n",
    "void\n",
    "main()\n",
    "{\n",
    "  fcolor = color;\n",
    "}\n" };
  char compiler_log[LOGSIZE];

  /* Obtain an unused name for our vertex array */
  printf("Creating vertex array\n");
  glGenVertexArrays(1, &vertex_array);
  check_error("glGenVertexArrays");

  /* Tell OpenGL to use the new vertex array */
  glBindVertexArray(vertex_array);
  check_error("glBindVertexArray");

  /* Obtain an unused name for our vertex buffer */
  printf("Creating vertex buffer\n");
  glGenBuffers(1, &vertex_buffer);
  check_error("glGenBuffers");

  /* Tell OpenGL to use the new vertex buffer as the
   * vertex array */
  glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
  check_error("glBindBuffer");

  /* We want to get two coordinates from the vertex buffer and
   * feed them as the first parameter to the vertex shader */
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 2, 0);

  /* Create vertex shader */
  printf("Creating vertex shader\n");
  vertex_shader = glCreateShader(GL_VERTEX_SHADER);
  check_error("glCreateShader");

  /* Assign vertex shader source code */
  glShaderSource(vertex_shader, sizeof(vertex_shader_source) / sizeof(GLchar *),
         vertex_shader_source, 0);
  check_error("glShaderSource");

  /* Compile vertex shader */
  glCompileShader(vertex_shader);
  check_error("glCompileShader");

  /* Get compiler log *//* Set up callback function for "timer" event */
  glGetShaderInfoLog(vertex_shader, LOGSIZE, 0, compiler_log);
  printf("  Compiler log: \"%s\"\n", compiler_log);

  /* Create fragment shader */
  printf("Creating fragment shader\n");
  fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
  check_error("glCreateShader");

  /* Assign fragment shader source code */
  glShaderSource(fragment_shader, sizeof(fragment_shader_source) / sizeof(GLchar *),
         fragment_shader_source, 0);
  check_error("glShaderSource");

  /* Compile fragment shader */
  glCompileShader(fragment_shader);
  check_error("glCompileShader");

  /* Get compiler log */
  glGetShaderInfoLog(fragment_shader, LOGSIZE, 0, compiler_log);
  printf("  Compiler log: \"%s\"\n", compiler_log);

  /* Create shader program */
  printf("Creating shader program\n");
  shader_program = glCreateProgram();
  check_error("glCreateProgram");

  /* Attach vertex shader */
  glAttachShader(shader_program, vertex_shader);
  check_error("glAttachShader");

  /* Attach fragment shader */
  glAttachShader(shader_program, fragment_shader);
  check_error("glAttachShader");

  /* Link shader program */
  glLinkProgram(shader_program);
  check_error("glLinkProgram");

  /* Get linker log */
  glGetProgramInfoLog(shader_program, LOGSIZE, 0, compiler_log);
  printf("  Linker log: \"%s\"\n", compiler_log);

  /* Get location of "viewtrans" matrix */
  viewtrans = glGetUniformLocation(shader_program, "viewtrans");
  check_error("glGetUniformLocation");

  /* Tell OpenGL to use the new shader program */
  glUseProgram(shader_program);

  /* Choose background color */
  glClearColor(1.0, 0.0, 1.0, 0.0);
}

Here's what I use to draw:

static void
canvas_display()
{
  glClearColor(0.0, 0.0, 0.0, 0.0);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

This is all based off of a tutorial. What actually happens is something like a 300 x 300 white window shows up, gets reshaped into a 800 x 600 black window, BUT with still a 300 x 300 white square in the middle or in a corner, whose pixels (partially) turn black when resizing the window such that (part of) the square disappears (either manually or through code). I've also written code to draw triangles, but that doesn't work either, as one might expect. But here's the code for that anyway:

static void
canvas_display()
{
    glClearColor(0.0, 0.0, 0.0, 0.0);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    GLfloat vertices[] =
    { 0.0, 0.0,
      0.5, 0.5,
      0.5, 0.0 };

    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT) * 2, vertices);

    glDrawArrays(GL_TRIANGLES, 0, 3);
}

Body:
Do not continuously specify the new vertex array objects. Create 1 Vertex Array Object at initialization. The vertex array is contained in the Vertex Buffer Object. When a named buffer object is bound to the ARRAY_BUFFER target, then the last parameter of glVertexAttribPointer is treated as a byte offset into the buffer object's data store. Thus the offset has to be NULL:

void init()
{
    // [...]

    GLfloat vertices[] =
    { 0.0, 0.0,
      0.5, 0.5,
      0.5, 0.0 };

    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT) * 2, NULL);
}

Ensure that the program is installed and the VAO is bound when the geometry is drawn. By default the values of uniforms are initialized by zero. At least you have to set the Identity matrix then matrix uniform viewtrans.

Since you use double buffering (GLUT_DOUBLE), you have to swaps the buffers of the current window after drawing all the geometry by glutSwapBuffers

void canvas_display()
{
    glClearColor(1.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(shader_program);
    GLfloat identity_mat[] = { 1,0,0,0,  0,1,0,0, 0,0,1,0, 0,0,0,1 };
    glUniformMatrix4fv(viewtrans, 1, GL_FALSE, identity_mat);

    glBindVertexArray(vertex_array);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glutSwapBuffers();
    glutPostRedisplay();
}


问:
How to resize std::string to remove all null terminator characters?
I'm using a std::string to interface with a C-library that requires a char* and a length field:

```<code>std::string buffer(MAX_BUFFER_SIZE, '\0');
TheCLibraryFunction(&buffer[0], buffer.size());
</code>```

However, the size() of the string is the actual size, not the size of the string containing actual valid non-null characters (i.e. the equivalent of strlen()). What is the best method of telling the std::string to reduce its size so that there's <s>only 1 ending null terminator character</s> no explicit null terminator characters? The best solution I can think of is something like:

```<code>buffer.resize(strlen(buffer.c_str()));
</code>```

Or even:

```<code>char buffer[MAX_BUFFER_SIZE]{};
TheCLibraryFunction(buffer, sizeof(buffer));
std::string thevalue = buffer;
</code>```

Hoping for some built-in / "modern C++" way of doing this.

EDIT

I'd like to clarify the "ending null terminator" requirement I mentioned previously. I didn't mean that I want 1 null terminator explicitly in std::string's buffer, I was more or less thinking of the string as it comes out of basic_string::c_str() which has 1 null terminator. However for the purposes of the resize(), I want it to represent the size of actual non-null characters. Sorry for the confusion.

答:
One Liner using boost::trim_if if you want to trim multiple characters (I wanted to remove \r, \n, \0 and ' ') from the string:

```<code>int main()
{
    std::string str("abcd \0 \r\n \0", 12);
    std::cout << "Str: " << str << std::endl;
    std::cout << "Length: " << str.length() << std::endl;

    boost::trim_if(str, boost::is_any_of(std::string("\r\n\0 ", 4)));

    std::cout << "Length: " << str.length() << std::endl;
    return 0;
}
</code>```

Prints:

```<code>Str: abcd

Length: 12
Length: 4
</code>```

Body:
I'm using a std::string to interface with a C-library that requires a char* and a length field:

std::string buffer(MAX_BUFFER_SIZE, '\0');
TheCLibraryFunction(&buffer[0], buffer.size());

However, the size() of the string is the actual size, not the size of the string containing actual valid non-null characters (i.e. the equivalent of strlen()). What is the best method of telling the std::string to reduce its size so that there's <s>only 1 ending null terminator character</s> no explicit null terminator characters? The best solution I can think of is something like:

buffer.resize(strlen(buffer.c_str()));

Or even:

char buffer[MAX_BUFFER_SIZE]{};
TheCLibraryFunction(buffer, sizeof(buffer));
std::string thevalue = buffer;

Hoping for some built-in / "modern C++" way of doing this.

EDIT

I'd like to clarify the "ending null terminator" requirement I mentioned previously. I didn't mean that I want 1 null terminator explicitly in std::string's buffer, I was more or less thinking of the string as it comes out of basic_string::c_str() which has 1 null terminator. However for the purposes of the resize(), I want it to represent the size of actual non-null characters. Sorry for the confusion.

Body:
One Liner using boost::trim_if if you want to trim multiple characters (I wanted to remove \r, \n, \0 and ' ') from the string:

int main()
{
    std::string str("abcd \0 \r\n \0", 12);
    std::cout << "Str: " << str << std::endl;
    std::cout << "Length: " << str.length() << std::endl;

    boost::trim_if(str, boost::is_any_of(std::string("\r\n\0 ", 4)));

    std::cout << "Length: " << str.length() << std::endl;
    return 0;
}

Prints:

Str: abcd

Length: 12
Length: 4


问:
How to compare two enums?
I have two enums:

```<code>public enum UserType {
    USER,
    EMPLOYER

}
</code>```

```<code>public enum UserDetails {
    USER,
    EMPLOYER
}
</code>```

I try to compare this by this:

```<code>if(UserType.USER.equals(UserDetails.USER)){
    return true;
}
</code>```

but i can't because, my equals() throw me this:

```<code>equals() between objects of inconvertible types 'UserType' and 'UserDetails'
</code>```

so, how can I compare two values from two diffrent enums?

答:
Different types

The enum in Java is a class, albeit a slightly special kind of class. A class defines a type.

Unless related by inheritance or by interface, different types cannot be compared for equality. A String cannot be equal to a LocalDate which cannot be equal to a DataSource.

Likewise, an object of enum UserType cannot be equal to an object of enum UserDetails. Apples to oranges, not equal by definition.  So, your Question is senseless, technically.

The fact that some enum classes happen to share names on some of their constants has no meaning, it is just coincidence that your two enums share the name USER or EMPLOYER. The enum Month bundled with Java defines a constant named APRIL. I might define another enum with an object also named APRIL. But that does not make them equal.

Asking this question suggests that you have a problem with your design. Perhaps you should post another Question on that design issue if it has but already been addressed on Stack Overflow. As commented by Kayaman, your Question seems like an XY Problem.

The other Answers suggesting you:

Compare the strings of the names of the enum constants.

Compare the ordinal position of the constants within the enum definition.

…are misguided. Those approaches violate the purpose of enums in Java, which is to provide a type-safe identity of certain values known at compile-time.

If you are comparing the names of the constants, then you might as well be using mere String objects rather than enums.

If you are comparing ordinal numbers, then you might as well be using mere integer numbers rather than enums.

Both cases are fragile, resulting in runtime failures if you make a change to one enum without matching the other. And in both cases you have lost the usefulness of the enum, transmogrifying the enum into a confusing level of indirection for a string or int.

Title: How to compare two enums?

Body:
I have two enums:

public enum UserType {
    USER,
    EMPLOYER

}

public enum UserDetails {
    USER,
    EMPLOYER
}

I try to compare this by this:

if(UserType.USER.equals(UserDetails.USER)){
    return true;
}

but i can't because, my equals() throw me this:

equals() between objects of inconvertible types 'UserType' and 'UserDetails'

so, how can I compare two values from two diffrent enums?


问:
Hello, I am trying to arrange an array from the small value to big value, but its not working
I am trying to arrange an array from the small value to grow, and for some reason this function does not work (SmallToGrow), the rest is excellent. Thanks.

There are auxiliary functions that I use and are excellent facts, only the (SmallToGrow) function does not work for me and I cannot understand why. I'd love anyone who can help. Thanks
    enter code here

```<code>  //this check if all cells equals
   public bool EverybodyAreEqual(int [] array)
        {
            for (int i = 0; i < array.Length - 1; i++)
                if (array[i] != array[i + 1])
                return false;
            return true;
        }
//This function changes all the values in the array that contain the -numInArray- value you entered,
 // to the -numChanged- value you entered
 public void ChangNumWhere(ref  int []  array,int numInArray,int numChanged)
        {
            for (int i = 0; i < array.Length; i++)
                if (array[i] == numInArray)
                    array[i] = numChanged;
        }
   //A function that returns the number of values that are not equal in the array
    public int NumDifferentArray(int [] array)
        {
             int[] arr = new int[array.Length];
               for (int i = 0; i < arr.Length; i++)
                  arr[i] = array[i];
             bool con = true;
             int contain = 0;
             int index = 0;
             for(int i=0; con;i++)
             {
                if (!arr.Contains(i))
                 {
                  contain = i;
                  con = false;
                }
             }
            while(!this.EverybodyAreEqual(arr))
            {
                for (int i = 0; i < arr.Length; i++)
                    if (arr[i] != contain)
                    {
                        this.ChangNumWhere(ref arr, arr[i], contain);
                        index++;
                    }
            }
            return index;
        }
 public int HowTimesExsist(int [] array,int num)
        {
            int index = 0;
            for(int i=0;i<array.Length;i++)
            {
                if (array[i] == num)
                    index++;
            }
            return index;
        }
  /// This function returns a minimum value as required,
  /// for example if you requested 0 the smallest value is returned,
  /// if 1 is returned one above it and so on,
  /// if the index is greater than the length of the array the largest number is returned
    public int MinBottom(int[] array, int num)
        {
            if (num < 0)
                throw new Exception("num canot be less then 0");
            int max = this.MaxArray(array);
            while (num > 0)
            {
               int min = this.MinArray(array);
               for (int i = 0; i < array.Length; i++)
                    if(array[i]==min)
                         array[i] = max;
                num--;
            }
            return this.MinArray(array);
        }
 public  int[]  SmallToGrow(int [] array)
        {
            int i = 0;
            int[] arr = new int[array.Length];
             for (int j = 0; j < this.NumDifferentArray(array); j++)
                for (int b = 0; b < this.HowTimesExsist(array, MinBottom(array, j)); i++, b++)
                    arr[i] = this.MinBottom(array, j);
            return arr;
         }
</code>```

答:
Why don't you use a list instead? They have a method attached to it that sorts it all for you.

```<code>List<int> sortInt = new List<int>() { 2, 5, 1, 50, 258, 87, 63, 52, 100, 85, 21 };

sortInt.Sort();
</code>```

Returned them in numerical order with [0] being 1 and [10] being 258.

you can then turn the list to an array with sortint.ToArray();.

Edit

As dymanoid mentioned you can just use your array and just run the array.Sort() method with it. Learn something new every day.

Body:
I am trying to arrange an array from the small value to grow, and for some reason this function does not work (SmallToGrow), the rest is excellent. Thanks.

There are auxiliary functions that I use and are excellent facts, only the (SmallToGrow) function does not work for me and I cannot understand why. I'd love anyone who can help. Thanks
    enter code here

  //this check if all cells equals
   public bool EverybodyAreEqual(int [] array)
        {
            for (int i = 0; i < array.Length - 1; i++)
                if (array[i] != array[i + 1])
                return false;
            return true;
        }
//This function changes all the values in the array that contain the -numInArray- value you entered,
 // to the -numChanged- value you entered
 public void ChangNumWhere(ref  int []  array,int numInArray,int numChanged)
        {
            for (int i = 0; i < array.Length; i++)
                if (array[i] == numInArray)
                    array[i] = numChanged;
        }
   //A function that returns the number of values that are not equal in the array
    public int NumDifferentArray(int [] array)
        {
             int[] arr = new int[array.Length];
               for (int i = 0; i < arr.Length; i++)
                  arr[i] = array[i];
             bool con = true;
             int contain = 0;
             int index = 0;
             for(int i=0; con;i++)
             {
                if (!arr.Contains(i))
                 {
                  contain = i;
                  con = false;
                }
             }
            while(!this.EverybodyAreEqual(arr))
            {
                for (int i = 0; i < arr.Length; i++)
                    if (arr[i] != contain)
                    {
                        this.ChangNumWhere(ref arr, arr[i], contain);
                        index++;
                    }
            }
            return index;
        }
 public int HowTimesExsist(int [] array,int num)
        {
            int index = 0;
            for(int i=0;i<array.Length;i++)
            {
                if (array[i] == num)
                    index++;
            }
            return index;
        }
  /// This function returns a minimum value as required,
  /// for example if you requested 0 the smallest value is returned,
  /// if 1 is returned one above it and so on,
  /// if the index is greater than the length of the array the largest number is returned
    public int MinBottom(int[] array, int num)
        {
            if (num < 0)
                throw new Exception("num canot be less then 0");
            int max = this.MaxArray(array);
            while (num > 0)
            {
               int min = this.MinArray(array);
               for (int i = 0; i < array.Length; i++)
                    if(array[i]==min)
                         array[i] = max;
                num--;
            }
            return this.MinArray(array);
        }
 public  int[]  SmallToGrow(int [] array)
        {
            int i = 0;
            int[] arr = new int[array.Length];
             for (int j = 0; j < this.NumDifferentArray(array); j++)
                for (int b = 0; b < this.HowTimesExsist(array, MinBottom(array, j)); i++, b++)
                    arr[i] = this.MinBottom(array, j);
            return arr;
         }

Body:
Why don't you use a list instead? They have a method attached to it that sorts it all for you.

List<int> sortInt = new List<int>() { 2, 5, 1, 50, 258, 87, 63, 52, 100, 85, 21 };

sortInt.Sort();

Returned them in numerical order with [0] being 1 and [10] being 258.

you can then turn the list to an array with sortint.ToArray();.

Edit

As dymanoid mentioned you can just use your array and just run the array.Sort() method with it. Learn something new every day.


问:
How to generate skeleton view using human pose estimation?
I am trying to use human pose estimation through keras implementation. I am using this source https://github.com/michalfaber/keras_Realtime_Multi-Person_Pose_Estimation. My problem is how can I generate the skeleton view of the following image, the one on the left part? However, I can generate the one on the right part.

** Source Photograph taken from Pexels

Below is the code I am using to achieve this.

```<code>    # vgg normalization (subtracting mean) on input images
    model = get_testing_model()
    model.load_weights(keras_weights_file)

    # load config
    params, model_params = config_reader()

    input_image = cv2.imread(image_path)  # B,G,R order

    body_parts, all_peaks, subset, candidate = extract_parts(input_image, params, model, model_params)
    canvas = draw(input_image, all_peaks, subset, candidate)

    toc = time.time()
    print('processing time is %.5f' % (toc - tic))

    cv2.imwrite(output, canvas)

    cv2.destroyAllWindows()
</code>```

答:
You need to draw over black image not input image for your requirement. Here below in the updated code.    </p>

```<code># vgg normalization (subtracting mean) on input images
model = get_testing_model()
model.load_weights(keras_weights_file)

# load config
params, model_params = config_reader()

input_image = cv2.imread(image_path)  # B,G,R order

body_parts, all_peaks, subset, candidate = extract_parts(input_image, params, model, model_params)
black_img = np.zeros_like(input_image, np.uint8)
canvas = draw(black_img, all_peaks, subset, candidate)

toc = time.time()
print('processing time is %.5f' % (toc - tic))

cv2.imwrite(output, canvas)

cv2.destroyAllWindows()
</code>```

Body:
I am trying to use human pose estimation through keras implementation. I am using this source https://github.com/michalfaber/keras_Realtime_Multi-Person_Pose_Estimation. My problem is how can I generate the skeleton view of the following image, the one on the left part? However, I can generate the one on the right part.

** Source Photograph taken from Pexels

Below is the code I am using to achieve this.

    # vgg normalization (subtracting mean) on input images
    model = get_testing_model()
    model.load_weights(keras_weights_file)

    # load config
    params, model_params = config_reader()

    input_image = cv2.imread(image_path)  # B,G,R order

    body_parts, all_peaks, subset, candidate = extract_parts(input_image, params, model, model_params)
    canvas = draw(input_image, all_peaks, subset, candidate)

    toc = time.time()
    print('processing time is %.5f' % (toc - tic))

    cv2.imwrite(output, canvas)

    cv2.destroyAllWindows()

Body:
You need to draw over black image not input image for your requirement. Here below in the updated code.

# vgg normalization (subtracting mean) on input images
model = get_testing_model()
model.load_weights(keras_weights_file)

# load config
params, model_params = config_reader()

input_image = cv2.imread(image_path)  # B,G,R order

body_parts, all_peaks, subset, candidate = extract_parts(input_image, params, model, model_params)
black_img = np.zeros_like(input_image, np.uint8)
canvas = draw(black_img, all_peaks, subset, candidate)

toc = time.time()
print('processing time is %.5f' % (toc - tic))

cv2.imwrite(output, canvas)

cv2.destroyAllWindows()


问:
Prevent CSS Inheritance
I am trying to write a jQuery plugin that can be ported to any site.

What my plugin does is create a div and applies a style to it.

It works well in standalone but when I put it into the context of a site, there is a css class that it is inheriting from.  The thing is, I can't modify the web site's existing CSS... so I need a way to "prevent inheritance" (which I know is technically not possible).

I have tried the !important flag on the specific styles that are causing problems, but to no avail.  I am looking for a point in the right direction more than specific code, so that's why I'm not posting all of my code...

The other thing is that I do not want to use an iframe instead of a div because I need to be able to provide the ability for a form to interact with my div, potentially.

However, the two css classes from the web site (which I can not modify) that are causing my problems are:

```<code>* {
    font-weight: inherit;
    font-style: inherit;
    border: 0 none;
    outline: 0;
    padding: 0;
    margin: 0;
}

html {
    width: 100%;
    height: 100%;
    font-size: 10px;
}
</code>```

答:
CSS isn't inheritance-based, but rather "cascading" (it's the first C in "CSS").  Understanding that, there are a few ways you could work around the issue you describe:

1) Add inline styles to your element via script.  Inline styles take precedence over CSS rules, either from classes, ids, or elements.

2) Add your own CSS file programmatically.  CSS cascades in the order the rule appears in the document.  You can write a CSS link element to the bottom of the page to include your plugin's CSS rules.  Since these are presumably lower or "later" in the document than the site's CSS, your rules will take precedence.

3) Write a style tag to the bottom of the document programmatically.  Same concept here as #2, but without an external file.

I would personally tend toward #1.  If you want your plugin to be consistent in appearance no matter what else is going on, no matter what site it is used on, the only way to be sure is to apply your styles inline.

That said, there's value in making your plugin's interface customizable by using CSS classes.  Maybe you're trying to take something away that you shouldn't.  For instance, if the entire site uses a Serif font, and you're forcing a Sans font on your plugin's UI, your plugin's look and feel is now at odds with the site.  That could be a deal-breaker when someone is considering your plugin... customization is a good thing in the world of reusable code, and CSS is the way to make it happen.

Title: Prevent CSS Inheritance

Body:
I am trying to write a jQuery plugin that can be ported to any site.

What my plugin does is create a div and applies a style to it.

It works well in standalone but when I put it into the context of a site, there is a css class that it is inheriting from.  The thing is, I can't modify the web site's existing CSS... so I need a way to "prevent inheritance" (which I know is technically not possible).

I have tried the !important flag on the specific styles that are causing problems, but to no avail.  I am looking for a point in the right direction more than specific code, so that's why I'm not posting all of my code...

The other thing is that I do not want to use an iframe instead of a div because I need to be able to provide the ability for a form to interact with my div, potentially.

However, the two css classes from the web site (which I can not modify) that are causing my problems are:

* {
    font-weight: inherit;
    font-style: inherit;
    border: 0 none;
    outline: 0;
    padding: 0;
    margin: 0;
}

html {
    width: 100%;
    height: 100%;
    font-size: 10px;
}


问:
Not able to access websites when Charles Proxy is opened (Windows 10)
I downloaded the app Charles Proxy, I added the certificate and I can confirm that the Charles certificate is in my certlm (Certificate Manager) in the "Trusted Root Certification" folder, I had also enabled SSL Proxying to include this location: "*:443" which I believe means that I want to see all data coming in.

I'm not sure what the problem is, but whenever I open up Charles Proxy, it doesn't allow me to access any websites, all the data coming in Charles is coming in as status: "Blocked"

I'm using Windows 10 if that helps. I didn't have this issue on MacOS, Help is appreciated!

答: I personally have never used Charles on a Windows machine but it sounds like your browser isn't configured to run through the proxy.  Firefox use to have an add-on for Charles but now you have to manually enter the proxy ip to intercept the data.  I'm not sure if you can use any other browsers on Windows with Charles, but use Firefox and go to Preferences > Network Settings > Manual Proxy Configuration and add your machine's ip address and the default Charles port 8888.  Also make sure to check the checkbox to allow HTTPS.  Save these changes and you should be good to go.</p>


问:
ADB Android Device Unauthorized
Since I reinstalled Eclipse (simply deleted and downloaded it again) I can't debug my applications on Samsung Galaxy i9001 (with CyanogenMod - Android 4.4.2). It worked fine before reinstallation.

Unplug/plug, Uncheck/check "Debug Enabled", adb kill-server/adb start-server, restart phone/computer doesn't work for me. On the device authorize dialog never appears (but I remember that dialog appeared before reinstallation). I have no idea how to force this authorize dialog to display. There is no abd_key.pub file in .android directory.
When i try read cpu info DDMS says:

```<code>[2014-04-15 12:47:06 - DDMS] device unauthorized. Please check the confirmation dialog on your device.
</code>```

Any ideas? Is it possible to generate keys manually without confirmation dialog?

USB Connection

Wireless Connection

答:
Here's what I did that that brought the authorization prompt and made my device appear. I used a Samsung Galaxy s7 edge.

Enable developer mode and USB debugging on your device.

Revoke the USB debugging authorization

Plug your phone to computer via USB.

Drag notification panel and select "Software Installation" as shown in the image below

This will begin installing USB driver and the prompt for USB debugging authorization will show.

Title: ADB Android Device Unauthorized

Body:
Since I reinstalled Eclipse (simply deleted and downloaded it again) I can't debug my applications on Samsung Galaxy i9001 (with CyanogenMod - Android 4.4.2). It worked fine before reinstallation.

Unplug/plug, Uncheck/check "Debug Enabled", adb kill-server/adb start-server, restart phone/computer doesn't work for me. On the device authorize dialog never appears (but I remember that dialog appeared before reinstallation). I have no idea how to force this authorize dialog to display. There is no abd_key.pub file in .android directory.
When i try read cpu info DDMS says:

[2014-04-15 12:47:06 - DDMS] device unauthorized. Please check the confirmation dialog on your device.

Any ideas? Is it possible to generate keys manually without confirmation dialog?

USB Connection

Wireless Connection


问:
Exercise 24 - Find the model number of the product (PC, laptop, or printer) with the highest price. Result set: model
I have this SQL statement and it returns the correct answer but it's too long as I can't figure out how to reuse the alias, so I had wrote the whole SELECT again:

```<code>select model from
(
select model, max(price) as maxt from
(
select model,price from pc where price in (select max(price) from pc)
union
select model,price from laptop where price in (select max(price) from laptop)
union
select model,price from printer where price in (select max(price) from printer)
) as ab
group by model
) as ba
where maxt in

(
select max(maxt) from (

select model, max(price) as maxt from
(
select model,price from pc where price in (select max(price) from pc)
union
select model,price from laptop where price in (select max(price) from laptop)
union
select model,price from printer where price in (select max(price) from printer)
) as aba
group by model
) as bac )
</code>```

The exercise is :
Find the model number of the product (PC, laptop, or printer) with the highest price.
Result set: model.

Table Laptop

```<code>code    model   speed   ram hd      price       screen
------------------------------------------------------
1       1298    350     32  4.0     700.0000    11
2       1321    500     64  8.0     970.0000    12
3       1750    750     128 12.0    1200.0000   14
4       1298    600     64  10.0    1050.0000   15
5       1752    750     128 10.0    1150.0000   14
6       1298    450     64  10.0    950.0000    12
</code>```

The PC table:

```<code>code     model  speed   ram hd  cd  price
-------------------------------------------------------
1   1232    500 64  5.0 12x 600.0000
10  1260    500 32  10.0    12x 350.0000
11  1233    900 128 40.0    40x 980.0000
12  1233    800 128 20.0    50x 970.0000
2   1121    750 128 14.0    40x 850.0000
3   1233    500 64  5.0 12x 600.0000
4   1121    600 128 14.0    40x 850.0000
5   1121    600 128 8.0 40x 850.0000
6   1233    750 128 20.0    50x 950.0000
7   1232    500 32  10.0    12x 400.0000
8   1232    450 64  8.0 24x 350.0000
9   1232    450 32  10.0    24x 350.0000
</code>```

Printer table:

```<code>code    model   color   type    price
-----------------------------------------
1   1276    n   Laser   400.0000
2   1433    y   Jet 270.0000
3   1434    y   Jet 290.0000
4   1401    n   Matrix  150.0000
5   1408    n   Matrix  270.0000
6   1288    n   Laser   400.0000
</code>```

Table Product:

```<code>maker   model   Type
-----------------------
A       1232    PC
A       1233    PC
A       1276    Printer
A       1298    Laptop
A       1401    Printer
A       1408    Printer
A       1752    Laptop
B       1121    PC
B       1750    Laptop
C       1321    Laptop
D       1288    Printer
D       1433    Printer
E       1260    PC
E       1434    Printer
E       2112    PC
E       2113    PC
</code>```

答:
For the same question:
Find the printer models having the highest price. Result set: model, price.

the following code seemed to work as well

select model, price
from
printer
where
price = (select max(price) from printer)
order by price desc
```

Body:
I have this SQL statement and it returns the correct answer but it's too long as I can't figure out how to reuse the alias, so I had wrote the whole SELECT again:

select model from
(
select model, max(price) as maxt from
(
select model,price from pc where price in (select max(price) from pc)
union
select model,price from laptop where price in (select max(price) from laptop)
union
select model,price from printer where price in (select max(price) from printer)
) as ab
group by model
) as ba
where maxt in

(
select max(maxt) from (

select model, max(price) as maxt from
(
select model,price from pc where price in (select max(price) from pc)
union
select model,price from laptop where price in (select max(price) from laptop)
union
select model,price from printer where price in (select max(price) from printer)
) as aba
group by model
) as bac )

The exercise is :
Find the model number of the product (PC, laptop, or printer) with the highest price.
Result set: model.

Table Laptop

code    model   speed   ram hd      price       screen
------------------------------------------------------
1       1298    350     32  4.0     700.0000    11
2       1321    500     64  8.0     970.0000    12
3       1750    750     128 12.0    1200.0000   14
4       1298    600     64  10.0    1050.0000   15
5       1752    750     128 10.0    1150.0000   14
6       1298    450     64  10.0    950.0000    12

The PC table:

code     model  speed   ram hd  cd  price
-------------------------------------------------------
1   1232    500 64  5.0 12x 600.0000
10  1260    500 32  10.0    12x 350.0000
11  1233    900 128 40.0    40x 980.0000
12  1233    800 128 20.0    50x 970.0000
2   1121    750 128 14.0    40x 850.0000
3   1233    500 64  5.0 12x 600.0000
4   1121    600 128 14.0    40x 850.0000
5   1121    600 128 8.0 40x 850.0000
6   1233    750 128 20.0    50x 950.0000
7   1232    500 32  10.0    12x 400.0000
8   1232    450 64  8.0 24x 350.0000
9   1232    450 32  10.0    24x 350.0000

Printer table:

code    model   color   type    price
-----------------------------------------
1   1276    n   Laser   400.0000
2   1433    y   Jet 270.0000
3   1434    y   Jet 290.0000
4   1401    n   Matrix  150.0000
5   1408    n   Matrix  270.0000
6   1288    n   Laser   400.0000

Table Product:

maker   model   Type
-----------------------
A       1232    PC
A       1233    PC
A       1276    Printer
A       1298    Laptop
A       1401    Printer
A       1408    Printer
A       1752    Laptop
B       1121    PC
B       1750    Laptop
C       1321    Laptop
D       1288    Printer
D       1433    Printer
E       1260    PC
E       1434    Printer
E       2112    PC
E       2113    PC


问:
Create React App - Unable to set window object before test runs
Trying to set up some tests for a component in a CRA-generated application.

Having an issue where the test is failing to run due to an imported file relying on a window object which isn't initialised.

Quick overview:
In public/index.html there is an object defined on the window called window.config.

```

<p>There is a file called <code>identity.constants.js</code> which exports an object that uses these window variables.</p>

<pre class="lang-js prettyprint-override"><code>export const IdentityConfig = {
    authority: window.config.IDENTITY_URL,
    client_id: window.config.OIDC_CLIENT_ID,
    ... etc
};
</code>```

The component I am trying to test imports another component that relies on identity.constants.js shown above.

The problem is that the test fails to start and throws an error stating window.config is undefined from the identity.constants.js file.

After reading the CRA docs, I have tried adding the following code into src/setupTests.js to set the config object before the test starts but it seems to fail before this code runs.

global.config = {
  ENV: "development",
  IDENTITY_URL: "identityurl.com",
  OIDC_CLIENT_ID: "i-am-a-clientId",
  ... etc
};
```

I'm looking for a way to set this window variable before the tests run (or a better way to structure the way I'm using window variables) so I can successfully run my tests.

答:
globa.config defines a global variable named config, you'll need to define global.window firstly, then add config as a property of global.window.
It seems your test environment is node, if you have jsdom as the devDependencies of your project, try to add below piece of code to your setupTests.js:

import { JSDOM } from 'jsdom';

const jsdom = new JSDOM('<!doctype html>');
global.window = jsdom.window;
global.document = jsdom.window.document;

global.window.config = {
  ENV: "development",
  IDENTITY_URL: "identityurl.com",
  OIDC_CLIENT_ID: "i-am-a-clientId",
  ... etc
};
```

<p>Without <code>jsdom</code>, a simple fix is like below:</p>

<pre class="lang-js prettyprint-override"><code>global.window = {
  config: {
    ENV: "development",
    IDENTITY_URL: "identityurl.com",
    OIDC_CLIENT_ID: "i-am-a-clientId",
    ... etc
  }
}
</code>```

Body:
Trying to set up some tests for a component in a CRA-generated application.

Having an issue where the test is failing to run due to an imported file relying on a window object which isn't initialised.

Quick overview:
In public/index.html there is an object defined on the window called window.config.

There is a file called identity.constants.js which exports an object that uses these window variables.

export const IdentityConfig = {
    authority: window.config.IDENTITY_URL,
    client_id: window.config.OIDC_CLIENT_ID,
    ... etc
};

The component I am trying to test imports another component that relies on identity.constants.js shown above.

The problem is that the test fails to start and throws an error stating window.config is undefined from the identity.constants.js file.

After reading the CRA docs, I have tried adding the following code into src/setupTests.js to set the config object before the test starts but it seems to fail before this code runs.

global.config = {
  ENV: "development",
  IDENTITY_URL: "identityurl.com",
  OIDC_CLIENT_ID: "i-am-a-clientId",
  ... etc
};

I'm looking for a way to set this window variable before the tests run (or a better way to structure the way I'm using window variables) so I can successfully run my tests.

Body:
globa.config defines a global variable named config, you'll need to define global.window firstly, then add config as a property of global.window.
It seems your test environment is node, if you have jsdom as the devDependencies of your project, try to add below piece of code to your setupTests.js:

import { JSDOM } from 'jsdom';

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
global.window = jsdom.window;
global.document = jsdom.window.document;

global.window.config = {
  ENV: "development",
  IDENTITY_URL: "identityurl.com",
  OIDC_CLIENT_ID: "i-am-a-clientId",
  ... etc
};

Without jsdom, a simple fix is like below:

global.window = {
  config: {
    ENV: "development",
    IDENTITY_URL: "identityurl.com",
    OIDC_CLIENT_ID: "i-am-a-clientId",
    ... etc
  }
}


问:
Why can't java find my method?
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?

What is the reason code such as the example below does not compile?

Thank you,

```<code>class a {
  public static void myMethod(Object myObj) {
    myObj.testing();
  }
}

class b {
  public void testing() {
    System.out.println ("TESTING!!!");
  }
}

class c {
  public static void main (String[] args) {
    b myB = new b();
    a.myMethod(myB);
  }
}
</code>```

Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.

答:
If you REALLY, REALLY want to keep the parameter as abstract as possible, you should consider reflection API. That way, you can pass whatever object you want and dynamically execute the method you want. You can take a look at some examples.

It's not the only way, but it might be a valid alternative depending on your problem.

Keep in mind that reflection is way slower than calling your methods directly. You might consider using an interface as well, such as the one on Amanda's post.

OwnerDisplayName: barfoon

ContentLicense: CC BY-SA 2.5

Title: Why can't java find my method?

Body:
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?

What is the reason code such as the example below does not compile?

Thank you,

class a {
  public static void myMethod(Object myObj) {
    myObj.testing();
  }
}

class b {
  public void testing() {
    System.out.println ("TESTING!!!");
  }
}

class c {
  public static void main (String[] args) {
    b myB = new b();
    a.myMethod(myB);
  }
}

Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.

LastEditorDisplayName: barfoon

OwnerDisplayName: Pablo Santa Cruz


问:
Allow Application Gateway Backend pool pointing at a specific VM
How do we add virtual machine as target in backend pool of an Application Gateway using terraform code ?

What property I should use in the following code to point at particular virtual Machine ?

```<code>    resource "azurerm_application_gateway" "network" {
  name                = "example-appgateway"
  resource_group_name = "${azurerm_resource_group.test.name}"
  location            = "${azurerm_resource_group.test.location}"

  sku {
    name     = "Standard_Small"
    tier     = "Standard"
    capacity = 2
  }

  gateway_ip_configuration {
    name      = "my-gateway-ip-configuration"
    subnet_id = "${azurerm_subnet.frontend.id}"
  }

  frontend_port {
    name = "${local.frontend_port_name}"
    port = 80
  }

  frontend_ip_configuration {
    name                 = "${local.frontend_ip_configuration_name}"
    public_ip_address_id = "${azurerm_public_ip.test.id}"
  }

  backend_address_pool {
    name = "${local.backend_address_pool_name}"
  }

  backend_http_settings {
    name                  = "${local.http_setting_name}"
    cookie_based_affinity = "Disabled"
    port                  = 80
    protocol              = "Http"
    request_timeout       = 1
  }

  http_listener {
    name                           = "${local.listener_name}"
    frontend_ip_configuration_name = "${local.frontend_ip_configuration_name}"
    frontend_port_name             = "${local.frontend_port_name}"
    protocol                       = "Http"
  }

  request_routing_rule {
    name                       = "${local.request_routing_rule_name}"
    rule_type                  = "Basic"
    http_listener_name         = "${local.listener_name}"
    backend_address_pool_name  = "${local.backend_address_pool_name}"
    backend_http_settings_name = "${local.http_setting_name}"
  }
}
</code>```

The backend_address_pool block supports:

name - (Required) User defined name for a backend address pool.

ip_addresses - (Optional) List of public IPAdresses, or internal IP
addresses in a backend address pool.

fqdns - (Optional) List of FQDNs in a backend address pool

答:
If someone will be looking at adding App Service to backend. This is following what you need to do:</p>

```<code>backend_address_pool {
  name = local.backend_address_pool_name
  fqdns = ["${azurerm_function_app.function_app.name}.azurewebsites.net"]
}
</code>```

Body:
How do we add virtual machine as target in backend pool of an Application Gateway using terraform code ?

What property I should use in the following code to point at particular virtual Machine ?

    resource "azurerm_application_gateway" "network" {
  name                = "example-appgateway"
  resource_group_name = "${azurerm_resource_group.test.name}"
  location            = "${azurerm_resource_group.test.location}"

  sku {
    name     = "Standard_Small"
    tier     = "Standard"
    capacity = 2
  }

  gateway_ip_configuration {
    name      = "my-gateway-ip-configuration"
    subnet_id = "${azurerm_subnet.frontend.id}"
  }

  frontend_port {
    name = "${local.frontend_port_name}"
    port = 80
  }

  frontend_ip_configuration {
    name                 = "${local.frontend_ip_configuration_name}"
    public_ip_address_id = "${azurerm_public_ip.test.id}"
  }

  backend_address_pool {
    name = "${local.backend_address_pool_name}"
  }

  backend_http_settings {
    name                  = "${local.http_setting_name}"
    cookie_based_affinity = "Disabled"
    port                  = 80
    protocol              = "Http"
    request_timeout       = 1
  }

  http_listener {
    name                           = "${local.listener_name}"
    frontend_ip_configuration_name = "${local.frontend_ip_configuration_name}"
    frontend_port_name             = "${local.frontend_port_name}"
    protocol                       = "Http"
  }

  request_routing_rule {
    name                       = "${local.request_routing_rule_name}"
    rule_type                  = "Basic"
    http_listener_name         = "${local.listener_name}"
    backend_address_pool_name  = "${local.backend_address_pool_name}"
    backend_http_settings_name = "${local.http_setting_name}"
  }
}

The backend_address_pool block supports:

name - (Required) User defined name for a backend address pool.

ip_addresses - (Optional) List of public IPAdresses, or internal IP
addresses in a backend address pool.

fqdns - (Optional) List of FQDNs in a backend address pool

Body:
If someone will be looking at adding App Service to backend. This is following what you need to do:

backend_address_pool {
  name = local.backend_address_pool_name
  fqdns = ["${azurerm_function_app.function_app.name}.azurewebsites.net"]
}


问:
HtmlWebResponseObject.ParsedHtml replacement in Powershell Core 6
My goal is to parse an html file retrieved with Invoke-WebRequest. If possible I'd like to avoid any external libraries.

The problem I am facing is, that Invoke-WebRequest returns a BasicHtmlWebResponseObject instead of a HtmlWebResponseObject since Powershell 6. The Basic version misses the ParsedHtml property. Is there a good alternative to parse html in Powershell Core 6?

I've tried to use Select-Xml but my html is not entirely valid (e.g. a missing closing tag), hence this fails to parse the result.

Another alternative I've found is to use New-Object -ComObject "HTMLFile" but from my understanding this relies on Internet Explorer for parsing which I'd like to avoid.

There is a very similar question here but sadly this question had no answer or activity since 8 months.

答:
As mentioned in the comments it is not really possible without a library. One very good library you could use it the AngleSharp library for dotnet. It has great html parsing capabilities and dotnet code interacts very friendly with powershell, have a look at this link.

Here is an example from their website:

```<code>var config = Configuration.Default.WithDefaultLoader();
var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(address);
var cellSelector = "tr.vevent td:nth-child(3)";
var cells = document.QuerySelectorAll(cellSelector);
var titles = cells.Select(m => m.TextContent);
</code>```

Body:
As mentioned in the comments it is not really possible without a library. One very good library you could use it the AngleSharp library for dotnet. It has great html parsing capabilities and dotnet code interacts very friendly with powershell, have a look at this link.

Here is an example from their website:

var config = Configuration.Default.WithDefaultLoader();
var address = "https://en.wikipedia.org/wiki/List_of_The_Big_Bang_Theory_episodes";
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(address);
var cellSelector = "tr.vevent td:nth-child(3)";
var cells = document.QuerySelectorAll(cellSelector);
var titles = cells.Select(m => m.TextContent);


问:
How to disable automatic line break when inserting two curly braces in vim?
Whenever I type two curly braces ({{), I get something like that:

```<code>{
|
}
</code>```

| is used to describe the position of the cursor.

This behaviour is totally annoying, e.g. when using different template engines which reserve this syntax for variables.

How can I find out where that behaviour comes from? And how do I shut it off?

Thanks

答:
If you use the same plugin as me, AutoClose, then you can type <leader>a (which is ,a for me, it depends on your <leader> key).

<leader>a toggles On or Off for autoclose.

Body:
Whenever I type two curly braces ({{), I get something like that:

{
|
}

| is used to describe the position of the cursor.

This behaviour is totally annoying, e.g. when using different template engines which reserve this syntax for variables.

How can I find out where that behaviour comes from? And how do I shut it off?

Thanks


问:
I got an error making a tile-based game. Could someone assist?
I'm making a tile based game and following a tutorial (Video Link) and I was trying to make inputting a map really easy, but i got an error saying "NameError: name 'path' is not defined" as you can see, i've imported 'path' from os, so it should work but it doesn't!

heres the code in reference:

```<code>import pygame as pg
import sys
from os import path
from settings import *
from sprites import *
from tilemap import *
class Game:
    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        pg.key.set_repeat(500, 100)
        self.load_data()

    def load_data(self):
        game_folder = path.dirname(__file__)
        self.map = Map(path.join(game_folder, 'map.txt'))

    def new(self):
        # initialize all variables and do all the setup for a new game
        self.all_sprites = pg.sprite.Group()
        self.walls = pg.sprite.Group()
        for row, tiles in enumerate(self.map.data):
            for col, tile in enumerate(tiles):
                if tile == '1':
                    Wall(self, col, row)
                if tile == 'P':
                    self.player = Player(self, col, row)

    def run(self):
        # game loop - set self.playing = False to end the game
        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()
        sys.exit()

    def update(self):
        # update portion of the game loop
        self.all_sprites.update()

    def draw_grid(self):
        for x in range(0, WIDTH, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (x, 0), (x, HEIGHT))
        for y in range(0, HEIGHT, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (0, y), (WIDTH, y))

    def draw(self):
        self.screen.fill(BGCOLOR)
        self.draw_grid()
        self.all_sprites.draw(self.screen)
        pg.display.flip()

    def events(self):
        # catch all events here
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass

# create the game object
g = Game()
g.show_start_screen()
while True:
    g.new()
    g.run()
    g.show_go_screen()
</code>```

(by the way this is python code)

答:
It looks like you haven't imported the path module from the os library correctly.

path is a module name, but you haven't imported it so the python interpreter doesn't know what this unknown variable is.

```<code>from os import path
</code>```

Body:
I'm making a tile based game and following a tutorial (Video Link) and I was trying to make inputting a map really easy, but i got an error saying "NameError: name 'path' is not defined" as you can see, i've imported 'path' from os, so it should work but it doesn't!

heres the code in reference:

import pygame as pg
import sys
from os import path
from settings import *
from sprites import *
from tilemap import *
class Game:
    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        pg.key.set_repeat(500, 100)
        self.load_data()

    def load_data(self):
        game_folder = path.dirname(__file__)
        self.map = Map(path.join(game_folder, 'map.txt'))

    def new(self):
        # initialize all variables and do all the setup for a new game
        self.all_sprites = pg.sprite.Group()
        self.walls = pg.sprite.Group()
        for row, tiles in enumerate(self.map.data):
            for col, tile in enumerate(tiles):
                if tile == '1':
                    Wall(self, col, row)
                if tile == 'P':
                    self.player = Player(self, col, row)

    def run(self):
        # game loop - set self.playing = False to end the game
        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()
        sys.exit()

    def update(self):
        # update portion of the game loop
        self.all_sprites.update()

    def draw_grid(self):
        for x in range(0, WIDTH, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (x, 0), (x, HEIGHT))
        for y in range(0, HEIGHT, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (0, y), (WIDTH, y))

    def draw(self):
        self.screen.fill(BGCOLOR)
        self.draw_grid()
        self.all_sprites.draw(self.screen)
        pg.display.flip()

    def events(self):
        # catch all events here
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass

# create the game object
g = Game()
g.show_start_screen()
while True:
    g.new()
    g.run()
    g.show_go_screen()

(by the way this is python code)

Body:
It looks like you haven't imported the path module from the os library correctly.

path is a module name, but you haven't imported it so the python interpreter doesn't know what this unknown variable is.

from os import path


问:
Javascript - .sort() does not have an affect on larger numbers
I am attempting to sort out an array that is being returned from least to greatest. I am attempting to achieve this by using the .sort() method. The sort method seems to be working exactly as expected when the numbers are less then a million, but has no affect when the numbers are larger then that.

I am expecting a sort array from least to greatest regardless of the number amount such as:

```<code>let topArr = [
            { sales: "28,883",  store: "Appointments" },
            { sales: "1,432,883", store: "Walk in" },
            { sales: "1,494,927", store: "Online" },
            { sales: "2,248,883",  store: "Retail Stores" },
        ];
</code>```

Here is an example of the sort method not working on larger numbers

let topArr = [
            { sales: "1,494,927", store: "Online" },
            { sales: "2,248,883",  store: "Retail Stores" },
            { sales: "1,432,883", store: "Walk in" },
            { sales: "28,883",  store: "Appointments" },
        ];

topArr.sort(function (a, b) {
        return parseInt(a.sales.replace("/,/g","")) - parseInt(b.sales.replace("/,/g",""));
 });

 console.log(topArr)```
</div>
</div>
</p>

<p>Here is an example of the sort method working as expected with smaller numbers: </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-js lang-js prettyprint-override"><code>let topArr = [
            { sales: "494,927", store: "Online" },
            { sales: "48,883",  store: "Retail Stores" },
            { sales: "432,883", store: "Walk in" },
            { sales: "28,883",  store: "Appointments" },
        ];

topArr.sort(function (a, b) {
        return parseInt(a.sales.replace("/,/g","")) - parseInt(b.sales.replace("/,/g",""));
 });

 console.log(topArr)</code>```

答:
You need regular expressions

```<code>/,/g
</code>```

not a string which looks like a regular expression.

let topArr = [
            { sales: "1,494,927", store: "Online" },
            { sales: "2,248,883",  store: "Retail Stores" },
            { sales: "1,432,883", store: "Walk in" },
            { sales: "28,883",  store: "Appointments" },
        ];

topArr.sort(function (a, b) {
        return a.sales.replace(/,/g,"") - b.sales.replace(/,/g,"");
 });

 console.log(topArr)```

Body:
I am attempting to sort out an array that is being returned from least to greatest. I am attempting to achieve this by using the .sort() method. The sort method seems to be working exactly as expected when the numbers are less then a million, but has no affect when the numbers are larger then that.

I am expecting a sort array from least to greatest regardless of the number amount such as:

let topArr = [
            { sales: "28,883",  store: "Appointments" },
            { sales: "1,432,883", store: "Walk in" },
            { sales: "1,494,927", store: "Online" },
            { sales: "2,248,883",  store: "Retail Stores" },
        ];

Here is an example of the sort method not working on larger numbers

let topArr = [
            { sales: "1,494,927", store: "Online" },
            { sales: "2,248,883",  store: "Retail Stores" },
            { sales: "1,432,883", store: "Walk in" },
            { sales: "28,883",  store: "Appointments" },
        ];

topArr.sort(function (a, b) {
        return parseInt(a.sales.replace("/,/g","")) - parseInt(b.sales.replace("/,/g",""));
 });

 console.log(topArr)

Here is an example of the sort method working as expected with smaller numbers:

let topArr = [
            { sales: "494,927", store: "Online" },
            { sales: "48,883",  store: "Retail Stores" },
            { sales: "432,883", store: "Walk in" },
            { sales: "28,883",  store: "Appointments" },
        ];

topArr.sort(function (a, b) {
        return parseInt(a.sales.replace("/,/g","")) - parseInt(b.sales.replace("/,/g",""));
 });

 console.log(topArr)

Body:
You need regular expressions

/,/g

not a string which looks like a regular expression.

let topArr = [
            { sales: "1,494,927", store: "Online" },
            { sales: "2,248,883",  store: "Retail Stores" },
            { sales: "1,432,883", store: "Walk in" },
            { sales: "28,883",  store: "Appointments" },
        ];

topArr.sort(function (a, b) {
        return a.sales.replace(/,/g,"") - b.sales.replace(/,/g,"");
 });

 console.log(topArr)


问:
Scala - how to use variables in a multi-line string literal
I want to call value of 'myActionID' variable. How do I do that?
If i pass static value like "actionId":1368201 to myActionID then it works, but If I use "actionId" : ${actionIdd} it gives error.

Here's the relevant code:

```<code>class LaunchWorkflow_Act extends Simulation {

    val scenarioRepeatCount = 1
    val userCount = 1
    val myActionID = "13682002351"

    val scn = scenario("LaunchMyFile")
        .repeat (scenarioRepeatCount) {
            exec(session => session.set("counter", (globalVar.getAndIncrement+" "+timeStamp.toString())))
            .exec(http("LaunchRequest")
            .post("""/api/test""")
            .headers(headers_0)
            .body(StringBody(
                """{    "actionId": ${myActionID} ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
                }""")))

            .pause(pause)

        }
    }

setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)
</code>```

Everything works fine If I put value 13682002351 instead of myActionID. While executing this script in Gatling I am Getting this error

ERROR i.g.http.action.HttpRequestAction - 'httpRequest-3' failed to
execute: No attribute named 'myActionID' is defined

答:
Using S interpolated String we can do this easily:

```<code> s"""Hello Word , Welcome Back!
      How are you doing ${userName}"""
</code>```

Body:
I want to call value of 'myActionID' variable. How do I do that?
If i pass static value like "actionId":1368201 to myActionID then it works, but If I use "actionId" : ${actionIdd} it gives error.

Here's the relevant code:

class LaunchWorkflow_Act extends Simulation {

    val scenarioRepeatCount = 1
    val userCount = 1
    val myActionID = "13682002351"

    val scn = scenario("LaunchMyFile")
        .repeat (scenarioRepeatCount) {
            exec(session => session.set("counter", (globalVar.getAndIncrement+" "+timeStamp.toString())))
            .exec(http("LaunchRequest")
            .post("""/api/test""")
            .headers(headers_0)
            .body(StringBody(
                """{    "actionId": ${myActionID} ,
                "jConfig": "{\"wflow\":[{\"Wflow\":{\"id\": \"13500145349\"},\"inherit-variables\": true,\"workflow-context-variable\": [{\"variable-name\": \"externalFilePath\",\"variable-value\": \"/var/nem/nem/media/mount/assets/Test.mp4\"},{\"variable-name\": \"Name\",\"variable-value\": \"${counter}\"}]}]}"
                }""")))

            .pause(pause)

        }
    }

setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)

Everything works fine If I put value 13682002351 instead of myActionID. While executing this script in Gatling I am Getting this error

ERROR i.g.http.action.HttpRequestAction - 'httpRequest-3' failed to
execute: No attribute named 'myActionID' is defined

Body:
Using S interpolated String we can do this easily:

 s"""Hello Word , Welcome Back!
      How are you doing ${userName}"""