问:
How to get size of String array
I create a string array in "Arduino" like this:

```<code>String commandList[] = {"dooropen", "doorlock"};
</code>```

And in my code I want to know size of this array and I don't want define size of this array like bottom code:

```<code>#define commandListArraySize 2
</code>```

I try to get size of this variable like this:

```<code>int size = sizeof(commandList);
</code>```

But the returned size = 12.

答:
I like template Array Size variant as it can't be used with pointer type:

// Solution proposed by @TylerLewis:
#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])

// Template based solution:
template<typename T, size_t N> size_t ArraySize(T(&)[N]){ return N; }

int test(String * ptr);

void setup() {
  String arr[] = {"A", "B", "C"};
  Serial.begin(115200);
  Serial.println(ArraySize(arr));  // prints 3
  Serial.println(ARRAY_SIZE(arr)); // prints 3

  test(arr);
}

void loop() {
}

int test(String * ptr) {
  // Serial.println(ArraySize(ptr));  // compile time error
  Serial.println(ARRAY_SIZE(ptr));    // prints 0 as sizeof pointer is 2 and sizeof String is 6
}
```

Title: How to get size of String array

Body:
I create a string array in "Arduino" like this:

String commandList[] = {"dooropen", "doorlock"};

And in my code I want to know size of this array and I don't want define size of this array like bottom code:

#define commandListArraySize 2

I try to get size of this variable like this:

int size = sizeof(commandList);

But the returned size = 12.


来源: stackexchange

问:
Records by unique id and on a per minute boundary
In a mysql database table below, I have records as shown below. I have data for many ID's. In the given example, I want to be able to get the first record in the list which has the least distance value. Additionally, I have an entire timeline of such data for many hours. So the goal is that for each MINUTE in the timeline, I want to be able to pick records for each unique ID in that minute with the lowest distance value. I know it's going to take a couple of good group by queries with join's but I've been unable to come up with something. Please help!!</p>

```<code>| NAME    | ID    | TIME                    | TOTAL_TIME | DISTANCE
| chicago | 74    | 2017-02-26 23:17:39 GMT | 54         | 5
| new york| 74    | 2017-02-26 23:17:51 GMT | 42         | 3
| chicago | 74    | 2017-02-26 23:17:41 GMT | 56         | 11
| chicago | 74    | 2017-02-26 23:17:52 GMT | 67         | 12
| new york| 74    | 2017-02-26 23:17:53 GMT | 44         | 8
| new york| 74    | 2017-02-26 23:17:56 GMT | 47         | 8
</code>```

答:
for each MINUTE in the timeline, I want to be able to pick records for each unique ID in that minute with the lowest distance value.

Kudos for expressing your SQL needs in clear English. First we need to decide on a GROUP BY key, which truncates a DATETIME down to the minutes. Unfortunately, MySQL has very bad datetime manipulation functions, so I'll use a kludge: convert to a string.

```<code>mysql> select LEFT(now(),16);
+------------------+
| LEFT(now(),16)   |
+------------------+
| 2017-04-01 21:15 |
+------------------+
</code>```

Now, a self join will give the rows that contain the minimum distance. Note that if several rows contain the same minimum distance, they will all be returned.

```<code>SELECT t.* FROM
( SELECT id, LEFT(time, 16) AS minute,
         min(distance) distance FROM yourtable
  GROUP BY LEFT(time, 16), id ) a
JOIN yourtable t USING (id, distance)
</code>```

This should do the trick...

ContentLicense: CC BY-SA 3.0

Body:
In a mysql database table below, I have records as shown below. I have data for many ID's. In the given example, I want to be able to get the first record in the list which has the least distance value. Additionally, I have an entire timeline of such data for many hours. So the goal is that for each MINUTE in the timeline, I want to be able to pick records for each unique ID in that minute with the lowest distance value. I know it's going to take a couple of good group by queries with join's but I've been unable to come up with something. Please help!!

| NAME    | ID    | TIME                    | TOTAL_TIME | DISTANCE
| chicago | 74    | 2017-02-26 23:17:39 GMT | 54         | 5
| new york| 74    | 2017-02-26 23:17:51 GMT | 42         | 3
| chicago | 74    | 2017-02-26 23:17:41 GMT | 56         | 11
| chicago | 74    | 2017-02-26 23:17:52 GMT | 67         | 12
| new york| 74    | 2017-02-26 23:17:53 GMT | 44         | 8
| new york| 74    | 2017-02-26 23:17:56 GMT | 47         | 8

Body:
for each MINUTE in the timeline, I want to be able to pick records for each unique ID in that minute with the lowest distance value.

Kudos for expressing your SQL needs in clear English. First we need to decide on a GROUP BY key, which truncates a DATETIME down to the minutes. Unfortunately, MySQL has very bad datetime manipulation functions, so I'll use a kludge: convert to a string.

mysql> select LEFT(now(),16);
+------------------+
| LEFT(now(),16)   |
+------------------+
| 2017-04-01 21:15 |
+------------------+

Now, a self join will give the rows that contain the minimum distance. Note that if several rows contain the same minimum distance, they will all be returned.

SELECT t.* FROM
( SELECT id, LEFT(time, 16) AS minute,
         min(distance) distance FROM yourtable
  GROUP BY LEFT(time, 16), id ) a
JOIN yourtable t USING (id, distance)

This should do the trick...


问:
How can run a Python script from an Fsharp module
While writing a fsharp module I realized the need to make a call to a python script.
- Cannot switch my fsharp module to python it'll break established infrastructure
- Cannot move the python functionality to fsharp, as it wouldn't be possible to convert all the nuances/efficiency of the code.

Any recommendations on how to call a python script from a fsharp module, passing in a couple of parameters (string values) and getting back a string value response?

答: Try out the Nuget package Python for .NET.  The Nuget link is here: https://www.nuget.org/packages/pythonnet/2.3.0-py35-dotnet and includes links to the project on github.</p>


问:
@Transactional annotation not working
I am trying to save a TestEntity object in the database. The code is being executed and the Id for the entity is created, but the entity is not persisted to the database (no row inserted):

```<code>@Repository
public class DBConnectionConfig {
    @Autowired
    SessionFactory sessionFactory;
    DBConnectionConfig(){
        //this.sessionFactory=getSessionFactory();
    }
    /*private SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    private void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }*/
    public Session getSession(){
        return sessionFactory.openSession();
    }
}

package com.homecare.persistance.repository;
@Repository
@Transactional
public class HomeCareDaoImp extends DBConnectionConfig  implements HomeCareDao{
    Logger LOGGER=Logger.getLogger("Connection.class");
    Session session=null;
    Transaction trnx=null;
    @Autowired
    ApplicationContext ctx;
    @Autowired
    DBConnectionConfig dBConnectionConfig;
    public void doaProcess(TestEntity testEntity){
        LOGGER.info(dBConnectionConfig.toString());
        session=getSession();
        // trnx=session.beginTransaction();
        session.save(testEntity);
        // session.flush();
        // trnx.commit();
        LOGGER.info("connection established");
    }
}
</code>```

Removing the comments from the 3 lines (beginTransation, flush, commit) solves the problem, but why does the @Transactional annotation not work here?

Spring XML:

```<code><!-- Our service layer components -->
<context:component-scan base-package="com.homecare" />
<!-- <context:component-scan base-package="com.homecare.persistance.repository" /> -->

 <!-- enable @Transactional Annotation -->

