问:
How to detect more then 5 duplicate character in an array
I'm using this code to detect duplicate characters and I want to make it detect if there are more then 5 duplicate characters and it's only detecting 1, so aaa is undetected but aaaaa or aaaaaaaaaa is detected so 5 or more duplicated characters

```<code>var str = 'abcdefg';

var re = /:\s|,\s/;
var ar = str.split(re);
console.log( ar );

function hasDuplicates(str)
{
    return new Set(str).size !== str.length;
}

if (hasDuplicates(str)) {
    console.log("Duplicate elements found.");
}
else {
    console.log("No Duplicates found.");
}
</code>```

output:

```<code>[ 'abcdefg' ]
No Duplicates found.
</code>```

```<code>[ 'hello' ]
Duplicate elements found.
</code>```

答:
You can use a regex with a backreference. It's as simple as /(.)\1{4,}/.test(str)

function hasDuplicates (str) {
  return /(.)\1{4,}/.test(str);
}

console.log(
  hasDuplicates('asdfg'),
  hasDuplicates('asdfgaaaaaa'),
  hasDuplicates('bbbbb')
)```
</div>
</div>
</p>

<p>Update:
If you want the number of repitions to be dynamic, you can create the regex dynamically using the <code>RegExp</code> constructor.</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>function hasDuplicates (str, n = 5) {
  return new RegExp(`(.)\\1{${n-1},}`).test(str)
}

console.log(
  hasDuplicates('asdfg'),
  hasDuplicates('asdfgaaaaaa'),
  hasDuplicates('bbbbb', 7)
)</code>```

Update2:
I just realized you're looking for a maximum repition. In order to do that you can use two regular expressions. One that checks for the minimum duplication count and the other one for the maximum.

function hasDuplicates(str, min = 5, max = 10) {
  return new RegExp(`(.)\\1{${min-1},}`).test(str) && !new RegExp(`(.)\\1{${max},}`).test(str)
}

console.log(
  hasDuplicates('asdfg'),
  hasDuplicates('asdfgaaaaaa'),
  hasDuplicates('bbbbb', 7),
  hasDuplicates('bbbbbbbbbb', 5, 10),
  hasDuplicates('bbbbbbbbbbb', 5, 10),
)```

Body:
I'm using this code to detect duplicate characters and I want to make it detect if there are more then 5 duplicate characters and it's only detecting 1, so aaa is undetected but aaaaa or aaaaaaaaaa is detected so 5 or more duplicated characters

var str = 'abcdefg';

var re = /:\s|,\s/;
var ar = str.split(re);
console.log( ar );

function hasDuplicates(str)
{
    return new Set(str).size !== str.length;
}

if (hasDuplicates(str)) {
    console.log("Duplicate elements found.");
}
else {
    console.log("No Duplicates found.");
}

output:

[ 'abcdefg' ]
No Duplicates found.

[ 'hello' ]
Duplicate elements found.

Body:
You can use a regex with a backreference. It's as simple as /(.)\1{4,}/.test(str)

function hasDuplicates (str) {
  return /(.)\1{4,}/.test(str);
}

console.log(
  hasDuplicates('asdfg'),
  hasDuplicates('asdfgaaaaaa'),
  hasDuplicates('bbbbb')
)

Update:
If you want the number of repitions to be dynamic, you can create the regex dynamically using the RegExp constructor.

function hasDuplicates (str, n = 5) {
  return new RegExp(`(.)\\1{${n-1},}`).test(str)
}

console.log(
  hasDuplicates('asdfg'),
  hasDuplicates('asdfgaaaaaa'),
  hasDuplicates('bbbbb', 7)
)

Update2:
I just realized you're looking for a maximum repition. In order to do that you can use two regular expressions. One that checks for the minimum duplication count and the other one for the maximum.

function hasDuplicates(str, min = 5, max = 10) {
  return new RegExp(`(.)\\1{${min-1},}`).test(str) && !new RegExp(`(.)\\1{${max},}`).test(str)
}

console.log(
  hasDuplicates('asdfg'),
  hasDuplicates('asdfgaaaaaa'),
  hasDuplicates('bbbbb', 7),
  hasDuplicates('bbbbbbbbbb', 5, 10),
  hasDuplicates('bbbbbbbbbbb', 5, 10),
)


来源: stackexchange

问:
slide toogle element, which was clicked
I have this simple html code:

```<code><ul>
   <li>
      <button onclick="test()">Button</button>
   </li>
   <li>
      <button onclick="test()">Button</button>
   </li>
   <li>
      <button onclick="test()">Button</button>
   </li>
</ul>
</code>```

and my javascript function:

```<code>function test() {
    // do something
}
</code>```

Now, if I clicked on a button I would like to remove the whole
 element of the button, which was clicked. Can you show me how? :/

With "remove" I mean

```<code>$(selector).toggle( "slide" );
</code>```

答:
First, avoid inline handlers - they're inelegant, tedious to work with, and have way too many problems to be worth using nowadays. Attach event listeners properly using Javascript with addEventListener or jQuery instead.

Iterate over all the buttons and add a listener to each. When clicked, navigate to the button's parent and call .toggle('slide') on it:

$('button').on('click', function() {
  $(this).parent().toggle( "slide" );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
   <li>
      <button>Button</button>
   </li>
   <li>
      <button>Button</button>
   </li>
   <li>
      <button>Button</button>
   </li>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Title: slide toogle element, which was clicked

Body:
I have this simple html code:

      <button onclick="test()">Button</button>

      <button onclick="test()">Button</button>

      <button onclick="test()">Button</button>

and my javascript function:

function test() {
    // do something
}

Now, if I clicked on a button I would like to remove the whole
 element of the button, which was clicked. Can you show me how? :/

With "remove" I mean

$(selector).toggle( "slide" );

Body:
First, avoid inline handlers - they're inelegant, tedious to work with, and have way too many problems to be worth using nowadays. Attach event listeners properly using Javascript with addEventListener or jQuery instead.

Iterate over all the buttons and add a listener to each. When clicked, navigate to the button's parent and call .toggle('slide') on it:

$('button').on('click', function() {
  $(this).parent().toggle( "slide" );
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
   <li>
      <button>Button</button>
   </li>
   <li>
      <button>Button</button>
   </li>
   <li>
      <button>Button</button>
   </li>
</ul>


问:
Apache Drill JDBC Java Client Exception
I am new to Apache Drill and got it setup fine to run locally in embedded mode and via Web interface. However, am facing the following issue when trying to access via Java client using JDBC.

Following drill docs and a few posts here, my setup is like:

```<code><dependency>
    <groupId>org.apache.drill.exec</groupId>
    <artifactId>drill-jdbc</artifactId>
    <version>1.7.0</version>
</dependency>
</code>```

code:

```<code>public static void main(String[] args) {
  Class.forName("org.apache.drill.jdbc.Driver");
  **Connection connection = DriverManager.getConnection("jdbc:drill:zk=local");**
  Statement st = connection.createStatement();
  ResultSet rs = st.executeQuery("SELECT * from cp.`employee` LIMIT 10");
  while (rs.next()) {
    System.out.println(rs.getString(1));
  }
...
</code>```

There are no compile issues however, on running the above, I get the following OutOfMemoryException on the highlighted section of above code:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/drill/exec/exception/OutOfMemoryException
 at org.apache.drill.jdbc.impl.DrillJdbc41Factory.newDrillConnection(DrillJdbc41Factory.java:64)
 at org.apache.drill.jdbc.impl.DrillFactory.newConnection(DrillFactory.java:69)
 at net.hydromatic.avatica.UnregisteredDriver.connect(UnregisteredDriver.java:126)
 at org.apache.drill.jdbc.Driver.connect(Driver.java:72)
 at java.sql.DriverManager.getConnection(DriverManager.java:664)
 at java.sql.DriverManager.getConnection(DriverManager.java:270)
 at com.mapr.drill.DrillJDBCExample.runMode1(DrillJDBCExample.java:49)
 at com.mapr.drill.DrillJDBCExample.main(DrillJDBCExample.java:21)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:497)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.ClassNotFoundException: org.apache.drill.exec.exception.OutOfMemoryException
 at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 ... 13 more
</code>```

I did this with drill running locally. Also tried with changing jdbc url to "jdbc:drill:drillbit=localhost";

Please help.

答:
Use  drill-jdbc-all instead of drill-jdbc. Below is an example</p>

```<code><dependency>
        <groupId>org.apache.drill.exec</groupId>
        <artifactId>drill-jdbc-all</artifactId>
        <version>1.15.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Apache Drill JDBC Java Client Exception

Body:
I am new to Apache Drill and got it setup fine to run locally in embedded mode and via Web interface. However, am facing the following issue when trying to access via Java client using JDBC.

Following drill docs and a few posts here, my setup is like:

<dependency>
    <groupId>org.apache.drill.exec</groupId>
    <artifactId>drill-jdbc</artifactId>
    <version>1.7.0</version>
</dependency>

code:

public static void main(String[] args) {
  Class.forName("org.apache.drill.jdbc.Driver");
  **Connection connection = DriverManager.getConnection("jdbc:drill:zk=local");**
  Statement st = connection.createStatement();
  ResultSet rs = st.executeQuery("SELECT * from cp.`employee` LIMIT 10");
  while (rs.next()) {
    System.out.println(rs.getString(1));
  }
...

There are no compile issues however, on running the above, I get the following OutOfMemoryException on the highlighted section of above code:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/drill/exec/exception/OutOfMemoryException
 at org.apache.drill.jdbc.impl.DrillJdbc41Factory.newDrillConnection(DrillJdbc41Factory.java:64)
 at org.apache.drill.jdbc.impl.DrillFactory.newConnection(DrillFactory.java:69)
 at net.hydromatic.avatica.UnregisteredDriver.connect(UnregisteredDriver.java:126)
 at org.apache.drill.jdbc.Driver.connect(Driver.java:72)
 at java.sql.DriverManager.getConnection(DriverManager.java:664)
 at java.sql.DriverManager.getConnection(DriverManager.java:270)
 at com.mapr.drill.DrillJDBCExample.runMode1(DrillJDBCExample.java:49)
 at com.mapr.drill.DrillJDBCExample.main(DrillJDBCExample.java:21)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:497)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.ClassNotFoundException: org.apache.drill.exec.exception.OutOfMemoryException
 at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 ... 13 more

I did this with drill running locally. Also tried with changing jdbc url to "jdbc:drill:drillbit=localhost";

Please help.

Body:
Use  drill-jdbc-all instead of drill-jdbc. Below is an example

<dependency>
        <groupId>org.apache.drill.exec</groupId>
        <artifactId>drill-jdbc-all</artifactId>
        <version>1.15.0</version>
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>


问:
Rails 3 - default_scope
I would like to order the article tags on my index page by popularity as opposed to by creation date i.e. the tags with the most amount of articles in them from highest to lowest. My model is as follows?</p>

```<code>class Tag < ActiveRecord::Base

  attr_accessible :name
  validates :name, :uniqueness => true

  # order by creation
  default_scope :order => 'created_at DESC'

  has_many :taggings, :dependent => :destroy
  has_many :articles, :through => :taggings
  end
</code>```

答:
I recommend using a counter cache column to store a taggings_count (which automatically gets updated when new taggings).

And then your default scope can look like this:

```<code>default_scope :order => 'taggings_count DESC'
</code>```

For more info, search for "counter_cache" in the Rails guide for AR associations

Title: Rails 3 - default_scope

Body:
I would like to order the article tags on my index page by popularity as opposed to by creation date i.e. the tags with the most amount of articles in them from highest to lowest. My model is as follows?

class Tag < ActiveRecord::Base

  attr_accessible :name
  validates :name, :uniqueness => true

  # order by creation
  default_scope :order => 'created_at DESC'

  has_many :taggings, :dependent => :destroy
  has_many :articles, :through => :taggings
  end

Body:
I recommend using a counter cache column to store a taggings_count (which automatically gets updated when new taggings).

And then your default scope can look like this:

default_scope :order => 'taggings_count DESC'

For more info, search for "counter_cache" in the Rails guide for AR associations


问:
How to test if an Enum member with a certain name exists?
Using Python 3.4 I want to test whether an Enum class contains a member with a certain name.

Example:

```<code>class Constants(Enum):
    One = 1
    Two = 2
    Three = 3

print(Constants['One'])
print(Constants['Four'])
</code>```

gives:

```<code>Constants.One
  File "C:\Python34\lib\enum.py", line 258, in __getitem__
    return cls._member_map_[name]
KeyError: 'Four'
</code>```

I could catch the KeyError and take the exception as indication of existence but maybe there is a more elegant way?

答:
In order to improve legibility, you can put these suggestions above as class method.
For instance:

class Constants(Enum):
    One = 1
    Two = 2
    Three = 3

    @classmethod
    def has_key(cls, name):
        return name in cls.__members__ # solution above 1
        # return any(x for x in cls if x.name == name) # or solution above 2
```
<p>In order to use:</p>
```In [6]: Constants.has_key('One')
Out[6]: True

In [7]: Constants.has_key('Four')
Out[7]: False
```

Body:
Using Python 3.4 I want to test whether an Enum class contains a member with a certain name.

Example:

class Constants(Enum):
    One = 1
    Two = 2
    Three = 3

print(Constants['One'])
print(Constants['Four'])

gives:

Constants.One
  File "C:\Python34\lib\enum.py", line 258, in __getitem__
    return cls._member_map_[name]
KeyError: 'Four'

I could catch the KeyError and take the exception as indication of existence but maybe there is a more elegant way?

Body:
In order to improve legibility, you can put these suggestions above as class method.
For instance:

class Constants(Enum):
    One = 1
    Two = 2
    Three = 3

    @classmethod
    def has_key(cls, name):
        return name in cls.__members__ # solution above 1
        # return any(x for x in cls if x.name == name) # or solution above 2

In order to use:

In [6]: Constants.has_key('One')
Out[6]: True

In [7]: Constants.has_key('Four')
Out[7]: False


问:
Getting OpenGL ES Transform Feedback data back to the host using Emscripten
Using GLFW, the C++ OpenGL ES code below calculates the square roots of five numbers and outputs them on the command line. The code makes use of Transform Feedback. When I compile on Ubuntu 17.10, using the following command, I get the result I expect:

```<code>$ g++ tf.cpp -lGL -lglfw
</code>```

If I use Emscripten, however, an exception is thrown, which indicates that
glMapBufferRange is only supported when access is MAP_WRITE|INVALIDATE_BUFFER. I do want to read rather than write, so perhaps I shouldn't use glMapBufferRange, but what can I use instead? I have tried on both Firefox and Chromium. The command I use to compile with Emscripten is:

```<code>$ em++ -std=c++11 tf.cpp -s USE_GLFW=3 -s USE_WEBGL2=1 -s FULL_ES3=1 -o a.out.html
</code>```

The code follows:

```<code>#include <iostream>

#define GLFW_INCLUDE_ES3
#include <GLFW/glfw3.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

static const GLuint WIDTH  = 800;
static const GLuint HEIGHT = 600;
static const GLchar *vertex_shader_src =
"#version 300 es\n"
"precision mediump float;\n"
"in  float inValue;\n"
"out float outValue;\n"
"void main() {\n"
"  outValue = sqrt(inValue);\n"
"}\n";

// Emscripten complains if there's no fragment shader
static const GLchar *fragment_shader_src =
"#version 300 es\n"
"precision mediump float;\n"
"out vec4 colour;\n"
"void main() {\n"
"  colour = vec4(1.0, 1.0, 0.0, 1.0);\n"
"}\n";

static const GLfloat vertices[] = {
   0.0f,  0.5f, 0.0f,
   0.5f, -0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f,
};

GLint get_shader_prog(const char *vert_src, const char *frag_src = "")
{
  enum Consts { INFOLOG_LEN = 512 };
  GLchar infoLog[INFOLOG_LEN];
  GLint fragment_shader, vertex_shader, shader_program, success;
  shader_program = glCreateProgram();

  auto mk_shader = [&](GLint &shader, const GLchar **str, GLenum shader_type) {
    shader = glCreateShader(shader_type);
    glShaderSource(shader, 1, str, NULL);
    glCompileShader(shader);
    glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
    if (!success) {
      glGetShaderInfoLog(shader, INFOLOG_LEN, NULL, infoLog);
      std::cout << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << '\n';
    }
    glAttachShader(shader_program, shader);
  };

  mk_shader(vertex_shader,   &vert_src, GL_VERTEX_SHADER);
  mk_shader(fragment_shader, &frag_src, GL_FRAGMENT_SHADER);

  const GLchar* feedbackVaryings[] = { "outValue" };
  glTransformFeedbackVaryings(shader_program, 1, feedbackVaryings,
                              GL_INTERLEAVED_ATTRIBS);

  glLinkProgram(shader_program);
  glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
  if (!success) {
    glGetProgramInfoLog(shader_program, INFOLOG_LEN, NULL, infoLog);
    std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << '\n';
  }
  glUseProgram(shader_program);

  glDeleteShader(vertex_shader);
  glDeleteShader(fragment_shader);
  return shader_program;
}

int main(int argc, char *argv[])
{
  glfwInit();
  glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
  glfwMakeContextCurrent(window);

  GLuint shader_prog = get_shader_prog(vertex_shader_src, fragment_shader_src);
  GLint inputAttrib = glGetAttribLocation(shader_prog, "inValue");

  glViewport(0, 0, WIDTH, HEIGHT);

  GLuint vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  GLfloat data[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);

  glVertexAttribPointer(inputAttrib, 1, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(inputAttrib);

  GLuint tbo;
  glGenBuffers(1, &tbo);
  glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, tbo);
  glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, sizeof(data),
               nullptr, GL_STATIC_READ);
  glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo);
  glEnable(GL_RASTERIZER_DISCARD);

  glBeginTransformFeedback(GL_POINTS);
  glDrawArrays(GL_POINTS, 0, 5);
  glEndTransformFeedback();

  glDisable(GL_RASTERIZER_DISCARD);
  glFlush();

  GLfloat feedback[5]{1,2,3,4,5};
  void *void_buf = glMapBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER,0,
                                    sizeof(feedback), GL_MAP_READ_BIT);
  GLfloat *buf = static_cast<GLfloat *>(void_buf);
  for (int i = 0; i < 5; i++)
    feedback[i] = buf[i];
  glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER);

  for (int i = 0; i < 5; i++)
    std::cout << feedback[i] << ' ';
  std::cout << std::endl;

  glDeleteBuffers(1, &vbo);
  glDeleteBuffers(1, &tbo);
  glDeleteVertexArrays(1, &vao);
  glfwTerminate();

  return 0;
}
</code>```

答:
As has been mentioned by another answer, WebGL 2.0 is close to OpenGL ES 3.0, but confusingly does not define glMapBufferRange() function, so that Emscripten tries emulating only part of functionality of this function.

Real WebGL 2.0, however, exposes glGetBufferSubData() analog, which does not exist in OpenGL ES, but exist in desktop OpenGL. The method can be wrapped in code via EM_ASM_:

void myGetBufferSubData (GLenum theTarget, GLintptr theOffset, GLsizeiptr theSize, void* theData)
{
#ifdef __EMSCRIPTEN__
  EM_ASM_(
  {
    Module.ctx.getBufferSubData($0, $1, HEAPU8.subarray($2, $2 + $3));
  }, theTarget, theOffset, theData, theSize);
#else
  glGetBufferSubData (theTarget, theOffset, theSize, theData);
#endif
}
```

Fetching VBO data back is troublesome in multi-platform code:

OpenGL 1.5+

glGetBufferSubData(): YES

glMapBufferRange(): YES

OpenGL ES 2.0

glGetBufferSubData(): NO

glMapBufferRange(): NO

OpenGL ES 3.0+

glGetBufferSubData(): NO

glMapBufferRange(): YES

WebGL 1.0

glGetBufferSubData(): NO

glMapBufferRange(): NO

WebGL 2.0

glGetBufferSubData(): YES

glMapBufferRange(): NO

So that:

Desktop OpenGL gives maximum flexibility.

OpenGL ES 2.0 and WebGL 1.0 give no chance to retrieve data back.

OpenGL ES 3.0+ gives only mapping buffer.

WebGL 2.0 gives only getBufferSubData().

Body:
Using GLFW, the C++ OpenGL ES code below calculates the square roots of five numbers and outputs them on the command line. The code makes use of Transform Feedback. When I compile on Ubuntu 17.10, using the following command, I get the result I expect:

$ g++ tf.cpp -lGL -lglfw

If I use Emscripten, however, an exception is thrown, which indicates that
glMapBufferRange is only supported when access is MAP_WRITE|INVALIDATE_BUFFER. I do want to read rather than write, so perhaps I shouldn't use glMapBufferRange, but what can I use instead? I have tried on both Firefox and Chromium. The command I use to compile with Emscripten is:

$ em++ -std=c++11 tf.cpp -s USE_GLFW=3 -s USE_WEBGL2=1 -s FULL_ES3=1 -o a.out.html

The code follows:

#include <iostream>

#define GLFW_INCLUDE_ES3
#include <GLFW/glfw3.h>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

static const GLuint WIDTH  = 800;
static const GLuint HEIGHT = 600;
static const GLchar *vertex_shader_src =
"#version 300 es\n"
"precision mediump float;\n"
"in  float inValue;\n"
"out float outValue;\n"
"void main() {\n"
"  outValue = sqrt(inValue);\n"
"}\n";

// Emscripten complains if there's no fragment shader
static const GLchar *fragment_shader_src =
"#version 300 es\n"
"precision mediump float;\n"
"out vec4 colour;\n"
"void main() {\n"
"  colour = vec4(1.0, 1.0, 0.0, 1.0);\n"
"}\n";

static const GLfloat vertices[] = {
   0.0f,  0.5f, 0.0f,
   0.5f, -0.5f, 0.0f,
  -0.5f, -0.5f, 0.0f,
};

GLint get_shader_prog(const char *vert_src, const char *frag_src = "")
{
  enum Consts { INFOLOG_LEN = 512 };
  GLchar infoLog[INFOLOG_LEN];
  GLint fragment_shader, vertex_shader, shader_program, success;
  shader_program = glCreateProgram();

  auto mk_shader = [&](GLint &shader, const GLchar **str, GLenum shader_type) {
    shader = glCreateShader(shader_type);
    glShaderSource(shader, 1, str, NULL);
    glCompileShader(shader);
    glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
    if (!success) {
      glGetShaderInfoLog(shader, INFOLOG_LEN, NULL, infoLog);
      std::cout << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << '\n';
    }
    glAttachShader(shader_program, shader);
  };

  mk_shader(vertex_shader,   &vert_src, GL_VERTEX_SHADER);
  mk_shader(fragment_shader, &frag_src, GL_FRAGMENT_SHADER);

  const GLchar* feedbackVaryings[] = { "outValue" };
  glTransformFeedbackVaryings(shader_program, 1, feedbackVaryings,
                              GL_INTERLEAVED_ATTRIBS);

  glLinkProgram(shader_program);
  glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
  if (!success) {
    glGetProgramInfoLog(shader_program, INFOLOG_LEN, NULL, infoLog);
    std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << '\n';
  }
  glUseProgram(shader_program);

  glDeleteShader(vertex_shader);
  glDeleteShader(fragment_shader);
  return shader_program;
}

int main(int argc, char *argv[])
{
  glfwInit();
  glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
  glfwMakeContextCurrent(window);

  GLuint shader_prog = get_shader_prog(vertex_shader_src, fragment_shader_src);
  GLint inputAttrib = glGetAttribLocation(shader_prog, "inValue");

  glViewport(0, 0, WIDTH, HEIGHT);

  GLuint vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  GLfloat data[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);

  glVertexAttribPointer(inputAttrib, 1, GL_FLOAT, GL_FALSE, 0, 0);
  glEnableVertexAttribArray(inputAttrib);

  GLuint tbo;
  glGenBuffers(1, &tbo);
  glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, tbo);
  glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, sizeof(data),
               nullptr, GL_STATIC_READ);
  glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo);
  glEnable(GL_RASTERIZER_DISCARD);

  glBeginTransformFeedback(GL_POINTS);
  glDrawArrays(GL_POINTS, 0, 5);
  glEndTransformFeedback();

  glDisable(GL_RASTERIZER_DISCARD);
  glFlush();

  GLfloat feedback[5]{1,2,3,4,5};
  void *void_buf = glMapBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER,0,
                                    sizeof(feedback), GL_MAP_READ_BIT);
  GLfloat *buf = static_cast<GLfloat *>(void_buf);
  for (int i = 0; i < 5; i++)
    feedback[i] = buf[i];
  glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER);

  for (int i = 0; i < 5; i++)
    std::cout << feedback[i] << ' ';
  std::cout << std::endl;

  glDeleteBuffers(1, &vbo);
  glDeleteBuffers(1, &tbo);
  glDeleteVertexArrays(1, &vao);
  glfwTerminate();

  return 0;
}

Body:
As has been mentioned by another answer, WebGL 2.0 is close to OpenGL ES 3.0, but confusingly does not define glMapBufferRange() function, so that Emscripten tries emulating only part of functionality of this function.

Real WebGL 2.0, however, exposes glGetBufferSubData() analog, which does not exist in OpenGL ES, but exist in desktop OpenGL. The method can be wrapped in code via EM_ASM_:

void myGetBufferSubData (GLenum theTarget, GLintptr theOffset, GLsizeiptr theSize, void* theData)
{
#ifdef __EMSCRIPTEN__
  EM_ASM_(
  {
    Module.ctx.getBufferSubData($0, $1, HEAPU8.subarray($2, $2 + $3));
  }, theTarget, theOffset, theData, theSize);
#else
  glGetBufferSubData (theTarget, theOffset, theSize, theData);
#endif
}

Fetching VBO data back is troublesome in multi-platform code:

OpenGL 1.5+

glGetBufferSubData(): YES

glMapBufferRange(): YES

OpenGL ES 2.0

glGetBufferSubData(): NO

glMapBufferRange(): NO

OpenGL ES 3.0+

glGetBufferSubData(): NO

glMapBufferRange(): YES

WebGL 1.0

glGetBufferSubData(): NO

glMapBufferRange(): NO

WebGL 2.0

glGetBufferSubData(): YES

glMapBufferRange(): NO

So that:

Desktop OpenGL gives maximum flexibility.

OpenGL ES 2.0 and WebGL 1.0 give no chance to retrieve data back.

OpenGL ES 3.0+ gives only mapping buffer.

WebGL 2.0 gives only getBufferSubData().


问:
passing select query from stored procedure into a ArrayList in C#?
I have a stored procedure that select data and it gives me 8 rows and 4 columns of data. I wanted to know how will i be able to pass these data to an array list in c#?

I am using MS SQL.

答:
I suggeste you to create a class, for example, you are using table Student, this student has (id, name, age, phone : 4 columns), create a Student class with 4 properties, and at the moment of receiving data from DB, using a loop, create instance from student class and save in it a single row of data, and add it to the arrayList.
or use anonymous type in c# instead of student class</p>


问:
If is not executed unless System.out.println is used or while debugging
We are developing a Simulator with Students with Java and Swing. The Problem we have is that after a Button Click in the Simulator.java the variable for private static boolean startButton change too true. After this the "if" should start doing their job, but that is not the case.

I have this Code Block in my Brain.java:

```<code>
public class Brain
{
    // ==========================================================

    /*
     * This is the Part of Port A
     */
    // Tris for Port A | ARRAY VALUE 0
    private static boolean[] port_A_Tris_Checkboxes = new boolean[8];

    // PINs | ARRAY VALUE 1
    private static boolean[] port_A_Pins_Checkboxes = new boolean[5];

    /*
     * This is the Part of Port B
     */
    // Tris for Port B | ARRAY VALUE 2
    private static boolean[] port_B_Tris_Checkboxes = new boolean[8];

    // PINs | ARRAY VALUE 3
    private static boolean[] port_B_Pins_Checkboxes = new boolean[8];

    // ==========================================================

    /*
     * This is the Part of the Watchdog
     */
    private static boolean watchdogCheckbox;

    // ==========================================================

    /*
     * This is the Part of the Reset Button
     */
    private static boolean resetButton;

    // ==========================================================

    /*
     * This is the Part of the Einzelschritt Button
     */
    private static boolean einzelschrittButton;

    // ==========================================================

    /*
     * This is the Part of the Start Button
     */
    private static boolean startButton = false;

    // ==========================================================

    /*
     * This is the Part of the Stop Button
     */
    private static boolean stopButton = false;

    // ==========================================================

    public static void main(String[] args)
    {
        // startet das GUI
        Simulator.main(args);
        while (true) {

            if ((startButton == true) && (stopButton == false)) {

                // Do one step of the program
                Steuerwerk.runCommand(Decoder.decode(Simulator.getProgramMemory()
                        .getProgramMemory()[ProgramCounter.getProgramCounter()]),
                        Simulator.getProgramMemory().getProgramMemory()[ProgramCounter
                                .getProgramCounter()]);
                System.out.println(W_Register.getArgument());

            } else if (getStart() && getStop()) {

                /*
                 * If program has already started and the stop button was pressed,
                 * stop the program
                 */
                setStart(false);
                setStop(false);

            } else if (getStop()) {

                // No reason to save stopping of program if it didn't even start yet
                setStop(false);

            } else if (getEinzelschritt()) {

                // Do one step of the program
                Steuerwerk.runCommand(Decoder.decode(Simulator.getProgramMemory()
                        .getProgramMemory()[ProgramCounter.getProgramCounter()]),
                        Simulator.getProgramMemory().getProgramMemory()[ProgramCounter
                                .getProgramCounter()]);
                System.out.println(W_Register.getArgument());
                setEinzelschritt(false);
            }
        }

    }

    // ==========================================================

    /**
     *
     * @param index : Checkbox value, true if checkbox has been marked
     * @param whichArray : Value that say which ArrayIndex is checked in which
     *        Array
     *
     *        Diese Methode wird die in der GUI aktivierten Checkboxen hier in
     *        der Programm Logik vermerken sodass diese dann für die weitere
     *        Abarbeitung nach User wunsch geschehen und mit berüchsichtigung der
     *        aktivierten Checkboxen des Users
     */
    public static void setChechboxesForTrisOrPinBoolean(int index,
            int whichArray)
    {
        switch (whichArray) {
        case 0: {
            port_A_Tris_Checkboxes[index] = !port_A_Tris_Checkboxes[index];
            break;
        }
        case 1: {
            port_A_Pins_Checkboxes[index] = !port_A_Pins_Checkboxes[index];
            break;
        }
        case 2: {
            port_B_Tris_Checkboxes[index] = !port_B_Tris_Checkboxes[index];
            break;
        }
        case 3: {
            port_B_Pins_Checkboxes[index] = !port_B_Pins_Checkboxes[index];
            break;
        }
        default:
            throw new IllegalArgumentException("Unexpected value: " + whichArray);
        }
    }

    // ==========================================================

    /**
     * Diese methode wird die Aktivierung der Watchog Checkbox berücksichtigen
     * und eben dann auch vermerken
     */
    public static void setCheckboxForWatchdog()
    {
        watchdogCheckbox = !watchdogCheckbox;
    }

    // ==========================================================

    /*
     * The Set Method for the Reset Button
     */
    public static void setReset(boolean value)
    {
        if (value == true) {
            resetButton = true;
        } else {
            resetButton = false;
        }
    }

    /*
     * Get Method for the Reset Button Value
     */
    public static boolean getReset()
    {
        return resetButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Einzelschritt Button
     */
    public static void setEinzelschritt(boolean value)
    {
        if (value == true) {
            einzelschrittButton = true;
        } else {
            einzelschrittButton = false;
        }
    }

    /*
     * Get Method for the Einzelschritt Button Value
     */
    public static boolean getEinzelschritt()
    {
        return einzelschrittButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Start Button
     */
    public static void setStart(boolean value)
    {
        if (value == true) {
            startButton = true;
        } else {
            startButton = false;
        }
    }

    /*
     * Get Method for the Start Button Value
     */
    public static boolean getStart()
    {
        return startButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Stop Button
     */
    public static void setStop(boolean value)
    {
        if (value == true) {
            stopButton = true;
        } else {
            stopButton = false;
        }
    }

    /*
     * Get Method for the Stop Button Value
     */
    public static boolean getStop()
    {
        return stopButton;
    }

    // ==========================================================
}

</code>```

the other Part is my Simulator:

```<code>JButton btnStart = new JButton("START");
        btnStart.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                // TODO Auto-generated method stub
                System.out.println("Pressed");
                Brain.setStart(true);
            }
        });
</code>```

The funny thing is that only if we add a System.out.println() or we Debug... it starts the if.

答:
If you modify variables concurrently in multiple threads then they need to be volatile unless you use some other process of synchronization to ensure read barriers exist.

Most Swing code will run on the Event Dispatch Thread which is distinct from the main thread (which the non-Swing part of your code seems to be runnning on).

System.out.println will execute code that uses synchronized and as such probably works as an effective read barrier here.

Similarly using a Debugger will undo many of the optimizations that volatile also disables so it could have the same effect.

Change your private static boolean to private static volatile boolean.

Body:
We are developing a Simulator with Students with Java and Swing. The Problem we have is that after a Button Click in the Simulator.java the variable for private static boolean startButton change too true. After this the "if" should start doing their job, but that is not the case.

I have this Code Block in my Brain.java:

public class Brain
{
    // ==========================================================

    /*
     * This is the Part of Port A
     */
    // Tris for Port A | ARRAY VALUE 0
    private static boolean[] port_A_Tris_Checkboxes = new boolean[8];

    // PINs | ARRAY VALUE 1
    private static boolean[] port_A_Pins_Checkboxes = new boolean[5];

    /*
     * This is the Part of Port B
     */
    // Tris for Port B | ARRAY VALUE 2
    private static boolean[] port_B_Tris_Checkboxes = new boolean[8];

    // PINs | ARRAY VALUE 3
    private static boolean[] port_B_Pins_Checkboxes = new boolean[8];

    // ==========================================================

    /*
     * This is the Part of the Watchdog
     */
    private static boolean watchdogCheckbox;

    // ==========================================================

    /*
     * This is the Part of the Reset Button
     */
    private static boolean resetButton;

    // ==========================================================

    /*
     * This is the Part of the Einzelschritt Button
     */
    private static boolean einzelschrittButton;

    // ==========================================================

    /*
     * This is the Part of the Start Button
     */
    private static boolean startButton = false;

    // ==========================================================

    /*
     * This is the Part of the Stop Button
     */
    private static boolean stopButton = false;

    // ==========================================================

    public static void main(String[] args)
    {
        // startet das GUI
        Simulator.main(args);
        while (true) {

            if ((startButton == true) && (stopButton == false)) {

                // Do one step of the program
                Steuerwerk.runCommand(Decoder.decode(Simulator.getProgramMemory()
                        .getProgramMemory()[ProgramCounter.getProgramCounter()]),
                        Simulator.getProgramMemory().getProgramMemory()[ProgramCounter
                                .getProgramCounter()]);
                System.out.println(W_Register.getArgument());

            } else if (getStart() && getStop()) {

                /*
                 * If program has already started and the stop button was pressed,
                 * stop the program
                 */
                setStart(false);
                setStop(false);

            } else if (getStop()) {

                // No reason to save stopping of program if it didn't even start yet
                setStop(false);

            } else if (getEinzelschritt()) {

                // Do one step of the program
                Steuerwerk.runCommand(Decoder.decode(Simulator.getProgramMemory()
                        .getProgramMemory()[ProgramCounter.getProgramCounter()]),
                        Simulator.getProgramMemory().getProgramMemory()[ProgramCounter
                                .getProgramCounter()]);
                System.out.println(W_Register.getArgument());
                setEinzelschritt(false);
            }
        }

    }

    // ==========================================================

    /**
     *
     * @param index : Checkbox value, true if checkbox has been marked
     * @param whichArray : Value that say which ArrayIndex is checked in which
     *        Array
     *
     *        Diese Methode wird die in der GUI aktivierten Checkboxen hier in
     *        der Programm Logik vermerken sodass diese dann für die weitere
     *        Abarbeitung nach User wunsch geschehen und mit berüchsichtigung der
     *        aktivierten Checkboxen des Users
     */
    public static void setChechboxesForTrisOrPinBoolean(int index,
            int whichArray)
    {
        switch (whichArray) {
        case 0: {
            port_A_Tris_Checkboxes[index] = !port_A_Tris_Checkboxes[index];
            break;
        }
        case 1: {
            port_A_Pins_Checkboxes[index] = !port_A_Pins_Checkboxes[index];
            break;
        }
        case 2: {
            port_B_Tris_Checkboxes[index] = !port_B_Tris_Checkboxes[index];
            break;
        }
        case 3: {
            port_B_Pins_Checkboxes[index] = !port_B_Pins_Checkboxes[index];
            break;
        }
        default:
            throw new IllegalArgumentException("Unexpected value: " + whichArray);
        }
    }

    // ==========================================================

    /**
     * Diese methode wird die Aktivierung der Watchog Checkbox berücksichtigen
     * und eben dann auch vermerken
     */
    public static void setCheckboxForWatchdog()
    {
        watchdogCheckbox = !watchdogCheckbox;
    }

    // ==========================================================

    /*
     * The Set Method for the Reset Button
     */
    public static void setReset(boolean value)
    {
        if (value == true) {
            resetButton = true;
        } else {
            resetButton = false;
        }
    }

    /*
     * Get Method for the Reset Button Value
     */
    public static boolean getReset()
    {
        return resetButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Einzelschritt Button
     */
    public static void setEinzelschritt(boolean value)
    {
        if (value == true) {
            einzelschrittButton = true;
        } else {
            einzelschrittButton = false;
        }
    }

    /*
     * Get Method for the Einzelschritt Button Value
     */
    public static boolean getEinzelschritt()
    {
        return einzelschrittButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Start Button
     */
    public static void setStart(boolean value)
    {
        if (value == true) {
            startButton = true;
        } else {
            startButton = false;
        }
    }

    /*
     * Get Method for the Start Button Value
     */
    public static boolean getStart()
    {
        return startButton;
    }

    // ==========================================================

    /*
     * The Set Method for the Stop Button
     */
    public static void setStop(boolean value)
    {
        if (value == true) {
            stopButton = true;
        } else {
            stopButton = false;
        }
    }

    /*
     * Get Method for the Stop Button Value
     */
    public static boolean getStop()
    {
        return stopButton;
    }

    // ==========================================================
}

the other Part is my Simulator:

JButton btnStart = new JButton("START");
        btnStart.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                // TODO Auto-generated method stub
                System.out.println("Pressed");
                Brain.setStart(true);
            }
        });

The funny thing is that only if we add a System.out.println() or we Debug... it starts the if.


问:
Google's Geocoding API Closing Connection without Response
I'm currently working on a script to geocode a list of addresses to get it ready for analysis and visualization. This is my first time working with Geocoding, so I'm struggling and not sure if there is something obvious I'm missing here. I'm working with Google's Geocoding API.

The general outline of my (not optimized) process is to turn a column in a DataFrame containing addresses into a list. Then, I create a new list from that one using a list comprehension where each element is a subset of the data I got back.

```<code>key = ...
city = "Long Beach"
state = "CA"

addresses = df["Address"].values.tolist()
geocodes = [geocode(x,city,state,key) for x in addresses]
</code>```

The actual function I'm using for the geocoding is below. It takes in my API key, the address, and city/state parameters to give a move complete address. Then, it just makes the call and returns a list of three elements that I'm looking for in the response.

```<code>def geocode(address, city, state, key):
    time.sleep(.05)
    params = f"{address.lower()} {city}, {state}".replace(" ","+")
    request_url = "https://maps.googleapis.com/maps/api/geocode/json?address="+params+f"&key={key}"
    response = requests.get(request_url).json()
    neighborhood = response["results"][0]["address_components"][2]["long_name"]
    lat = response["results"][0]["geometry"]["location"]["lat"]
    lon = response["results"][0]["geometry"]["location"]["lng"]
    return [neighborhood, lat, lon]
</code>```

When I run it, the script will progress for a while, then fail. When it does, the traceback gives me the exceptions I'm including below this. So far, I haven't been able to find info on what this issue might be or how I should approach diagnosing the problem for Google's Geocoding API. They give info on how to interpret the request statuses, but when I'm checking the statuses that I get back before the failure, all of them are 'OK' and none of them provide an indication of why the connection is closing.

```<code>RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

ProtocolError                             Traceback (most recent call last)
----------
ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
----------
ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
</code>```

Now, I have toyed around with it and ruled out a couple things so far:
1. I have tried this succesfully with single calls and gotten what I needed. The problems happen when I run it on a list.
2. I've used TQDM and printed the statuses (at different points), and the script does successfully make the call, get the data back, and move to the next one many times before it fails.
3. I don't think it's a rate limiting issue. This API has no daily limits, only a Queries per Second limit of 50. The crude time.sleep(.05) in my function should be keeping it to around 20 QPS and have me under that limit.

Does anyone know what my problem might be? Or would someone explain what additional diagnostics I should be doing? Again, I'm new to geocoding and haven't experienced this issue before with the APIs I have experience with, so even help in understanding what's going on so that I can solve it myself would be greatly appreciated if no one can find the problem.

答:
Try using the official googlemaps py module. It uses requests.Session under the hood too but I've never had trouble with it. You may need some multithreading down the line but if you don't have 'too many' addresses, this should do the trick:

```<code>import time
import logging
import googlemaps

key = '...'
gmaps_client = googlemaps.Client(key=key)

addresses = [
    ["8473 Manor Station Street", "Cartersville", "GA"],
    ["14 Edgewater Ave.", "Ottumwa", "IA"],
    ["42 Aspen Court", "San Diego", "CA"]
]

def geocode(address, city, state):
    time.sleep(.05)
    params = f"{address.lower()} {city}, {state}".replace(" ", "+")

    try:
        response = gmaps_client.geocode(params)[0]

        neighborhood = response["address_components"][2]["long_name"]
        lat = response["geometry"]["location"]["lat"]
        lon = response["geometry"]["location"]["lng"]

        return [neighborhood, lat, lon]
    except Exception as e:
        logging.error(e)
        return [None, None, None]

geocodes = [geocode(*group) for group in addresses]

print(geocodes)

</code>```

Body:
I'm currently working on a script to geocode a list of addresses to get it ready for analysis and visualization. This is my first time working with Geocoding, so I'm struggling and not sure if there is something obvious I'm missing here. I'm working with Google's Geocoding API.

The general outline of my (not optimized) process is to turn a column in a DataFrame containing addresses into a list. Then, I create a new list from that one using a list comprehension where each element is a subset of the data I got back.

key = ...
city = "Long Beach"
state = "CA"

addresses = df["Address"].values.tolist()
geocodes = [geocode(x,city,state,key) for x in addresses]

The actual function I'm using for the geocoding is below. It takes in my API key, the address, and city/state parameters to give a move complete address. Then, it just makes the call and returns a list of three elements that I'm looking for in the response.

def geocode(address, city, state, key):
    time.sleep(.05)
    params = f"{address.lower()} {city}, {state}".replace(" ","+")
    request_url = "https://maps.googleapis.com/maps/api/geocode/json?address="+params+f"&key={key}"
    response = requests.get(request_url).json()
    neighborhood = response["results"][0]["address_components"][2]["long_name"]
    lat = response["results"][0]["geometry"]["location"]["lat"]
    lon = response["results"][0]["geometry"]["location"]["lng"]
    return [neighborhood, lat, lon]

When I run it, the script will progress for a while, then fail. When it does, the traceback gives me the exceptions I'm including below this. So far, I haven't been able to find info on what this issue might be or how I should approach diagnosing the problem for Google's Geocoding API. They give info on how to interpret the request statuses, but when I'm checking the statuses that I get back before the failure, all of them are 'OK' and none of them provide an indication of why the connection is closing.

RemoteDisconnected: Remote end closed connection without response

During handling of the above exception, another exception occurred:

ProtocolError                             Traceback (most recent call last)
----------
ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
----------
ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

Now, I have toyed around with it and ruled out a couple things so far:
1. I have tried this succesfully with single calls and gotten what I needed. The problems happen when I run it on a list.
2. I've used TQDM and printed the statuses (at different points), and the script does successfully make the call, get the data back, and move to the next one many times before it fails.
3. I don't think it's a rate limiting issue. This API has no daily limits, only a Queries per Second limit of 50. The crude time.sleep(.05) in my function should be keeping it to around 20 QPS and have me under that limit.

Does anyone know what my problem might be? Or would someone explain what additional diagnostics I should be doing? Again, I'm new to geocoding and haven't experienced this issue before with the APIs I have experience with, so even help in understanding what's going on so that I can solve it myself would be greatly appreciated if no one can find the problem.

Body:
Try using the official googlemaps py module. It uses requests.Session under the hood too but I've never had trouble with it. You may need some multithreading down the line but if you don't have 'too many' addresses, this should do the trick:

import time
import logging
import googlemaps

key = '...'
gmaps_client = googlemaps.Client(key=key)

addresses = [
    ["8473 Manor Station Street", "Cartersville", "GA"],
    ["14 Edgewater Ave.", "Ottumwa", "IA"],
    ["42 Aspen Court", "San Diego", "CA"]
]

def geocode(address, city, state):
    time.sleep(.05)
    params = f"{address.lower()} {city}, {state}".replace(" ", "+")

    try:
        response = gmaps_client.geocode(params)[0]

        neighborhood = response["address_components"][2]["long_name"]
        lat = response["geometry"]["location"]["lat"]
        lon = response["geometry"]["location"]["lng"]

        return [neighborhood, lat, lon]
    except Exception as e:
        logging.error(e)
        return [None, None, None]

geocodes = [geocode(*group) for group in addresses]

print(geocodes)


问:
What data do I need to implement k nearest neighbor?
I currently have a reddit-clone type website. I'm trying to recommend posts based on the posts that my users have previously liked.

It seems like K nearest neighbor or k means are the best way to do this.

I can't seem to understand how to actually implement this. I've seen some mathematical formulas (such as the one on the k means wikipedia page), but they don't really make sense to me.

Could someone maybe recommend some pseudo code, or places to look so I can get a better feel on how to do this?

答:
K-Nearest Neighbor (aka KNN) is a classification algorithm.

Basically, you take a training group of N items and classify them.  How you classify them is completely dependent on your data, and what you think the important classification characteristics of that data are.  In your example, this may be category of posts, who posted the item, who upvoted the item, etc.

Once this 'training' data has been classified, you can then evaluate an 'unknown' data point.  You determine the 'class' of the unknown by locating the nearest neighbors to it in the classification system.  If you determine the classification by the 3 nearest neighbors, it could then be called a 3-nearest neighboring algorithm.

How you determine the 'nearest neighbor' depends heavily on how you classify your data.  It is very common to plot the data into N-dimensional space where N represents the number of different classification characteristics you are examining.

A trivial example:

Let's say you have the longitude/latitude coordinates of a location that can be on any landmass anywhere in the world.  Let us also assume that you do not have a map, but you do have a very large data set that gives you the longitude/latitude of many different cities in the world, and you also know which country those cities are in.

If I asked you which country the a random longitude latitude point is in, would you be able to figure it out?  What would you do to figure it out?

Longitude/latitude data falls naturally into an X,Y graph.  So, if you plotted out all the cities onto this graph, and then the unknown point, how would you figure out the country of the unknown?  You might start drawing circles around that point, growing increasingly larger until the circle encompasses the 10 nearest cities on the plot.  Now, you can look at the countries of those 10 cities.  If all 10 are in the USA, then you can say with a fair degree of certainty that your unknown point is also in the USA.  But if only 6 cities are in the USA, and the other 4 are in Canada, can you say where your unknown point is? You may still guess USA, but with less certainty.

The toughest part of KNN is figuring out how to classify your data in a way that you can determine 'neighbors' of similar quality, and the distance to those neighbors.


问:
TypeScript : how to declare an enum across multiple files?
file AppActions.ts

export enum Actions {
  START = 0,
  RECOVER,
  FIRST_RUN,
  ALERT_NETWORK,
  LOADING_DATA,
  RECEIVED_DATA,
  GO_OFFLINE,
  GO_ONLINE
}
```
<p>file PlayerActions.ts</p>
<pre class="lang-ts prettyprint-override"><code>import {Actions} from "./AppActions.ts"
enum Actions {
  HEAL_SINGLE,
  HIT_SINGLE
}
</code>```

Normally, regarding this manual it should throw an error at compile time. But:

1- the PlayerActions.ts does not seem to extend the existing Actions enum. (in WebStorm import {Actions} from "./AppActions.ts" is in grey)

2- the compiler does not throw any errors.

So what is the right way to declare Enum across multiple files?

答:
It doesn't seem to be possible to have partial enums in Typescript since the Transpiler builds the global types per each "export."

One possible solution might be merging two (multiple) enums as follows:

In the first file you have:

```<code>export enum Action_first_half{
   START = 0,
   RECOVER,
   ...
}
</code>```

In another file you have:

```<code>export enum Action_second_half {
   HEAL_SINGLE,
   HIT_SINGLE
}
</code>```

Then in another file, you can have:

```<code>const Actions = { ...Action_second_half , ...Action_first_half};
type Actions = typeof Actions ;
</code>```

Now, you can treat the "Actions" as if it is a regular enum:

```<code>public const action: Actions = Actions.START;
</code>```

Body:
file AppActions.ts

export enum Actions {
  START = 0,
  RECOVER,
  FIRST_RUN,
  ALERT_NETWORK,
  LOADING_DATA,
  RECEIVED_DATA,
  GO_OFFLINE,
  GO_ONLINE
}

file PlayerActions.ts

import {Actions} from "./AppActions.ts"
enum Actions {
  HEAL_SINGLE,
  HIT_SINGLE
}

Normally, regarding this manual it should throw an error at compile time. But:

1- the PlayerActions.ts does not seem to extend the existing Actions enum. (in WebStorm import {Actions} from "./AppActions.ts" is in grey)

2- the compiler does not throw any errors.

So what is the right way to declare Enum across multiple files?

Body:
It doesn't seem to be possible to have partial enums in Typescript since the Transpiler builds the global types per each "export."

One possible solution might be merging two (multiple) enums as follows:

In the first file you have:

export enum Action_first_half{
   START = 0,
   RECOVER,
   ...
}

In another file you have:

export enum Action_second_half {
   HEAL_SINGLE,
   HIT_SINGLE
}

Then in another file, you can have:

const Actions = { ...Action_second_half , ...Action_first_half};
type Actions = typeof Actions ;

Now, you can treat the "Actions" as if it is a regular enum:

public const action: Actions = Actions.START;


问:
Getting `TypeError: jest.fn is not a function`
I'm trying to create the following unit test using Jest.

```<code>jest.dontMock("pointsAwardingActions.js");
describe("points awarding actions", () => {
  describe("award points", () => {
    it("should dispatch begin ajax action", () => {
      var pointsAwardingActions = require("pointsAwardingActions.js");
      const mockedDispatch = jest.fn();
    });
  });
});
</code>```

But I'm getting the following error after running npm test.

TypeError: jest.fn is not a function

This is some section of my package.json:

```<code>{
  "scripts": {
    "test": "jest"
  },
  "author": "alayor",
  "license": "ISC",
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "testFileExtensions": ["spec.js"],
    "moduleFileExtensions": ["js"],
    "collectCoverage": "true"
  },
  "dependencies": {
    "babel-cli": "6.8.0",
    "babel-core": "6.8.0",
    "babel-jest": "^6.0.1",
    "babel-loader": "6.2.4",
    "babel-plugin-react-display-name": "2.0.0",
    "babel-polyfill": "6.8.0",
    "babel-preset-es2015": "6.6.0",
    "babel-preset-react": "6.5.0",
    "babel-preset-react-hmre": "1.1.1",
    "expect": "1.19.0",
    "express": "4.13.4",
    "jest": "^0.1.40",
    "jest-cli": "^0.8.1",
    ...
  }
}
</code>```

What could be the reason I'm getting that error?

答:
It's already included in your Jest package, so please make sure that you type correct like this: ("mockReturnValue").

It will clear your error.

Body:
I'm trying to create the following unit test using Jest.

jest.dontMock("pointsAwardingActions.js");
describe("points awarding actions", () => {
  describe("award points", () => {
    it("should dispatch begin ajax action", () => {
      var pointsAwardingActions = require("pointsAwardingActions.js");
      const mockedDispatch = jest.fn();
    });
  });
});

But I'm getting the following error after running npm test.

TypeError: jest.fn is not a function

This is some section of my package.json:

{
  "scripts": {
    "test": "jest"
  },
  "author": "alayor",
  "license": "ISC",
  "jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
    "testFileExtensions": ["spec.js"],
    "moduleFileExtensions": ["js"],
    "collectCoverage": "true"
  },
  "dependencies": {
    "babel-cli": "6.8.0",
    "babel-core": "6.8.0",
    "babel-jest": "^6.0.1",
    "babel-loader": "6.2.4",
    "babel-plugin-react-display-name": "2.0.0",
    "babel-polyfill": "6.8.0",
    "babel-preset-es2015": "6.6.0",
    "babel-preset-react": "6.5.0",
    "babel-preset-react-hmre": "1.1.1",
    "expect": "1.19.0",
    "express": "4.13.4",
    "jest": "^0.1.40",
    "jest-cli": "^0.8.1",
    ...
  }
}

What could be the reason I'm getting that error?


问:
React Native ios 'GoogleMaps/GoogleMaps.h' file not found
I got a problem with my app.

When I try to build it on Android Studio everything works fine but when I try to build it on Xcode I got an error and the build fails.

The reason seems to come from AirMaps:

Lexical or Preprocessor Issue

'GoogleMaps/GoogleMaps.h' file not found

```<code>AIRGoogleMapUrlTile.h
</code>```

It's strange because it worked fine until now and I can't find why.

I'm using:

```<code>- "react": "16.0.0-alpha.6",
- "react-native": "0.43.3",
- "react-native-maps": "^0.21.0"
</code>```

and here is my Podfile:

```<code>source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '9.0'