<!-- data source with c3p0 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.postgresql.Driver" />
      <property name="url" value="jdbc:postgresql://localhost:5433/My_DB" />
      <property name="username" value="postgres" />
      <property name="password" value="password" />
   </bean>

   <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.homecare.persistance.resource"></property>   <!-- yet to defined place where to scan> -->
      <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="SessionFactory" />
   </bean>
</beans>
</code>```

POM xml file:

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

<!-- spring framwork -->
<!-- Hibernate -->
       <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
       </dependency>
        <dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache-core</artifactId>
           <version>2.2.0</version>
       </dependency>
</code>```

答:
Try by overriding the getSession() method:</p>

```<code>@Repository
@Transactional
public class HomeCareDaoImp extends DBConnectionConfig  implements HomeCareDao{
    Logger LOGGER=Logger.getLogger("Connection.class");
    Session session=null;
    Transaction trnx=null;

    @Autowired
    ApplicationContext ctx;

    public void doaProcess(TestEntity testEntity){
            LOGGER.info(dBConnectionConfig.toString());
            session=getSession();
            // trnx=session.beginTransaction();
            session.save(testEntity);
            // session.flush();
            // trnx.commit();
            LOGGER.info("connection established");
        }

    @Override
    public void getSession() {
        super.getSession();
    }
  }
</code>```

Title: @Transactional annotation not working

Body:
I am trying to save a TestEntity object in the database. The code is being executed and the Id for the entity is created, but the entity is not persisted to the database (no row inserted):

@Repository
public class DBConnectionConfig {
    @Autowired
    SessionFactory sessionFactory;
    DBConnectionConfig(){
        //this.sessionFactory=getSessionFactory();
    }
    /*private SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    private void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }*/
    public Session getSession(){
        return sessionFactory.openSession();
    }
}

package com.homecare.persistance.repository;
@Repository
@Transactional
public class HomeCareDaoImp extends DBConnectionConfig  implements HomeCareDao{
    Logger LOGGER=Logger.getLogger("Connection.class");
    Session session=null;
    Transaction trnx=null;
    @Autowired
    ApplicationContext ctx;
    @Autowired
    DBConnectionConfig dBConnectionConfig;
    public void doaProcess(TestEntity testEntity){
        LOGGER.info(dBConnectionConfig.toString());
        session=getSession();
        // trnx=session.beginTransaction();
        session.save(testEntity);
        // session.flush();
        // trnx.commit();
        LOGGER.info("connection established");
    }
}

Removing the comments from the 3 lines (beginTransation, flush, commit) solves the problem, but why does the @Transactional annotation not work here?

Spring XML:

<context:component-scan base-package="com.homecare" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.postgresql.Driver" />
      <property name="url" value="jdbc:postgresql://localhost:5433/My_DB" />
      <property name="username" value="postgres" />
      <property name="password" value="password" />
   </bean>

   <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.homecare.persistance.resource"></property>
      <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="SessionFactory" />
   </bean>
</beans>

POM xml file:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

       <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
       </dependency>
        <dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache-core</artifactId>
           <version>2.2.0</version>
       </dependency>

Body:
Try by overriding the getSession() method:

@Repository
@Transactional
public class HomeCareDaoImp extends DBConnectionConfig  implements HomeCareDao{
    Logger LOGGER=Logger.getLogger("Connection.class");
    Session session=null;
    Transaction trnx=null;

    @Autowired
    ApplicationContext ctx;

    public void doaProcess(TestEntity testEntity){
            LOGGER.info(dBConnectionConfig.toString());
            session=getSession();
            // trnx=session.beginTransaction();
            session.save(testEntity);
            // session.flush();
            // trnx.commit();
            LOGGER.info("connection established");
        }

    @Override
    public void getSession() {
        super.getSession();
    }
  }


问:
Error /usr/bin/env: ‘python’: No such file or directory - installing presto on AWS EC2 instance
I unpacked the presto on AWS EC2 instance and followed the documentation on prestodb
when I run bin/launcher startI get the following error:

/usr/bin/env: ‘python’: No such file or directory

答:
I guess documentation could mention that explicitly, but you need certain piece of software installed to run presto. This includes, but is not limited to:

Supported Java JVM

Python (i guess 2.7 would do)


问:
How To Install Pytesseract in windows 8.1(win64) (visual studio 2012+python+anaconda)
```<code>from PIL import Image
from tesseract import image_to_string

print image_to_string(Image.open('C:\Users/Uzel/Desktop/pythonfoto/denklem.png'))
print image_to_string(Image.open('C:\Users/Uzel/Desktop/pythonfoto/denklem.png'), lang='eng')
</code>```

I use this code after installing tesseract orc.

Traceback (most recent call last):
  File "C:\Users\Uzel\Documents\Visual Studio 2012\Projects\module3.py", line 28, in
    from tesseract import image_to_string
ImportError: cannot import name image_to_string

I have this error. I tried pytesseract but I can not manage. Can we solve this problem. How? thank you.

答:
Below is a sample code with pytesseract.

```<code>import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract 4.0.0/tesseract.exe"
print(pytesseract.image_to_string(Image.open("./imagesStackoverflow/text.png"),
                                  lang="eng",boxes=False,config="--psm 3 --eom 3"))
</code>```

The pytesseract.pytesseract.tesseract_cmd is to specific the EXE path explicitly in case the path hasn't been properly set up in Windows environment.

You need to have Tesseract installed in Windows and pytesseract installed with Python.

Hope this help.

Body:
from PIL import Image
from tesseract import image_to_string

print image_to_string(Image.open('C:\Users/Uzel/Desktop/pythonfoto/denklem.png'))
print image_to_string(Image.open('C:\Users/Uzel/Desktop/pythonfoto/denklem.png'), lang='eng')

I use this code after installing tesseract orc.

Traceback (most recent call last):
  File "C:\Users\Uzel\Documents\Visual Studio 2012\Projects\module3.py", line 28, in
    from tesseract import image_to_string
ImportError: cannot import name image_to_string

I have this error. I tried pytesseract but I can not manage. Can we solve this problem. How? thank you.

Body:
Below is a sample code with pytesseract.

import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract 4.0.0/tesseract.exe"
print(pytesseract.image_to_string(Image.open("./imagesStackoverflow/text.png"),
                                  lang="eng",boxes=False,config="--psm 3 --eom 3"))

The pytesseract.pytesseract.tesseract_cmd is to specific the EXE path explicitly in case the path hasn't been properly set up in Windows environment.

You need to have Tesseract installed in Windows and pytesseract installed with Python.

Hope this help.


问:
Running a python script with website input
I've got a bit of webdev experience, and just started learning python. I've created a python script that takes in an argument, and then runs a program, and prints print statements into the console. I'm curious if it's possible to put this program behind a webpage.

i.e. Webpage with a dropdown, chose the option and click a "Go" button. Then the python script is run with the option you chose, and your report is shown on the page.

I've looked at a few similar posts: Execute a python script on button click

run python script with html button

but they seem to offer very different solutions, and people seem to think the PhP idea is insecure. I'm also looking for something a bit more explicit. I'm fine to change the python script to return ajson or something instead of just print statements.

答:
A pretty common way to communicate between a webpage and a python program is to run the python as a WSGI server.  Effectively the python program is a separate server which communicates with the webpage using GETs and POSTs.

One nice thing about this approach is that it decouples the Python app from the the web-page proper.  You can test it by sending http requests directly to a test server while you're developing.

Python includes a built-in WSGI implementation, so creating a WSGI server is pretty simple.  Here's a very minimal example:

```<code>from wsgiref.simple_server import make_server

# this will return a text response
def hello_world_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain')]  # HTTP Headers
    start_response(status, headers)
    return ["Hello World"]

# first argument passed to the function
# is a dictionary containing CGI-style environment variables
# second argument is a function to call
# make a server and turn it on port 8000
httpd = make_server('', 8000, hello_world_app)
httpd.serve_forever()
</code>```

Body:
A pretty common way to communicate between a webpage and a python program is to run the python as a WSGI server.  Effectively the python program is a separate server which communicates with the webpage using GETs and POSTs.

One nice thing about this approach is that it decouples the Python app from the the web-page proper.  You can test it by sending http requests directly to a test server while you're developing.

Python includes a built-in WSGI implementation, so creating a WSGI server is pretty simple.  Here's a very minimal example:

from wsgiref.simple_server import make_server

# this will return a text response
def hello_world_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain')]  # HTTP Headers
    start_response(status, headers)
    return ["Hello World"]

# first argument passed to the function
# is a dictionary containing CGI-style environment variables
# second argument is a function to call
# make a server and turn it on port 8000
httpd = make_server('', 8000, hello_world_app)
httpd.serve_forever()


问:
JAVA Array of int to bytes array
I have an int array int[] stegoBitsArray = {0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,1...} I want each 8 bits converted to byte and added to byte array which i would later convert to char array because 01101100 is letter "l" and so on so ... So i tried using ByteBuffer but it throws me BufferOverflowException here's my code snippet:

```<code> int[] stegoBitsArray = getStegoTextFromImage(stegoImage);
 ByteBuffer byteBuffer = ByteBuffer.allocate(stegoBitsArray.length);
 for (int i = 0; i < stegoBitsArray.length; i++) {
    byteBuffer.putInt(stegoBitsArray[i]);
 }
</code>```

Or it's more better to convert from int array to characters?

答:
How come you can have a value like 0110110001100001 in an integer array. Either it can be stored as a string or there is another way.

You can have an array of integer values something like int array = {123, 456, 333} etc then you can directly convert those integers to characters by looping on the array.

```<code>for(int i = 0; i < array.length; i++){
   char c = (char)array[i];
   System.out.println(c);
}
</code>```

Or if you want to convert integer to binary then Java supports in Integer class a method called toBinaryString. you can find a good resource for it HERE.

The combination of these two can lead you to your desired solution.

Title: JAVA Array of int to bytes array

Body:
I have an int array int[] stegoBitsArray = {0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,1...} I want each 8 bits converted to byte and added to byte array which i would later convert to char array because 01101100 is letter "l" and so on so ... So i tried using ByteBuffer but it throws me BufferOverflowException here's my code snippet:

 int[] stegoBitsArray = getStegoTextFromImage(stegoImage);
 ByteBuffer byteBuffer = ByteBuffer.allocate(stegoBitsArray.length);
 for (int i = 0; i < stegoBitsArray.length; i++) {
    byteBuffer.putInt(stegoBitsArray[i]);
 }

Or it's more better to convert from int array to characters?

Body:
How come you can have a value like 0110110001100001 in an integer array. Either it can be stored as a string or there is another way.

You can have an array of integer values something like int array = {123, 456, 333} etc then you can directly convert those integers to characters by looping on the array.

for(int i = 0; i < array.length; i++){
   char c = (char)array[i];
   System.out.println(c);
}

Or if you want to convert integer to binary then Java supports in Integer class a method called toBinaryString. you can find a good resource for it HERE.

The combination of these two can lead you to your desired solution.


问:
Sending an array of parameters to bind_param
I have the parameters to send to a prepared statement in an array, I am using call_user_func_array and using it as such call_user_func_array(array($stmt, "bind_param"), array_merge(array($types), $params_fixed)), where $types contains the types and $params_fixed contains the parameters.

I ran it and got the error Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in ..., I searched for this error and an answer was to send the parameters by reference so I added an ampersand before the $params_fixed parameter however now I get the error Fatal error: Call-time pass-by-reference has been removed in ....

How can I resolve this issue? What am I missing here?

NOTE: Before learning I had to use call_user_func_array, I was using it as such $stmt->bind_param($types, ...$params_fixed)

NOTE 2: below is the code for filling the array to send

```<code>    $params_fixed = array();
    $types = "";
    if($param_count > 0) {
      foreach($params as $param) {
        switch(gettype($param)) {
          case "boolean":
            $types = $types . "i";
            $params_fixed[] = $param ? 1 : 0;
            break;
          case "integer":
            $types = $types . "i";
            $params_fixed[] = &$param;
            break;
          case "double":
            $types = $types . "d";
            $params_fixed[] = &$param;
            break;
          case "string":
            $types = $types . "s";
            $params_fixed[] = &$param;
            break;
          default:
            $types = $types . "s";
            $params_fixed[] = null;
            break;
        }
      }
    }
</code>```

NOTE 3: below is the code in question

```<code>public function query($sql, ...$params) {
  $param_num_sql = substr_count($sql, "?");
  $param_count = count($params);

  if($param_num_sql != $param_count) {
    $this->error = 'parameters don\'t match';
    return null;
  }

  $params_fixed = array();
  $types = "";
  if($param_count > 0) {
    foreach($params as $param) {
      $types = $types . "s";
      $params_fixed[] = &$param;

      // switch(gettype($param)) {
      //   case "boolean":
      //     $types = $types . "i";
      //     $params_fixed[] = $param ? 1 : 0;
      //     break;
      //   case "integer":
      //     $types = $types . "i";
      //     $params_fixed[] = $param;
      //     break;
      //   case "double":
      //     $types = $types . "d";
      //     $params_fixed[] = $param;
      //     break;
      //   case "string":
      //     $types = $types . "s";
      //     $params_fixed[] = $param;
      //     break;
      //   default:
      //     $types = $types . "s";
      //     $params_fixed[] = null;
      //     break;
      // }
    }
  }

  if($param_num_sql == 0) {
    $result = $this->conn->query($sql);
  } else {
    $stmt = $this->conn->prepare($sql);

    //call_user_func_array(array($stmt, "bind_param"), array_merge(array($types), $params_fixed));

    //if(!$stmt->bind_param($types, ...$params_fixed)) {

echo "<br/>types: $types<br/>";
echo '<br/>';
print_r($params_fixed);
echo '<br/>';

    if(!call_user_func_array(array($stmt, "bind_param"), array_merge(array($types), $params_fixed))) {
      // an error occurred
    }

    $stmt->execute();

    $result = $stmt->get_result();

    $stmt->close();
  }

  if($result != null && $result->num_rows > 0)
    return $result->fetch_all();
  else
    return null;
}
</code>```

and below is the code calling this method

$dbcon->query($query, $fname, $mname, $lname, $dob, $mobile, $home, $email, $area, $city, $street, $bldg, $floor, $car_capacity, $status, $prefer_act, $volunteer_days, $backup_days);

答:
try like this