target 'Situaction' do
  rn_path = '../node_modules/react-native'
  rn_maps_path = '../node_modules/react-native-maps'

  pod 'Fabric'
  pod 'Crashlytics'

  pod 'GoogleMaps'
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'react-native-google-maps'
        target.build_configurations.each do |config|
            config.build_settings['CLANG_ENABLE_MODULES'] = 'No'
        end
    end
    if target.name == "React"
        target.remove_from_project
    end
  end
end
</code>```

Can you help me please,

Thanks in advance

EDIT:

here are the header search paths.
Header Search Paths

答:
If you are using React Native 0.60 and higher, add the following to your Podfile above the use_native_modules! function and run pod install in the ios folder:

```<code>  # React Native Maps dependencies
  rn_maps_path = '../node_modules/react-native-maps'
  pod 'react-native-google-maps', :path => rn_maps_path
  pod 'GoogleMaps'
  pod 'Google-Maps-iOS-Utils'
</code>```

visit the documentation

Body:
I got a problem with my app.

When I try to build it on Android Studio everything works fine but when I try to build it on Xcode I got an error and the build fails.

The reason seems to come from AirMaps:

Lexical or Preprocessor Issue

'GoogleMaps/GoogleMaps.h' file not found

AIRGoogleMapUrlTile.h

It's strange because it worked fine until now and I can't find why.

I'm using:

- "react": "16.0.0-alpha.6",
- "react-native": "0.43.3",
- "react-native-maps": "^0.21.0"

and here is my Podfile:

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '9.0'

target 'Situaction' do
  rn_path = '../node_modules/react-native'
  rn_maps_path = '../node_modules/react-native-maps'

  pod 'Fabric'
  pod 'Crashlytics'

  pod 'GoogleMaps'
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'react-native-google-maps'
        target.build_configurations.each do |config|
            config.build_settings['CLANG_ENABLE_MODULES'] = 'No'
        end
    end
    if target.name == "React"
        target.remove_from_project
    end
  end
end

Can you help me please,

Thanks in advance

EDIT:

here are the header search paths.
Header Search Paths

Body:
If you are using React Native 0.60 and higher, add the following to your Podfile above the use_native_modules! function and run pod install in the ios folder:

  # React Native Maps dependencies
  rn_maps_path = '../node_modules/react-native-maps'
  pod 'react-native-google-maps', :path => rn_maps_path
  pod 'GoogleMaps'
  pod 'Google-Maps-iOS-Utils'

visit the documentation


问:
What is PAGEIOLATCH_SH wait type in SQL Server?
I have a query that is taking a long time in the middle of a transaction. When I get the wait_type of the process it is PAGEIOLATCH_SH.

What does this wait type mean and how can this be resolved?

答:
From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

```<code>Select * from <table> where <col1> = <value> order by <PrimaryKey>
</code>```

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

OwnerDisplayName: Ryan

Body:
From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

OwnerDisplayName: Quassnoi

LastEditorDisplayName: Quassnoi


问:
NoClassDefFoundError: org/w3c/dom/ls/DocumentLS - issue occurring only on deployment after having fixed it on compile time

Background

I have a project where I parse some XML documents and I happened to need the xerces dependency:

```<code><dependency>
    <groupId>xerces</groupId>
    <artifactId>xerces</artifactId>
    <version>2.4.0</version>
</dependency>
</code>```

While writing the unit tests with junit4, I had an issue every time I was running a unit test, which was the following and occurring every time I was compiling with mvn clean install:

```<code>[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.346 s <<< FAILURE! - in ConversionTest
[ERROR] ConversionTest.initializationError  Time elapsed: 0.054 s  <<< ERROR!
java.lang.NoClassDefFoundError: org/w3c/dom/ls/DocumentLS
        at ConversionTest.fromDirectory(ConversionTest.java:92)
        at ConversionTest.data(ConversionTest.java:65)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ls.DocumentLS
        at ConversionTest.fromDirectory(ConversionTest.java:92)
        at ConversionTest.data(ConversionTest.java:65)
</code>```

Compile-time solution

Searching the web, I have realized that I needed to add a new dependency to my pom.xml:

```<code><dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>
</code>```

After doing this, the tests compiled fine and I could produce my .jar which was packaged with the following build plug-in:

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>com.company.tools.Application</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
</code>```

... and compiled with the following settings:

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <configuration>
                <encoding>cp1252</encoding>
                <release>11</release>
                <fork>true</fork>
                <meminitial>128m</meminitial>
                <maxmem>512m</maxmem>
                <compilerArgs>
                    <arg>-Xpkginfo:always</arg>
                </compilerArgs>
            </configuration>
        </plugin>
</code>```

This produced a .jar which contains all the required dependencies, here including the famous org/w3c/dom/ls/DocumentLS:

Deployment

Now I move this .jar into my server and try to run it with the following command:

```<code>java -jar myJar.jar <inputs>
</code>```

When I do that, I get the following exception, again!

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/w3c/dom/ls/DocumentLS
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
        at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
        at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:801)
        at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:699)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:622)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:580)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at org.apache.xerces.jaxp.DocumentBuilderImpl.<init>(Unknown Source)
        at org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(Unknown Source)
        at com.company.tools.impl.FileProviderImpl.getXmlFile(FileProviderImpl.java:68)
        at com.company.tools.impl.FileProviderImpl.<init>(FileProviderImpl.java:38)
        at com.company.tools.impl.FileProviderImpl$Builder.build(FileProviderImpl.java:91)
        at com.company.tools.Application.main(Application.java:50)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ls.DocumentLS
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        ... 15 more
</code>```

My question and some details about the machines

I am a bit lost here. I've added the dependency to my pom.xml, the class is well packaged inside the .jar, but still I have the same issue.
What am I doing wrong?

If it can help:

My machine:

```<code>Java version: 11.0.2-BellSoft, vendor: BellSoft, runtime: C:\jdk-11.0.2
Default locale: fr_FR, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
</code>```

My server:

```<code>openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
OS: Linux myServerAddress 3.10.0-327.el7.x86_64 #1 SMP Thu Oct 29 17:29:29 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Thanks in advance!

答:
I ended up finding the solution thanks to @Sambit second comment about this GitHub issue. Posting the answer here hoping it can save someone else days of headache!

Basically, I had this in my pom.xml:

```<code><dependencies>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xerces</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>
</dependencies>
</code>```

In both cases (unit test and main code), the exception was raised by this code:

```<code>try(InputStream is = new FileInputStream(file)) {
    documents.put(file.getName(), DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is));
}
</code>```

... specifically, by the call to newDocumentBuilder() which was looking for an implementation of type DocumentImpl.

Issue explanation

The first dependency xerces is pulling a transitive dependency on a deprecated version of xercesImpl.
Hence, when I was running my tests, the code was compiling (because the dependency was there) but when the newDocumentBuilder() was looking for the DocumentImpl, the implementation was returned by the bad dependency which was looking for org/w3c/dom/ls/DocumentLS without success, so raising the NoClassDefFoundError.

Once I added the explicit dependency to xercesImpl in my pom, the junit runner understood that instead of searching the DocumentImpl in the deprecated version of xercesImpl, it should have been looked for in the explicit dependency so the issue was solved.

However, the JVM running the program on the server wasn't taking the same assumption: the newDocumentBuilder() was still looking for DocumentImpl inside the transitive dependency, so the issue was still there.

Resolution

Get rid of the transitive dependency:

```<code><dependencies>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xerces</artifactId>
        <version>2.4.0</version>
        <exclusions>
            <exclusion>
                <groupId>xerces</groupId>
                <artifactId>xercesImpl</artifactId>
            <exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>