```<code>        $mysqli = new mysqli('localhost', 'root','','mydb');

        $stmt=$mysqli->prepare("select * from blog where id=? and date=?");
            $title='1';
            $text='2016-04-07';
        call_user_func_array(array($stmt, "bind_param"),array_merge(array('ss'),array(&$title,&$text)));
        $stmt->execute();
        $result = $stmt->get_result();
        print_r($result->fetch_array());
        echo $stmt->error;
</code>```

ok if you have parameters coming from the array

```<code>        $mysqli = new mysqli('localhost', 'root','','jobspace');

        $stmt=$mysqli->prepare("select * from listings where listing_type_sid=? and user_sid=?");
            $title='6';
            $text='8';
            $arr=array($title,$text);
            foreach($arr as &$ar){
               $new[]=&$ar;
            }
        $types = implode(array_fill(0,count($arr),'s'));
        call_user_func_array(array($stmt, "bind_param"),array_merge(array($types),$new));
        $stmt->execute();
        $result = $stmt->get_result();
        print_r($result->fetch_array());
        echo $stmt->error;
</code>```

Body:
I have the parameters to send to a prepared statement in an array, I am using call_user_func_array and using it as such call_user_func_array(array($stmt, "bind_param"), array_merge(array($types), $params_fixed)), where $types contains the types and $params_fixed contains the parameters.

I ran it and got the error Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in ..., I searched for this error and an answer was to send the parameters by reference so I added an ampersand before the $params_fixed parameter however now I get the error Fatal error: Call-time pass-by-reference has been removed in ....

How can I resolve this issue? What am I missing here?

NOTE: Before learning I had to use call_user_func_array, I was using it as such $stmt->bind_param($types, ...$params_fixed)

NOTE 2: below is the code for filling the array to send

    $params_fixed = array();
    $types = "";
    if($param_count > 0) {
      foreach($params as $param) {
        switch(gettype($param)) {
          case "boolean":
            $types = $types . "i";
            $params_fixed[] = $param ? 1 : 0;
            break;
          case "integer":
            $types = $types . "i";
            $params_fixed[] = &$param;
            break;
          case "double":
            $types = $types . "d";
            $params_fixed[] = &$param;
            break;
          case "string":
            $types = $types . "s";
            $params_fixed[] = &$param;
            break;
          default:
            $types = $types . "s";
            $params_fixed[] = null;
            break;
        }
      }
    }

NOTE 3: below is the code in question

public function query($sql, ...$params) {
  $param_num_sql = substr_count($sql, "?");
  $param_count = count($params);

  if($param_num_sql != $param_count) {
    $this->error = 'parameters don\'t match';
    return null;
  }

  $params_fixed = array();
  $types = "";
  if($param_count > 0) {
    foreach($params as $param) {
      $types = $types . "s";
      $params_fixed[] = &$param;

      // switch(gettype($param)) {
      //   case "boolean":
      //     $types = $types . "i";
      //     $params_fixed[] = $param ? 1 : 0;
      //     break;
      //   case "integer":
      //     $types = $types . "i";
      //     $params_fixed[] = $param;
      //     break;
      //   case "double":
      //     $types = $types . "d";
      //     $params_fixed[] = $param;
      //     break;
      //   case "string":
      //     $types = $types . "s";
      //     $params_fixed[] = $param;
      //     break;
      //   default:
      //     $types = $types . "s";
      //     $params_fixed[] = null;
      //     break;
      // }
    }
  }

  if($param_num_sql == 0) {
    $result = $this->conn->query($sql);
  } else {
    $stmt = $this->conn->prepare($sql);

    //call_user_func_array(array($stmt, "bind_param"), array_merge(array($types), $params_fixed));

    //if(!$stmt->bind_param($types, ...$params_fixed)) {

echo "
types: $types
";
echo '
';
print_r($params_fixed);
echo '
';

    if(!call_user_func_array(array($stmt, "bind_param"), array_merge(array($types), $params_fixed))) {
      // an error occurred
    }

    $stmt->execute();

    $result = $stmt->get_result();

    $stmt->close();
  }

  if($result != null && $result->num_rows > 0)
    return $result->fetch_all();
  else
    return null;
}

and below is the code calling this method

$dbcon->query($query, $fname, $mname, $lname, $dob, $mobile, $home, $email, $area, $city, $street, $bldg, $floor, $car_capacity, $status, $prefer_act, $volunteer_days, $backup_days);

Body:
try like this

        $mysqli = new mysqli('localhost', 'root','','mydb');

        $stmt=$mysqli->prepare("select * from blog where id=? and date=?");
            $title='1';
            $text='2016-04-07';
        call_user_func_array(array($stmt, "bind_param"),array_merge(array('ss'),array(&$title,&$text)));
        $stmt->execute();
        $result = $stmt->get_result();
        print_r($result->fetch_array());
        echo $stmt->error;

ok if you have parameters coming from the array

        $mysqli = new mysqli('localhost', 'root','','jobspace');

        $stmt=$mysqli->prepare("select * from listings where listing_type_sid=? and user_sid=?");
            $title='6';
            $text='8';
            $arr=array($title,$text);
            foreach($arr as &$ar){
               $new[]=&$ar;
            }
        $types = implode(array_fill(0,count($arr),'s'));
        call_user_func_array(array($stmt, "bind_param"),array_merge(array($types),$new));
        $stmt->execute();
        $result = $stmt->get_result();
        print_r($result->fetch_array());
        echo $stmt->error;


问:
Two text boxes and many buttons python
I would like to press a button and have it print the location of the cursor X/Y coordinates as well as the content of the button in tkinter.

I'm new to python and I haven't found any way to do this. Can anyone help me finding the right start on this issue?

答:
You can use the bind the button click event to print the location clicked, here's an example of how you can do that.

```<code>import tkinter as tk

def print_location(event):
    print(event.x, event.y)
root = tk.Tk()
button = tk.Button(root, text='click me')
button.bind("<Button-1>", print_location)
button.pack()
root.mainloop()
</code>```

Note: using external modules such as pyautogui is not recommended and unnecessary.

Title: Two text boxes and many buttons python

Body:
You can use the bind the button click event to print the location clicked, here's an example of how you can do that.

import tkinter as tk

def print_location(event):
    print(event.x, event.y)
root = tk.Tk()
button = tk.Button(root, text='click me')
button.bind("<Button-1>", print_location)
button.pack()
root.mainloop()

Note: using external modules such as pyautogui is not recommended and unnecessary.


问:
Passing a integer through command line in C?
I was wondering if someone could explain how passing arguments through command line works? I'm really confused by how it works. Right now I'm trying to pass one integer into the main program. How would I go about doing this? </p>

<p>EDIT: keep getting the initialization makes integer from pointer without a cast [-Wint-conversion] error? </p>

```<code>#include <stdio.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{
  double r,area, circ;

  char a = argv[1];
  int num =  a - '0';

  printf("You have entered %d",num);

  r= num/2;
  area = PI * r * r;
  circ= 2 * PI * r;

  printf ("A circle with a diameter of %d ", num);
  printf ("has an area of %5.3lf cm2\n", area);
  printf ("and a circumference of %4.2lf cm.\n", circ);

  return (0);

}
</code>```

答:
The signature for the main function in C would be this:

```<code>int main(int argc, char *argv[]);
</code>```

argc is the number of arguments passed to your program, including the program name its self.