</dependencies>
</code>```

Body:
Background

I have a project where I parse some XML documents and I happened to need the xerces dependency:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xerces</artifactId>
    <version>2.4.0</version>
</dependency>

While writing the unit tests with junit4, I had an issue every time I was running a unit test, which was the following and occurring every time I was compiling with mvn clean install:

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.346 s <<< FAILURE! - in ConversionTest
[ERROR] ConversionTest.initializationError  Time elapsed: 0.054 s  <<< ERROR!
java.lang.NoClassDefFoundError: org/w3c/dom/ls/DocumentLS
        at ConversionTest.fromDirectory(ConversionTest.java:92)
        at ConversionTest.data(ConversionTest.java:65)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ls.DocumentLS
        at ConversionTest.fromDirectory(ConversionTest.java:92)
        at ConversionTest.data(ConversionTest.java:65)

Compile-time solution

Searching the web, I have realized that I needed to add a new dependency to my pom.xml:

<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0</version>
</dependency>

After doing this, the tests compiled fine and I could produce my .jar which was packaged with the following build plug-in:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>com.company.tools.Application</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

... and compiled with the following settings:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.plugin.version}</version>
            <configuration>
                <encoding>cp1252</encoding>
                <release>11</release>
                <fork>true</fork>
                <meminitial>128m</meminitial>
                <maxmem>512m</maxmem>
                <compilerArgs>
                    <arg>-Xpkginfo:always</arg>
                </compilerArgs>
            </configuration>
        </plugin>

This produced a .jar which contains all the required dependencies, here including the famous org/w3c/dom/ls/DocumentLS:

Deployment

Now I move this .jar into my server and try to run it with the following command:

java -jar myJar.jar <inputs>

When I do that, I get the following exception, again!

Exception in thread "main" java.lang.NoClassDefFoundError: org/w3c/dom/ls/DocumentLS
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
        at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
        at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:801)
        at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:699)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:622)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:580)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at org.apache.xerces.jaxp.DocumentBuilderImpl.<init>(Unknown Source)
        at org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.newDocumentBuilder(Unknown Source)
        at com.company.tools.impl.FileProviderImpl.getXmlFile(FileProviderImpl.java:68)
        at com.company.tools.impl.FileProviderImpl.<init>(FileProviderImpl.java:38)
        at com.company.tools.impl.FileProviderImpl$Builder.build(FileProviderImpl.java:91)
        at com.company.tools.Application.main(Application.java:50)
Caused by: java.lang.ClassNotFoundException: org.w3c.dom.ls.DocumentLS
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        ... 15 more

My question and some details about the machines

I am a bit lost here. I've added the dependency to my pom.xml, the class is well packaged inside the .jar, but still I have the same issue.
What am I doing wrong?

If it can help:

My machine:

Java version: 11.0.2-BellSoft, vendor: BellSoft, runtime: C:\jdk-11.0.2
Default locale: fr_FR, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

My server:

openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
OS: Linux myServerAddress 3.10.0-327.el7.x86_64 #1 SMP Thu Oct 29 17:29:29 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux

Thanks in advance!

Body:
I ended up finding the solution thanks to @Sambit second comment about this GitHub issue. Posting the answer here hoping it can save someone else days of headache!

Basically, I had this in my pom.xml:

<dependencies>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xerces</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>
</dependencies>

In both cases (unit test and main code), the exception was raised by this code:

try(InputStream is = new FileInputStream(file)) {
    documents.put(file.getName(), DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is));
}

... specifically, by the call to newDocumentBuilder() which was looking for an implementation of type DocumentImpl.

Issue explanation

The first dependency xerces is pulling a transitive dependency on a deprecated version of xercesImpl.
Hence, when I was running my tests, the code was compiling (because the dependency was there) but when the newDocumentBuilder() was looking for the DocumentImpl, the implementation was returned by the bad dependency which was looking for org/w3c/dom/ls/DocumentLS without success, so raising the NoClassDefFoundError.

Once I added the explicit dependency to xercesImpl in my pom, the junit runner understood that instead of searching the DocumentImpl in the deprecated version of xercesImpl, it should have been looked for in the explicit dependency so the issue was solved.

However, the JVM running the program on the server wasn't taking the same assumption: the newDocumentBuilder() was still looking for DocumentImpl inside the transitive dependency, so the issue was still there.

Resolution

Get rid of the transitive dependency:

<dependencies>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xerces</artifactId>
        <version>2.4.0</version>
        <exclusions>
            <exclusion>
                <groupId>xerces</groupId>
                <artifactId>xercesImpl</artifactId>
            <exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>xerces</groupId>
        <artifactId>xercesImpl</artifactId>
        <version>2.11.0</version>
    </dependency>
</dependencies>


问:
I can't switch between tabs on a Bottom Navigation Bar in my App
I am having quite a challenge, i was following some tutorial project but when we reached a point of adding a bottom navigation bar, I have been stuck here for weeks trying to figure out where the problem is.
The activity loads successfully but i can not switch between the different tabs on the bottom navigation bar namely, Home, Add and Logout.

Here is my Code for the activity.

```<code>public class SellerHomeActivity extends AppCompatActivity {

private TextView mTextMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seller_home);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {

                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;

                case R.id.navigation_add:
                    Intent intentCategory = new Intent(SellerHomeActivity.this, SellerProductCategoryActivity.class);
                    startActivity(intentCategory);
                    return true;

                case R.id.navigation_logout:
                    final FirebaseAuth mAuth;
                    mAuth = FirebaseAuth.getInstance();
                    mAuth.signOut();

                    Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                    intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intentMain);
                    finish();
                    return true;
            }

            return false;

        }
    });
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
</code>```

//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }

}

Any help rendered will be so helpful to me,
Thanks in advance

答:
Another approach I can suggest making BottomNavigationView navView public static and adding another OnNavigationItemSelectedListener in your SellerProductCategoryActivity.

In this case first activity should look like this:

```<code>public class SellerHomeActivity extends AppCompatActivity {

public static TextView mTextMessage;
public static BottomNavigationView navView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_home);
navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {

            case R.id.navigation_home:

                return true;

            case R.id.navigation_add:
                Intent intentCategory = new Intent(SellerHomeActivity.this, SellerProductCategoryActivity.class);
                startActivity(intentCategory);
                return true;

            case R.id.navigation_logout:
                final FirebaseAuth mAuth;
                mAuth = FirebaseAuth.getInstance();
                mAuth.signOut();

                Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intentMain);
                finish();
                return true;
        }

        return false;

    }
});
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
        R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout)
        .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