argv is an array containing each argument as a string of characters.

So if you invoked your program like this:

```<code>./program 10
</code>```

argc would be 2

argv[0] would be the string program

argv[1] would be the string 10

You could fix your code like this:

```<code>#include <stdio.h>
#include <stdlib.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{
  double r,area, circ;

  char *a = argv[1];
  int num = atoi(a);

  printf("You have entered %d",num);

  r= num/2;
  area = PI * r * r;
  circ= 2 * PI * r;

  printf ("A circle with a diameter of %d ", num);
  printf ("has an area of %5.3lf cm2\n", area);
  printf ("and a circumference of %4.2lf cm.\n", circ);

  return (0);

}
</code>```

You probably also want to add line breaks into your print statements for readability.

Body:
I was wondering if someone could explain how passing arguments through command line works? I'm really confused by how it works. Right now I'm trying to pass one integer into the main program. How would I go about doing this?

EDIT: keep getting the initialization makes integer from pointer without a cast [-Wint-conversion] error?

#include <stdio.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{
  double r,area, circ;

  char a = argv[1];
  int num =  a - '0';

  printf("You have entered %d",num);

  r= num/2;
  area = PI * r * r;
  circ= 2 * PI * r;

  printf ("A circle with a diameter of %d ", num);
  printf ("has an area of %5.3lf cm2\n", area);
  printf ("and a circumference of %4.2lf cm.\n", circ);

  return (0);

}

Body:
The signature for the main function in C would be this:

int main(int argc, char *argv[]);

argc is the number of arguments passed to your program, including the program name its self.

argv is an array containing each argument as a string of characters.

So if you invoked your program like this:

./program 10

argc would be 2

argv[0] would be the string program

argv[1] would be the string 10

You could fix your code like this:

#include <stdio.h>
#include <stdlib.h>
#define PI 3.1416
int
main (int argc, char *argv[])

{
  double r,area, circ;

  char *a = argv[1];
  int num = atoi(a);

  printf("You have entered %d",num);

  r= num/2;
  area = PI * r * r;
  circ= 2 * PI * r;

  printf ("A circle with a diameter of %d ", num);
  printf ("has an area of %5.3lf cm2\n", area);
  printf ("and a circumference of %4.2lf cm.\n", circ);

  return (0);

}

You probably also want to add line breaks into your print statements for readability.

ContentLicense: CC BY-SA 4.0


问:
Can we store value of @yield in a variable
I have a simple question can we store the value that will be yielded in a variable.

for instance an example

```<code>$var = @yield('title')
</code>```

If no, then is there any way to get the value of this yield

答:
Yes you can retrieve the value of an yield which is defined by a section using something like the following, for example:

```<code>// Assumed you've the following in your view: @section('title', 'Some Title')

$title = app()->view->getSections()['title']; // Some Title
</code>```

Basically, the app()->view->getSections() will return you an associative array of all the sections so, to get a specific section, all you need to get an specific index from the array. From the view, you can access the app using the global $app variable, i.e: $app->view or $app['view'].

Body:
I have a simple question can we store the value that will be yielded in a variable.

for instance an example

$var = @yield('title')

If no, then is there any way to get the value of this yield

Body:
Yes you can retrieve the value of an yield which is defined by a section using something like the following, for example:

// Assumed you've the following in your view: @section('title', 'Some Title')

$title = app()->view->getSections()['title']; // Some Title

Basically, the app()->view->getSections() will return you an associative array of all the sections so, to get a specific section, all you need to get an specific index from the array. From the view, you can access the app using the global $app variable, i.e: $app->view or $app['view'].


问:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name - Spring security
I am trying to use spring security, spring mvc with maven. So I have written my xml files like this:

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mywebsite</groupId>
    <artifactId>emusicstore</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.4.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.0-api -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.194</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.1.4.RELEASE</version>
        </dependency>
    </dependencies>

</project>
</code>```

My web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml,
            /WEB-INF/applicationContext.xml
        </param-value>
    </context-param>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
</code>```

My applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:tcp://localhost/~/test" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.emusicstore</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1024000" />
    </bean>

    <security:http auto-config="true">
        <security:intercept-url pattern="/admin/**" access="ROLE_USER" />
        <security:form-login
            login-page="/login"
            default-target-url="/admin/"
            authentication-failure-url="login?error"
            username-parameter="username"
            password-parameter="password" />
        <security:logout
            logout-success-url="/login?logout" />
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="dataSource"
                                        authorities-by-username-query="SELECT username authority FROM authorities WHERE username=?"
                                        users-by-username-query="SELECT username, password, enabled FROM users WHERE username=?" />
        </security:authentication-provider>
    </security:authentication-manager>
</beans>
</code>```

My dispatcher-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.emusicstore" />

    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />

    <tx:annotation-driven />
</beans>
</code>```

Here is full error stacktrace

```<code>01-Apr-2017 18:39:07.910 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping': Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.support.AopUtils.selectInvocableMethod(Ljava/lang/reflect/Method;Ljava/lang/Class;)Ljava/lang/reflect/Method;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4754)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5216)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
    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:498)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:482)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
    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:498)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
    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:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: org.springframework.aop.support.AopUtils.selectInvocableMethod(Ljava/lang/reflect/Method;Ljava/lang/Class;)Ljava/lang/reflect/Method;
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:248)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:214)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:184)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:127)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 57 more
</code>```

Everything was working fine, but then I tried to add spring security and I got this error. Thank you for your help in advance.

One more thing, IDEA that I am using is, Intellij 2017.1. Just in case that's relevant somehow.

答:
The exception message is clear. Something is trying to use a method which does not exist. That is because you have a version mismatch. You are using:

```<code>spring-core    --> 4.3.7.RELEASE
spring-orm     --> 4.3.7.RELEASE

spring-context --> 4.1.4.RELEASE

spring-security-xxx --> 3.1.4.RELEASE
</code>```

Checking the dependencies you could see spring-orm 4.3.7 has spring-aop 4.3.7 as optional dependency, however, the spring security version you are using depends on spring-aop 3.0.7. Also, checking the spring code you can find the method your log is complaining is not available until spring 4.3

spring-framework AopUtils code

So, I guess, when resolving the dependencies spring-oap 3.0.7 is being the one selected and there you have your exception.

If you are using maven you can check the dependency tree for spring-oap using the command:

```<code>mvn dependency:tree -Dverbose -Dincludes=spring-oap
</code>```

That will show you what version has been omitted for conflict with X version.

Summing up, and to solve your problem, you should use the same spring version when possible, or at least one using same dependencies. So, in your case, change your spring security dependencies to use 4.2.2. It should solve your problem.

Spring-context depends on spring-aop as well, so you have to change spring-context dependency to use version 4.3.7, the same version you are using for main spring artifacts.

Body:
I am trying to use spring security, spring mvc with maven. So I have written my xml files like this:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mywebsite</groupId>
    <artifactId>emusicstore</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.194</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.1.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.1.4.RELEASE</version>
        </dependency>
    </dependencies>

</project>

My web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml,
            /WEB-INF/applicationContext.xml
        </param-value>
    </context-param>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

My applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:tcp://localhost/~/test" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.emusicstore</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1024000" />
    </bean>

    <security:http auto-config="true">
        <security:intercept-url pattern="/admin/**" access="ROLE_USER" />
        <security:form-login
            login-page="/login"
            default-target-url="/admin/"
            authentication-failure-url="login?error"
            username-parameter="username"
            password-parameter="password" />
        <security:logout
            logout-success-url="/login?logout" />
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="dataSource"
                                        authorities-by-username-query="SELECT username authority FROM authorities WHERE username=?"
                                        users-by-username-query="SELECT username, password, enabled FROM users WHERE username=?" />
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

My dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.emusicstore" />

    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />

    <tx:annotation-driven />
</beans>

Here is full error stacktrace

01-Apr-2017 18:39:07.910 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping': Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.support.AopUtils.selectInvocableMethod(Ljava/lang/reflect/Method;Ljava/lang/Class;)Ljava/lang/reflect/Method;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4754)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5216)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
    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:498)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:482)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
    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:498)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
    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:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError: org.springframework.aop.support.AopUtils.selectInvocableMethod(Ljava/lang/reflect/Method;Ljava/lang/Class;)Ljava/lang/reflect/Method;
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:248)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:214)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:184)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:127)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 57 more

Everything was working fine, but then I tried to add spring security and I got this error. Thank you for your help in advance.

One more thing, IDEA that I am using is, Intellij 2017.1. Just in case that's relevant somehow.

Body:
The exception message is clear. Something is trying to use a method which does not exist. That is because you have a version mismatch. You are using:

spring-core    --> 4.3.7.RELEASE
spring-orm     --> 4.3.7.RELEASE

spring-context --> 4.1.4.RELEASE

spring-security-xxx --> 3.1.4.RELEASE

Checking the dependencies you could see spring-orm 4.3.7 has spring-aop 4.3.7 as optional dependency, however, the spring security version you are using depends on spring-aop 3.0.7. Also, checking the spring code you can find the method your log is complaining is not available until spring 4.3

spring-framework AopUtils code

So, I guess, when resolving the dependencies spring-oap 3.0.7 is being the one selected and there you have your exception.

If you are using maven you can check the dependency tree for spring-oap using the command:

mvn dependency:tree -Dverbose -Dincludes=spring-oap

That will show you what version has been omitted for conflict with X version.

Summing up, and to solve your problem, you should use the same spring version when possible, or at least one using same dependencies. So, in your case, change your spring security dependencies to use 4.2.2. It should solve your problem.

Spring-context depends on spring-aop as well, so you have to change spring-context dependency to use version 4.3.7, the same version you are using for main spring artifacts.


问:
Can GlassFish 2 be configured to make a webservice accessible **only** from some specific port?
Currently we serve some web applications in a domain on port 80. This port is accessible from the internet.

Now there should be deployed some EJB wich expose some of their methods as webservices using the @WebMethod annotation. These should not be accessibe from the (public) port 80, but only from port 8000, which can be accessed only from the internal network.

I set up a new virtual server named "internal" which uses a http-listener that listens on port 8000:

```<code><virtual-server hosts="${com.sun.aas.hostName}" http-listeners="http-listener-3" id="internal" log-file="${com.sun.aas.instanceRoot}/logs/server.log" state="on">
          <property name="sso-enabled" value="false"/>
          <property name="docroot" value="${com.sun.aas.instanceRoot}/docroot"/>
          <property name="accesslog" value="${com.sun.aas.instanceRoot}/logs/access"/>
</virtual-server>

<http-listener acceptor-threads="1" address="0.0.0.0" blocking-enabled="false" default-virtual-server="internal" enabled="true" family="inet" id="http-listener-3" port="8000" security-enabled="false" server-name="" xpowered-by="false">
          <property name="proxiedProtocols" value="ws/tcp"/>
</http-listener>
</code>```

Then I assigned this virtual server to the enterprise application that hosts the service by setting the virtual-servers attribute.

```<code><application-ref disable-timeout-in-minutes="30" enabled="true" lb-enabled="false" ref="myapp" virtual-servers="internal"/>
</code>```

The webservices are available now both on port 80 and 8000, but what is needed is that they are available on port 8000 only, not from 80. Is there a way to achieve this in GlassFish 2 using a single domain? Or must a second domain be used?

答: You need to pull your webMethods out and place them into their own app. Then when you deploy the app you can manage (the target tab) which server / virtual servers they end up on.</p>

ContentLicense: CC BY-SA 2.5

Body:
Currently we serve some web applications in a domain on port 80. This port is accessible from the internet.

Now there should be deployed some EJB wich expose some of their methods as webservices using the @WebMethod annotation. These should not be accessibe from the (public) port 80, but only from port 8000, which can be accessed only from the internal network.

I set up a new virtual server named "internal" which uses a http-listener that listens on port 8000:

<virtual-server hosts="${com.sun.aas.hostName}" http-listeners="http-listener-3" id="internal" log-file="${com.sun.aas.instanceRoot}/logs/server.log" state="on">
          <property name="sso-enabled" value="false"/>
          <property name="docroot" value="${com.sun.aas.instanceRoot}/docroot"/>
          <property name="accesslog" value="${com.sun.aas.instanceRoot}/logs/access"/>
</virtual-server>

<http-listener acceptor-threads="1" address="0.0.0.0" blocking-enabled="false" default-virtual-server="internal" enabled="true" family="inet" id="http-listener-3" port="8000" security-enabled="false" server-name="" xpowered-by="false">
          <property name="proxiedProtocols" value="ws/tcp"/>
</http-listener>

Then I assigned this virtual server to the enterprise application that hosts the service by setting the virtual-servers attribute.

<application-ref disable-timeout-in-minutes="30" enabled="true" lb-enabled="false" ref="myapp" virtual-servers="internal"/>

The webservices are available now both on port 80 and 8000, but what is needed is that they are available on port 8000 only, not from 80. Is there a way to achieve this in GlassFish 2 using a single domain? Or must a second domain be used?


问:
Recursive binary search / C
I've been trying to write a binary search using recursion (a new concept for me) all day in C. I researched quite a lot and came up with this:

```<code>int binary_search(int *parr, int value, int left, int right){
    int middle = (left+right)/2;
    if(*(parr+middle)==value){
        return 1;
    }
    if(right<left){
        return 0;
    }
    if(*(parr+middle)>value){
        return binary_search(*parr, value, left, middle-1);
    }
    else{
        return binary_search(*parr, value, middle+1, right);
    }
}
</code>```

And this is my main function:

```<code>int main()
{
    int arr[maxbr],n, i, g;
    do{
        printf("\n n=");
        scanf("%d", &n);
    } while(n>maxbr);

    for(i=0; i<n; i++){
        printf("\n a[%d]", i);
        scanf("%d", &arr[i]);
    }

    g = binary_search(arr, 5, 0, n-1);
    printf(" %d", g);
}
</code>```

This crashes after I enter n and the array, for some reason. Thanks in advance for the help!

答:
You probably want:

```<code> return binary_search(parr, value, left, middle-1);
</code>```

Without the * in front of parr.  *parr is the first int, parr is the array.

(fix the other one too)

Title: Recursive binary search / C

Body:
I've been trying to write a binary search using recursion (a new concept for me) all day in C. I researched quite a lot and came up with this:

int binary_search(int *parr, int value, int left, int right){
    int middle = (left+right)/2;
    if(*(parr+middle)==value){
        return 1;
    }
    if(right<left){
        return 0;
    }
    if(*(parr+middle)>value){
        return binary_search(*parr, value, left, middle-1);
    }
    else{
        return binary_search(*parr, value, middle+1, right);
    }
}