</code>```

And the listener on SellerProductCategoryActivity should be like this:

```<code>SellerHomeActivity.navView.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {

            case R.id.navigation_home:
                SellerHomeActivity.mTextMessage.setText(R.string.title_home);
                Intent intentCategory = new Intent(SellerProductCategoryActivity.this,
                SellerHomeActivity.class);
                startActivity(intentCategory);
                return true;

            case R.id.navigation_add:
                return true;

            case R.id.navigation_logout:
                final FirebaseAuth mAuth;
                mAuth = FirebaseAuth.getInstance();
                mAuth.signOut();

                Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intentMain);
                finish();
                return true;
        }

        return false;

    }
});
</code>```

Body:
I am having quite a challenge, i was following some tutorial project but when we reached a point of adding a bottom navigation bar, I have been stuck here for weeks trying to figure out where the problem is.
The activity loads successfully but i can not switch between the different tabs on the bottom navigation bar namely, Home, Add and Logout.

Here is my Code for the activity.

public class SellerHomeActivity extends AppCompatActivity {

private TextView mTextMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seller_home);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {

                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;

                case R.id.navigation_add:
                    Intent intentCategory = new Intent(SellerHomeActivity.this, SellerProductCategoryActivity.class);
                    startActivity(intentCategory);
                    return true;

                case R.id.navigation_logout:
                    final FirebaseAuth mAuth;
                    mAuth = FirebaseAuth.getInstance();
                    mAuth.signOut();

                    Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                    intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intentMain);
                    finish();
                    return true;
            }

            return false;

        }
    });
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }

}

Any help rendered will be so helpful to me,
Thanks in advance

Body:
Another approach I can suggest making BottomNavigationView navView public static and adding another OnNavigationItemSelectedListener in your SellerProductCategoryActivity.

In this case first activity should look like this:

public class SellerHomeActivity extends AppCompatActivity {

public static TextView mTextMessage;
public static BottomNavigationView navView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_home);
navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {

            case R.id.navigation_home:

                return true;

            case R.id.navigation_add:
                Intent intentCategory = new Intent(SellerHomeActivity.this, SellerProductCategoryActivity.class);
                startActivity(intentCategory);
                return true;

            case R.id.navigation_logout:
                final FirebaseAuth mAuth;
                mAuth = FirebaseAuth.getInstance();
                mAuth.signOut();

                Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intentMain);
                finish();
                return true;
        }

        return false;

    }
});
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
        R.id.navigation_home, R.id.navigation_add, R.id.navigation_logout)
        .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

And the listener on SellerProductCategoryActivity should be like this:

SellerHomeActivity.navView.setOnNavigationItemSelectedListener(new
BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {

            case R.id.navigation_home:
                SellerHomeActivity.mTextMessage.setText(R.string.title_home);
                Intent intentCategory = new Intent(SellerProductCategoryActivity.this,
                SellerHomeActivity.class);
                startActivity(intentCategory);
                return true;

            case R.id.navigation_add:
                return true;

            case R.id.navigation_logout:
                final FirebaseAuth mAuth;
                mAuth = FirebaseAuth.getInstance();
                mAuth.signOut();

                Intent intentMain = new Intent(SellerHomeActivity.this, MainActivity.class);
                intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intentMain);
                finish();
                return true;
        }

        return false;

    }
});


问:
Microsoft Access Question
I do not know VB that well. I can figure out most things. I was wondering if anyone can tell me what this line of code means</p>

```<code>Option Compare Database
</code>```

答:
It means "In this module, compare strings using rules that are defined in the database."

Alternatives are Option Compare Text (case-insensitive compare) and Option Compare Binary (case-sensitive).

Had you used Google, you would immediately have found this article that explains everything.

Title: Microsoft Access Question

Body:
I do not know VB that well. I can figure out most things. I was wondering if anyone can tell me what this line of code means

Option Compare Database


问:
Limit access to gitlab-runner from gitlab.com
I've installed a gitlab-runner instance on my server. I currently set up the firewall as allowing access to port 443, which the gitlab-runner is running on. There are no further restrictions configured though and I'd like to see it limited to gitlab.com only.

Is it possible to limit the source IPs to gitlab's?
Or is it safe to have a firewall rule that just opens port 443 for the runner?

Note: the executor is docker unprivileged

答:
You dont need to open any incoming ports, all the communication is from your runner instance to the gitlab.com

Your runner check every x time if there is a job to pull. It just need an internet access to reach (https) the gitlab.com site.


问:
Kubernetes nginx ingress prevent response from default-backend on https
Currently with the nginx ingress in kubernetes it will always respond to direct IP requests (i.e. http://1.1.1.1) with the default-backend and there doesn't appear to be a way of disabling it.

Worse, it will also respond to https://1.1.1.1 in the same manner with a self-signed cert (you can override it but obviously even if you provide a valid cert, it still won't be valid against an IP request)  This is a major security vulnerability that causes any site using Kubernetes and nginx ingress to fail PCI compliance network scans.

AND there is no way of overriding this behavior in your ingress defintion.

I'm trying to figure out how without hacking to be able to prevent the default-backend from responding to https on an IP request given that there is never a case in a production environment where this would be secure and will always cause PCI failure.

How does one get the nginx ingress to not respond to https on an IP request?

答:
I tried googling and tested several ideas but non of them worked.

I also tried reading nginx-ingress code but didn't find anything satisfying.

I think that the best thing you could do is to ask developers.
Just open an issue on nginx-ingress github repository.