And this is my main function:

int main()
{
    int arr[maxbr],n, i, g;
    do{
        printf("\n n=");
        scanf("%d", &n);
    } while(n>maxbr);

    for(i=0; i<n; i++){
        printf("\n a[%d]", i);
        scanf("%d", &arr[i]);
    }

    g = binary_search(arr, 5, 0, n-1);
    printf(" %d", g);
}

This crashes after I enter n and the array, for some reason. Thanks in advance for the help!

Body:
You probably want:

 return binary_search(parr, value, left, middle-1);

Without the * in front of parr.  *parr is the first int, parr is the array.

(fix the other one too)


问:
How does Kotlin property access syntax work for Java classes (i.e. EditText setText)?
I'm trying to switch my Android project to Kotlin. I have an EditText (a subclass of TextView) for which I want to set a hint and text programmatically. The hint works as expected. For text, though, I'm getting a type mismatch exception if I try to do it using Kotlin setter syntax:

```<code>    val test = EditText(context)

    test.setHint("hint")    // Lint message: "Use property access syntax"
    test.hint = "hint"      // ok

    test.setText("text")    // ok (no lint message)
    test.text = "text"      // Type mismatch: inferred type is kotlin.String but android.text.Editable! was expected
</code>```

If we look at the declaration, we'll find identical signatures inherited from TextView:

```<code>    public final void setHint(CharSequence hint)

    public final void setText(CharSequence text)
</code>```

I had an impression that x.y = z was a shortcut for x.setY(z) but apparently that impression was wrong. setText() is treated as a normal method rather than a setter, but what's the difference between these two methods that makes the compiler behave differently? The only one I can think of is that TextView has an mHint property but I don't think it might be the case.

Another thing I don't quite understand is, where does android.text.Editable come from? There is no corresponding setText(Editable) method, nor is there a public field of this type.

答:
To avoid type mismatch, you can use the Factory inner class of Editable class.
So you can do now something like:  </p>

```<code>textview.text = Editable.Factory.getInstance().newEditable("your text")
</code>```

Body:
I'm trying to switch my Android project to Kotlin. I have an EditText (a subclass of TextView) for which I want to set a hint and text programmatically. The hint works as expected. For text, though, I'm getting a type mismatch exception if I try to do it using Kotlin setter syntax:

    val test = EditText(context)

    test.setHint("hint")    // Lint message: "Use property access syntax"
    test.hint = "hint"      // ok

    test.setText("text")    // ok (no lint message)
    test.text = "text"      // Type mismatch: inferred type is kotlin.String but android.text.Editable! was expected

If we look at the declaration, we'll find identical signatures inherited from TextView:

    public final void setHint(CharSequence hint)

    public final void setText(CharSequence text)

I had an impression that x.y = z was a shortcut for x.setY(z) but apparently that impression was wrong. setText() is treated as a normal method rather than a setter, but what's the difference between these two methods that makes the compiler behave differently? The only one I can think of is that TextView has an mHint property but I don't think it might be the case.

Another thing I don't quite understand is, where does android.text.Editable come from? There is no corresponding setText(Editable) method, nor is there a public field of this type.

Body:
To avoid type mismatch, you can use the Factory inner class of Editable class.
So you can do now something like:

textview.text = Editable.Factory.getInstance().newEditable("your text")


问:
How to get DataGridView cell value?
I need to compare my array string with DataGridView cell value

```<code>string z = DataGridView->Rows[e->RowIndex]->Cells[1]->Value.ToString();
</code>```

I'm getting a problem:

IntelliSense: expression must have class type

答:
I figured out the answer if anyone else needs solution here it is</p>

```<code>String^ z = System::Convert::ToString(Grid_Darbuotojai->Rows[e->RowIndex]->Cells[1]->Value);
</code>```

Title: How to get DataGridView cell value?

Body:
I need to compare my array string with DataGridView cell value

string z = DataGridView->Rows[e->RowIndex]->Cells[1]->Value.ToString();

I'm getting a problem:

IntelliSense: expression must have class type

Body:
I figured out the answer if anyone else needs solution here it is

String^ z = System::Convert::ToString(Grid_Darbuotojai->Rows[e->RowIndex]->Cells[1]->Value);


问:
node.js, for-loops, and twitter API
I am trying to only fetch the text of the tweets for a twitter bot I am working on (keep in mind twitter's API docs are worse than Oracles, which I never thought that was possible, anyway). I was using the following link to make my bot https://community.risingstack.com/node-js-twitter-bot-tutorial/

I assume that it is within their randomTweet function where they get the index from.

```<code>function ranDom (arr) {
  var index = Math.floor(Math.random()*arr.length);
  return arr[index];
};
</code>```

and later in their code they would reference it using

```<code>Twitter.post('favorites/create', {id: randomTweet.id_str}
</code>```

I am trying to simply access the text using a regular foreach loop (seeing as, as far as I am aware, node.js has no concept of an indexed for loop) as follows:

```<code>var tweet = data.statuses;

    for(var result in tweet) {
        console.log(result.id_str);
    }
</code>```

However, all I am getting is undefined, and I am not certain as to why since for them it worked fine when they passed in a specific index.

答: To get the index use Object.keys(tweet).indexOf(result)

Title: node.js, for-loops, and twitter API

Body:
I am trying to only fetch the text of the tweets for a twitter bot I am working on (keep in mind twitter's API docs are worse than Oracles, which I never thought that was possible, anyway). I was using the following link to make my bot https://community.risingstack.com/node-js-twitter-bot-tutorial/

I assume that it is within their randomTweet function where they get the index from.

function ranDom (arr) {
  var index = Math.floor(Math.random()*arr.length);
  return arr[index];
};

and later in their code they would reference it using

Twitter.post('favorites/create', {id: randomTweet.id_str}

I am trying to simply access the text using a regular foreach loop (seeing as, as far as I am aware, node.js has no concept of an indexed for loop) as follows:

var tweet = data.statuses;

    for(var result in tweet) {
        console.log(result.id_str);
    }

However, all I am getting is undefined, and I am not certain as to why since for them it worked fine when they passed in a specific index.


问:
Error with OnTouchListener
I get an error trying to implement an OnTouchListener:

The method onTouch(View, MotionEvent)
  of type new View.OnTouchListener(){}
  must override a superclass method

I have no idea why it's not working as it seems I'm overrriding the method correctly:

```<code>public class MyActivity extends Activity
{
    ...creation code etc...

    OnTouchListener mTouchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
                 ...touch code...
            }
        }
}
</code>```

Any ideas on how I can debug this?

答:
```<code>View.OnTouchListener mTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return false;
        }
    };
</code>```

that compiles just fine, are you sure that there are no syntax errors ? What are you compiler settings ? java 5 or 6 ?

Title: Error with OnTouchListener

Body:
I get an error trying to implement an OnTouchListener:

The method onTouch(View, MotionEvent)
  of type new View.OnTouchListener(){}
  must override a superclass method

I have no idea why it's not working as it seems I'm overrriding the method correctly:

public class MyActivity extends Activity
{
    ...creation code etc...

    OnTouchListener mTouchListener = new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
                 ...touch code...
            }
        }
}

Any ideas on how I can debug this?

Body:
View.OnTouchListener mTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return false;
        }
    };

that compiles just fine, are you sure that there are no syntax errors ? What are you compiler settings ? java 5 or 6 ?


问:
Using a for loop on string values of my array and getting a string value back
Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:

```<code>var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
</code>```

Now here's the for loop I'm using:

```<code>for (i = 0; i < stuff.length; i++) {
  console.log(i);
};
</code>```

All I get in my chrome developer console is 0, 1, 2, 3.

How do I get each string value to show up?

答:
You'll have to create a loop to access all members in the array.
For simple purposes, either:

```<code>for(i = 0; i < stuff.length; i++)
{
   console.log(stuff[i]);
}
</code>```

Or you can directly have the value using a for..in loop

```<code>for(i in stuff)
{
   console.log(i);
}
</code>```

Both methods will produce the same output as all of the elements of the array are set to a value.

There are many methods to loop over an array in JavaScript and each of them has its advantages and disadvantages.

Body:
Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:

var stuff = ["ken", "kenneth", "kenny", "kennayyy"];

Now here's the for loop I'm using:

for (i = 0; i < stuff.length; i++) {
  console.log(i);
};

All I get in my chrome developer console is 0, 1, 2, 3.

How do I get each string value to show up?

Body:
You'll have to create a loop to access all members in the array.
For simple purposes, either:

for(i = 0; i < stuff.length; i++)
{
   console.log(stuff[i]);
}

Or you can directly have the value using a for..in loop

for(i in stuff)
{
   console.log(i);
}

Both methods will produce the same output as all of the elements of the array are set to a value.

There are many methods to loop over an array in JavaScript and each of them has its advantages and disadvantages.


问:
PostgreSQL, trigrams and similarity
Just testing PostgreSQL 9.6.2 on my Mac and playing with Ngrams.
Assuming there is a GIN trigram index on winery field.

The limit for similarity (I know this is deprecated):

```<code>SELECT set_limit(0.5);
</code>```

I'm building a trigram search on 2,3M row table.

My select code:

```<code>SELECT winery, similarity(winery, 'chateau chevla blanc') AS similarity
FROM usr_wines
WHERE status=1 AND winery % 'chateau chevla blanc'
ORDER BY similarity DESC;
</code>```

My results (329 ms on my mac):

```<code>Chateau ChevL Blanc 0,85
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc,  0,736842
Chateau Blanc   0,736842
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc (7)    0,666667
Chateau Cheval Blanc Cbo    0,64
Chateau Du Cheval Blanc 0,64
Chateau Du Cheval Blanc 0,64
</code>```

Well, I don't understand how can "Chateau blanc" have a similarity > to "Chateau Cheval Blanc" in this case ? I understand that the 2 words are the exact same "chateau" and "blanc", but there is no other word "cheval".

Also why "Chateau ChevL Blanc" is first ? A letter "a" is missing !

Well, my goal is to match all possible duplicates when I give a winery name, even if it's mispelled. What did I miss ?

答:
The trigram algorithm should be the more accurate the less is the difference in length of compared strings. You can modify the algorithm to compensate the effect of length difference.

The following exemplary function reduces the similarity by 1% for the difference of 1 character in string lenghts. This means that it favors strings of the same (similar) length.

```<code>create or replace function corrected_similarity(str1 text, str2 text)
returns float4 language sql as $$
    select similarity(str1, str2)* (1- abs(length(str1)-length(str2))/100.0)::float4
$$;

select
    winery,
    similarity(winery, 'chateau chevla blanc') as similarity,
    corrected_similarity(winery, 'chateau chevla blanc') as corrected_similarity
from usr_wines
where winery % 'chateau chevla blanc'
order by corrected_similarity desc;

          winery          | similarity | corrected_similarity
--------------------------+------------+----------------------
 Chateau ChevL Blanc      |       0.85 |               0.8415
 Chateau Cheval Blanc     |   0.727273 |             0.727273
 Chateau Cheval Blanc     |   0.727273 |             0.727273
 Chateau Cheval Blanc     |   0.727273 |             0.727273
 Chateau Blanc,           |   0.736842 |             0.692632
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Cheval Blanc (7) |   0.666667 |                 0.64
 Chateau Du Cheval Blanc  |       0.64 |               0.6208
 Chateau Du Cheval Blanc  |       0.64 |               0.6208
 Chateau Cheval Blanc Cbo |       0.64 |               0.6144
(14 rows)
</code>```

In a similar way you can correct the standard similarity by, for example, how many initial characters are identical (thought the function will be a bit more complicated).

Title: PostgreSQL, trigrams and similarity

Body:
Just testing PostgreSQL 9.6.2 on my Mac and playing with Ngrams.
Assuming there is a GIN trigram index on winery field.

The limit for similarity (I know this is deprecated):

SELECT set_limit(0.5);

I'm building a trigram search on 2,3M row table.

My select code:

SELECT winery, similarity(winery, 'chateau chevla blanc') AS similarity
FROM usr_wines
WHERE status=1 AND winery % 'chateau chevla blanc'
ORDER BY similarity DESC;

My results (329 ms on my mac):

Chateau ChevL Blanc 0,85
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc,  0,736842
Chateau Blanc   0,736842
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc (7)    0,666667
Chateau Cheval Blanc Cbo    0,64
Chateau Du Cheval Blanc 0,64
Chateau Du Cheval Blanc 0,64

Well, I don't understand how can "Chateau blanc" have a similarity > to "Chateau Cheval Blanc" in this case ? I understand that the 2 words are the exact same "chateau" and "blanc", but there is no other word "cheval".

Also why "Chateau ChevL Blanc" is first ? A letter "a" is missing !

Well, my goal is to match all possible duplicates when I give a winery name, even if it's mispelled. What did I miss ?

Body:
The trigram algorithm should be the more accurate the less is the difference in length of compared strings. You can modify the algorithm to compensate the effect of length difference.

The following exemplary function reduces the similarity by 1% for the difference of 1 character in string lenghts. This means that it favors strings of the same (similar) length.

create or replace function corrected_similarity(str1 text, str2 text)
returns float4 language sql as $$
    select similarity(str1, str2)* (1- abs(length(str1)-length(str2))/100.0)::float4
$$;

select
    winery,
    similarity(winery, 'chateau chevla blanc') as similarity,
    corrected_similarity(winery, 'chateau chevla blanc') as corrected_similarity
from usr_wines
where winery % 'chateau chevla blanc'
order by corrected_similarity desc;

          winery          | similarity | corrected_similarity
--------------------------+------------+----------------------
 Chateau ChevL Blanc      |       0.85 |               0.8415
 Chateau Cheval Blanc     |   0.727273 |             0.727273
 Chateau Cheval Blanc     |   0.727273 |             0.727273
 Chateau Cheval Blanc     |   0.727273 |             0.727273
 Chateau Blanc,           |   0.736842 |             0.692632
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Blanc            |   0.736842 |             0.685263
 Chateau Cheval Blanc (7) |   0.666667 |                 0.64
 Chateau Du Cheval Blanc  |       0.64 |               0.6208
 Chateau Du Cheval Blanc  |       0.64 |               0.6208
 Chateau Cheval Blanc Cbo |       0.64 |               0.6144
(14 rows)

In a similar way you can correct the standard similarity by, for example, how many initial characters are identical (thought the function will be a bit more complicated).