问:
Tracing Guarded Blocks in Java
I've been struggling for a couple days with this simple concurrency Oracle problem which models a Producer/Consumer. This is the first time I've used guarded blocks, wait, and notifyAll. I know what these methods do, however; I don't what steps occur first. I'm going to trace the problem as best as I can down below and you guys can tell me if I'm right.

The Producer/Consumer thread is started from the main thread. Each is given the same Drop instance.

If the Consumer Thread is faster then the Producer, its acquires the intrinsic lock on drop and tries to print out the message from drop.take() in a loop. However, the producer has not given the consumer the message because empty is true. This results in the thread being suspended and the lock is released. It is now waiting.

The Producer Thread calls drop.put() in a loop. It acquires the intrinsic lock on drop and continues the method because empty is true and it needs to prepare the message for Consumer. It sets empty to false and stores the message. notifyAll() is called which wakes up the Consumer Thread. The Producer is also waiting because empty is now false and the lock is released.

Since the drop.take() was notified and Producer had the intrinsic lock on drop, it wakes up the method. Empty is set to true and the message is returned and printed in the loop. It now notifies the Producer thread to wake up because it needs a new message.

Producer has been waiting. Since empty is true and the thread has been notified(and the lock was accessed), it can now wake up and produces another message.

Drop Class

package Store;

public class Drop {
    // Message sent from producer
    // to consumer.
    private String message;
    // True if consumer should wait
    // for producer to send message,
    // false if producer should wait for
    // consumer to retrieve message.
    private boolean empty = true;

    public synchronized String take() {
        // Wait until message is
        // available.
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        // Toggle status.
        empty = true;
        // Notify producer that
        // status has changed.
        notifyAll();
        return message;
    }

    public synchronized void put(String message) {
        // Wait until message has
        // been retrieved.
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        // Toggle status.
        empty = false;
        // Store message.
        this.message = message;
        // Notify consumer that status
        // has changed.
        notifyAll();
    }
}```
</div>
</div>
</p>

<p>Consumer Class:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>package Store;

import java.util.Random;

public class Consumer implements Runnable {
    private Drop drop;

    public Consumer(Drop drop) {
        this.drop = drop;
    }

    public void run() {
        Random random = new Random();
        for (String message = drop.take();
             ! message.equals("DONE");
             message = drop.take()) {
            System.out.format("MESSAGE RECEIVED: %s%n", message);
            try {
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {}
        }
    }
}</code>```

Producer Class:

package Store;

import java.util.Random;

public class Producer implements Runnable {
    private Drop drop;

    public Producer(Drop drop) {
        this.drop = drop;
    }

    public void run() {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };
        Random random = new Random();

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            drop.put(importantInfo[i]);
            try {
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {}
        }
        drop.put("DONE");
    }
}```
</div>
</div>
</p>

<p>Main Thread:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public class ProducerConsumerExample {
    public static void main(String[] args) {
        Drop drop = new Drop();
        (new Thread(new Producer(drop))).start();
        (new Thread(new Consumer(drop))).start();
    }
}</code>```

答:
I don't have a full answer, but I do have a couple of observations.

The while wrapping the wait will lead to exceptions if they ever loop. wait requires a lock, but wait releases the lock. Fortunately, you should not experience that behavior.

You may run into problems with your instance variables not updating across threads. You synchronize, then wait. That provides an opportunity for those variables to have different values. Marking them volatile would help with that.

You didn't say what your code actually does...

Title: Tracing Guarded Blocks in Java

Body:
I've been struggling for a couple days with this simple concurrency Oracle problem which models a Producer/Consumer. This is the first time I've used guarded blocks, wait, and notifyAll. I know what these methods do, however; I don't what steps occur first. I'm going to trace the problem as best as I can down below and you guys can tell me if I'm right.

The Producer/Consumer thread is started from the main thread. Each is given the same Drop instance.

If the Consumer Thread is faster then the Producer, its acquires the intrinsic lock on drop and tries to print out the message from drop.take() in a loop. However, the producer has not given the consumer the message because empty is true. This results in the thread being suspended and the lock is released. It is now waiting.

The Producer Thread calls drop.put() in a loop. It acquires the intrinsic lock on drop and continues the method because empty is true and it needs to prepare the message for Consumer. It sets empty to false and stores the message. notifyAll() is called which wakes up the Consumer Thread. The Producer is also waiting because empty is now false and the lock is released.

Since the drop.take() was notified and Producer had the intrinsic lock on drop, it wakes up the method. Empty is set to true and the message is returned and printed in the loop. It now notifies the Producer thread to wake up because it needs a new message.

Producer has been waiting. Since empty is true and the thread has been notified(and the lock was accessed), it can now wake up and produces another message.

Drop Class

package Store;

public class Drop {
    // Message sent from producer
    // to consumer.
    private String message;
    // True if consumer should wait
    // for producer to send message,
    // false if producer should wait for
    // consumer to retrieve message.
    private boolean empty = true;

    public synchronized String take() {
        // Wait until message is
        // available.
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        // Toggle status.
        empty = true;
        // Notify producer that
        // status has changed.
        notifyAll();
        return message;
    }

    public synchronized void put(String message) {
        // Wait until message has
        // been retrieved.
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {}
        }
        // Toggle status.
        empty = false;
        // Store message.
        this.message = message;
        // Notify consumer that status
        // has changed.
        notifyAll();
    }
}

Consumer Class:

package Store;

import java.util.Random;

public class Consumer implements Runnable {
    private Drop drop;

    public Consumer(Drop drop) {
        this.drop = drop;
    }

    public void run() {
        Random random = new Random();
        for (String message = drop.take();
             ! message.equals("DONE");
             message = drop.take()) {
            System.out.format("MESSAGE RECEIVED: %s%n", message);
            try {
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {}
        }
    }
}

Producer Class:

package Store;

import java.util.Random;

public class Producer implements Runnable {
    private Drop drop;

    public Producer(Drop drop) {
        this.drop = drop;
    }

    public void run() {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };
        Random random = new Random();

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            drop.put(importantInfo[i]);
            try {
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {}
        }
        drop.put("DONE");
    }
}

Main Thread:

public class ProducerConsumerExample {
    public static void main(String[] args) {
        Drop drop = new Drop();
        (new Thread(new Producer(drop))).start();
        (new Thread(new Consumer(drop))).start();
    }
}


来源: stackexchange

问:
Cannot Open Source File
I am attempting to open MSO.dll for a project written in C++ involving Excel automation. However, when I attempt to #import the MSO.dll, I get a "cannot open source file" error. I have added the file path to both the additional include directories (in Project -> Properties -> Configuration Properties -> C/C++ -> General) and the linker additional include directories.

Here is my code so far:

```<code>#pragma region Includes
#include <stdio.h>
#include <windows.h>
//#include "Solution1.h"
#pragma endregion

#pragma region Import the type libraries

#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE12\\MSO.DLL" \
    rename("RGB", "MSORGB") \
    rename("DocumentProperties", "MSODocumentProperties")

using namespace Office;
</code>```

答:
Is the path correct? This path should vary based upon Windows bitness and Office version. Specifically, on my Win64 machine with Office 2016, this file exists at

```<code>"C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\OFFICE16\\MSO.DLL"
</code>```

Here's a quick way to search for this file on your C: drive. Just open a command line and run the following. Copy and paste the path (you don't even really need to escape the backslashes, since paths in #include and #import directives are not treated as C++ string literals).

```<code>attrib /s c:\mso.dll
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cannot Open Source File

Body:
I am attempting to open MSO.dll for a project written in C++ involving Excel automation. However, when I attempt to #import the MSO.dll, I get a "cannot open source file" error. I have added the file path to both the additional include directories (in Project -> Properties -> Configuration Properties -> C/C++ -> General) and the linker additional include directories.

Here is my code so far:

#pragma region Includes
#include <stdio.h>
#include <windows.h>
//#include "Solution1.h"
#pragma endregion

#pragma region Import the type libraries

#import "C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE12\\MSO.DLL" \
    rename("RGB", "MSORGB") \
    rename("DocumentProperties", "MSODocumentProperties")

using namespace Office;

Body:
Is the path correct? This path should vary based upon Windows bitness and Office version. Specifically, on my Win64 machine with Office 2016, this file exists at

"C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\OFFICE16\\MSO.DLL"

Here's a quick way to search for this file on your C: drive. Just open a command line and run the following. Copy and paste the path (you don't even really need to escape the backslashes, since paths in #include and #import directives are not treated as C++ string literals).

attrib /s c:\mso.dll


问:
Foward declaration of classes in Python
The following program can run successfully:

```<code>class Simple(object):
    def __init__(self, name):
      self.name = name

    def __add__(self, other):
      c = Composite()
      c._members.append(self)
      c._members.append(other)
      return c

    def __repr__(self):
      return "Simple('%s')" % self.name

class Composite(object):
    def __init__(self):
      self._members = []

    def __add__(self, obj):
      if isinstance(obj, Simple):
        out = Composite()
        out._members = [k for k in self._members] + [obj]
      elif isinstance(obj, Composite):
        out = Composite()
        out._members = [k for k in self._members + obj._members]
      else:
        raise TypeError
      return out

if __name__ == "__main__":
    s1 = Simple('one')
    s2 = Simple('two')
    s3 = Simple('three')
    c1 = s1 + s2
    c2 = c1 + s3
    print c1._members
    print c2._members
    # output:
    # [Simple('one'), Simple('two')]
    # [Simple('one'), Simple('two'), Simple('three')]
</code>```

I would like to keep the definition of Simple, Composite, and __main__ in three different files, but I cannot do it because I cannot import Simple into composite.py and I cannot import Composite into simple.py.

How would you modify the class definition such that you can keep separate files?

Thank you.

PS. I've read several answers related to "forward declaration" but could not find an answer to my specific problem.

答:
Since none of the references are needed until the methods are called, circular imports can work here. The trick is to use fully-qualified references.

```<code>import composite

class Simple(object):
   ...
  def __add__(self, other):
    c = composite.Composite()
    c._members.append(self)
    c._members.append(other)
    return c
</code>```

ContentLicense: CC BY-SA 2.5

Title: Foward declaration of classes in Python

Body:
The following program can run successfully:

class Simple(object):
    def __init__(self, name):
      self.name = name

    def __add__(self, other):
      c = Composite()
      c._members.append(self)
      c._members.append(other)
      return c

    def __repr__(self):
      return "Simple('%s')" % self.name

class Composite(object):
    def __init__(self):
      self._members = []

    def __add__(self, obj):
      if isinstance(obj, Simple):
        out = Composite()
        out._members = [k for k in self._members] + [obj]
      elif isinstance(obj, Composite):
        out = Composite()
        out._members = [k for k in self._members + obj._members]
      else:
        raise TypeError
      return out

if __name__ == "__main__":
    s1 = Simple('one')
    s2 = Simple('two')
    s3 = Simple('three')
    c1 = s1 + s2
    c2 = c1 + s3
    print c1._members
    print c2._members
    # output:
    # [Simple('one'), Simple('two')]
    # [Simple('one'), Simple('two'), Simple('three')]

I would like to keep the definition of Simple, Composite, and __main__ in three different files, but I cannot do it because I cannot import Simple into composite.py and I cannot import Composite into simple.py.

How would you modify the class definition such that you can keep separate files?

Thank you.

PS. I've read several answers related to "forward declaration" but could not find an answer to my specific problem.

Body:
Since none of the references are needed until the methods are called, circular imports can work here. The trick is to use fully-qualified references.

import composite

class Simple(object):
   ...
  def __add__(self, other):
    c = composite.Composite()
    c._members.append(self)
    c._members.append(other)
    return c


问:
json array is repeating index
this is my code :

```<code>if ($API->connect("192.168.81.130", "admin", "")) {
    $API->write('/ip/route/print', false);
    $API->write('=.proplist=.id', false);
    $API->write('=.proplist=dst-address', false);
    $API->write('=.proplist=pref-src', false);
    $API->write('=.proplist=gateway');
    $result = $API->read();
    $API->disconnect();

    foreach ($result as $route){
        $response['id'] = $route['.id'];
        $response['dst-address'] = $route['dst-address'];
        if (isset($route['pref-src'])) {
            $response['pref-src'] = $route['pref-src'];
        } else {
            $response['pref-src'] = "";
        }
        $response['gateway'] = $route['gateway'];
        $array[] = $response;
        echo json_encode($array);
    }
}
</code>```

and the output is :

```<code>[{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"}][{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}]
</code>```

result for "[{"id":"*2","dst-address":"0.0.0.0/0","pref-src":"","gateway":"192.168.1.1"}]" is show twice.

i want the out put like this :

```<code>> [{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}].
</code>```

can anyone help me?.

答:
You need to initialize your array each time round the loop otherwise you are just adding to it each time, hence the duplication

You also need to move the echo of the json string to outside the loop

```<code>foreach ($result as $route){
    $response = array();

    $response['id'] = $route['.id'];
    $response['dst-address'] = $route['dst-address'];
    if (isset($route['pref-src'])) {
        $response['pref-src'] = $route['pref-src'];
    } else {
        $response['pref-src'] = "";
    }
    $response['gateway'] = $route['gateway'];
    $array[] = $response;

}
echo json_encode($array);
</code>```

Title: json array is repeating index

Body:
this is my code :

if ($API->connect("192.168.81.130", "admin", "")) {
    $API->write('/ip/route/print', false);
    $API->write('=.proplist=.id', false);
    $API->write('=.proplist=dst-address', false);
    $API->write('=.proplist=pref-src', false);
    $API->write('=.proplist=gateway');
    $result = $API->read();
    $API->disconnect();

    foreach ($result as $route){
        $response['id'] = $route['.id'];
        $response['dst-address'] = $route['dst-address'];
        if (isset($route['pref-src'])) {
            $response['pref-src'] = $route['pref-src'];
        } else {
            $response['pref-src'] = "";
        }
        $response['gateway'] = $route['gateway'];
        $array[] = $response;
        echo json_encode($array);
    }
}

and the output is :

[{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"}][{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}]

result for "[{"id":"*2","dst-address":"0.0.0.0/0","pref-src":"","gateway":"192.168.1.1"}]" is show twice.

i want the out put like this :

> [{"id":"*2","dst-address":"0.0.0.0\/0","pref-src":"","gateway":"192.168.1.1"},{"id":"*420639B3","dst-address":"192.168.81.0\/24","pref-src":"192.168.81.130","gateway":"ether1"}].

can anyone help me?.

Body:
You need to initialize your array each time round the loop otherwise you are just adding to it each time, hence the duplication

You also need to move the echo of the json string to outside the loop

foreach ($result as $route){
    $response = array();

    $response['id'] = $route['.id'];
    $response['dst-address'] = $route['dst-address'];
    if (isset($route['pref-src'])) {
        $response['pref-src'] = $route['pref-src'];
    } else {
        $response['pref-src'] = "";
    }
    $response['gateway'] = $route['gateway'];
    $array[] = $response;

}
echo json_encode($array);


问:
How do I create effective class hierarchy
I want to create a basic Item class hierarchy.
Each Item will have a String name and an int itemID.
These variables will be set in each subclass of Item.
The Item class declares the two variables and each subclass of Item
(public class Hammer extends Item) will set the name and itemID.
For example, name = "hammer" and itemID = 01.
How would I do this efficiently and effectively?

答:
The base class will declare two final private fields (name and itemid).
The values for these will be set via the base class constructor.

Each of the derived classes will call the base class constructor with the appropriate name and itemid value.

for example:

```<code>public abstract class Blam
{
    private final int itemId;
    private final String name;

    protected(
        final int itemId,
        final String name)
    {
        this.itemId = itemId;
        this.name = name;
    }
}

public class Derived
extends
    Blam
{
    public Derived()
    {
        super(123, "nameValue");
    }
}
</code>```

Body:
The base class will declare two final private fields (name and itemid).
The values for these will be set via the base class constructor.

Each of the derived classes will call the base class constructor with the appropriate name and itemid value.

for example:

public abstract class Blam
{
    private final int itemId;
    private final String name;

    protected(
        final int itemId,
        final String name)
    {
        this.itemId = itemId;
        this.name = name;
    }
}

public class Derived
extends
    Blam
{
    public Derived()
    {
        super(123, "nameValue");
    }
}


问:
Gmail API HistoryRequest query
To do a full sync, I can use ListRequest and pass a query (ex inbox only - label sent -label:sent OR to:me). How can I do the same for a partial sync - using HistoryRequest? I don't see the possibility of passing in any query?

答: You can set the labelId for a history request</p>

Title: Gmail API HistoryRequest query


问:
Using JavaScript to refresh or retrieve current information on button click
I'll preface this with I'm still new to JavaScript.  So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties.  I've written a simple application to hopefully illustrate what I'm getting at.

Below is a sample controller that's passing in List to the Index page:

```<code>    public ActionResult Index() {
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if(sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return View(activeIds);
    }
</code>```

This returns the current "active" items in the database. The (rough) view is as follows...

```<code>@model List<int>

@{
    ViewBag.Title = "Index";
}

<p>Current Recognized Count: @Model.Count() </p>
<a href="#" id="printBtn">Print</a>

<script>
$(document).ready(function () {
    $('#printBtn').click(function () {

        var numberOfActiveIds = @Model.Count();

        $.ajax({
            type: "POST",
            url: "/Home/PostResults",
            data: { ids: numberOfActiveIds},
            success: function (results) {
                if(results == "Success") {
                    window.location.href = '/Home/Results';
                }
            }
        });
    });
});
</script>
</code>```

The issue is getting the current number of active items from the database when the button is clicked.  Let's say that the user remains idle on the page after it loads for a few minutes.  When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8.  However, when the user finally clicks the button it'll submit 5 items instead of the current 8.

I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up.  Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?

If you have any additional questions, please let me know and I will gladly comply.  I've looked at other questions and answers on SO but I haven't found one that quite works for my situation.  Thanks!

Edit #1

So, I've added this function to the Home controller which just returns the list count as Json.

```<code>    public ActionResult GetIds(){
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return Json(activeIds.Count());
    }
</code>```

The view script now looks like this...

```<code><script>
$(document).ready(function () {
    $('#printBtn').click(function () {

        var numberOfActiveIds = @Model.Count();

        $.ajax({
            type: "GET",
            url: "/Home/GetIds",
            success: function(response) {
                numberOfActiveIds = response;

                $.ajax({
                    type: "POST",
                    url: "/Home/PostResults",
                    data: { ids: numberOfActiveIds},
                    success: function (results) {
                        if(results == "Success") {
                            window.location.href = '/Home/Results';
                        }
                    }
                });
            }
        });
    });
});
</script>
</code>```

I'm currently getting the following error...

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Edit #2

I had to set the JsonRequestBehavior to AllowGet for it to work properly.  Thanks again, everyone!

答:
gforce301 mentioned to GET the current actives via an ajax call to an additional, separate method making the query to the database and THEN ajax post the returned "actives". Is that possible?

Yes this is possible. That's why I mentioned it. Irregardless of other peoples opinions on how they think you should do this, I understand that you may be limited on why you can't do it their way even if they don't.

The code below is a restructuring of your code. It chains 2 ajax calls together, with the second one depending on the success of the first. Notice the comment block in the success handler of the first ajax call. Since I don't know what the response will be, I can't fill in the part on how to use it. This accomplishes your goal of having the user only make a single button click.

```<code><script>
$(document).ready(function () {
    $('#printBtn').click(function () {

        var numberOfActiveIds = @Model.Count();

        $.ajax({
            type: 'GET',
            url: '/path/to/get/activeIds',
            success: function(response) {
                /*
                    Since I don't know the structure of response
                    I have to just explain.

                    use response to populate numberOfActiveIds

                    now we just make our post ajax request.
                */

                $.ajax({
                    type: "POST",
                    url: "/Home/PostResults",
                    data: { ids: numberOfActiveIds},
                    success: function (results) {
                        if(results == "Success") {
                            window.location.href = '/Home/Results';
                        }
                    }
                });
            }
        });

    });
});
</script>
</code>```

Body:
I'll preface this with I'm still new to JavaScript.  So problem is in a larger application, our controller is passing in a list of information to the view where certain JavaScript functions rely on certain ViewModel properties.  I've written a simple application to hopefully illustrate what I'm getting at.

Below is a sample controller that's passing in List to the Index page:

    public ActionResult Index() {
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if(sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return View(activeIds);
    }

This returns the current "active" items in the database. The (rough) view is as follows...

@model List<int>

@{
    ViewBag.Title = "Index";
}

Current Recognized Count: @Model.Count()

Print

The issue is getting the current number of active items from the database when the button is clicked.  Let's say that the user remains idle on the page after it loads for a few minutes.  When their page originally loaded, the model returned 5 items listed as active... but while they've been waiting 3 additional items were switched to active in the database for a total of 8.  However, when the user finally clicks the button it'll submit 5 items instead of the current 8.

I'm unable to run the query to get the current number of active items in the "/Home/PostResults" ActionResult due to the nature of how the larger application is set up.  Is there a way I could refresh the page (getting the updated model) before the rest of the function carries out using values of the refreshed model?

If you have any additional questions, please let me know and I will gladly comply.  I've looked at other questions and answers on SO but I haven't found one that quite works for my situation.  Thanks!

Edit #1

So, I've added this function to the Home controller which just returns the list count as Json.

    public ActionResult GetIds(){
        List<int> activeIds = new List<int>();
        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[JS-Test] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                activeIds.Add((int)sqlDR["ID"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return Json(activeIds.Count());
    }

The view script now looks like this...

I'm currently getting the following error...

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Edit #2

I had to set the JsonRequestBehavior to AllowGet for it to work properly.  Thanks again, everyone!

Body:
gforce301 mentioned to GET the current actives via an ajax call to an additional, separate method making the query to the database and THEN ajax post the returned "actives". Is that possible?

Yes this is possible. That's why I mentioned it. Irregardless of other peoples opinions on how they think you should do this, I understand that you may be limited on why you can't do it their way even if they don't.

The code below is a restructuring of your code. It chains 2 ajax calls together, with the second one depending on the success of the first. Notice the comment block in the success handler of the first ajax call. Since I don't know what the response will be, I can't fill in the part on how to use it. This accomplishes your goal of having the user only make a single button click.

<script>
$(document).ready(function () {
    $('#printBtn').click(function () {

        var numberOfActiveIds = @Model.Count();

        $.ajax({
            type: 'GET',
            url: '/path/to/get/activeIds',
            success: function(response) {
                /*
                    Since I don't know the structure of response
                    I have to just explain.

                    use response to populate numberOfActiveIds

                    now we just make our post ajax request.
                */

                $.ajax({
                    type: "POST",
                    url: "/Home/PostResults",
                    data: { ids: numberOfActiveIds},
                    success: function (results) {
                        if(results == "Success") {
                            window.location.href = '/Home/Results';
                        }
                    }
                });
            }
        });

    });
});
</script>


问:
response.result.value in alamofire post method is nil
```<code>        let parametersDictionary = [
        "email" : "name@gmail.com",
        "password" : "password"
    ]
    Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
        print("response:", response.result.value)
    }
</code>```

I'm working in post method api and above code is not working. I'm getting nil response. But this url is working properly in postman and android studio too. What is the reason behind this issue?

答:
Your url only works when requesting using form with url encoded

Try to use this, as documented on GitHub

```<code>Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: parametersDictionary , encoding: URLEncoding.default)
</code>```

If this encoding doesn't work, try encoding: URLEncoding.httpBody

Body:
        let parametersDictionary = [
        "email" : "name@gmail.com",
        "password" : "password"
    ]
    Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
        print("response:", response.result.value)
    }

I'm working in post method api and above code is not working. I'm getting nil response. But this url is working properly in postman and android studio too. What is the reason behind this issue?

Body:
Your url only works when requesting using form with url encoded

Try to use this, as documented on GitHub

Alamofire.request("http://nanosoftech.com/store/user_check", method: .post, parameters: parametersDictionary , encoding: URLEncoding.default)

If this encoding doesn't work, try encoding: URLEncoding.httpBody


问:
Cannot start nexus: Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
I'm currently working on configuring nexus on our server. I followed all the required steps steps but it seems that I'm missing something.

java version "1.8.0_121"

nexus version "3.2.1"

My complete log trace is below:

```<code>              jvm 1    | Caused by: org.codehaus.plexus.component.repository.exception.ComponentLookupException: com.google.inject.ProvisionException: Guice provision errors:
              jvm 1    |
              jvm 1    | 1) Error injecting: org.sonatype.nexus.DefaultNexus
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   while locating org.sonatype.nexus.Nexus
              jvm 1    |
              jvm 1    | 1 error
              jvm 1    |       role: org.sonatype.nexus.Nexus
              jvm 1    |   roleHint:
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:238)
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:226)
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:220)
              jvm 1    |    at org.sonatype.nexus.web.NexusBooterListener.contextInitialized(NexusBooterListener.java:43)
              jvm 1    |    ... 41 more
              jvm 1    | Caused by: com.google.inject.ProvisionException: Guice provision errors:
              jvm 1    |
              jvm 1    | 1) Error injecting: org.sonatype.nexus.DefaultNexus
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   while locating org.sonatype.nexus.Nexus
              jvm 1    |
              jvm 1    | 1 error
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:952)
              jvm 1    |    at org.sonatype.guice.bean.locators.QualifiedBean.getValue(QualifiedBean.java:85)
              jvm 1    |    at org.sonatype.guice.plexus.locators.LazyPlexusBean.getValue(LazyPlexusBean.java:55)
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:234)
              jvm 1    |    ... 44 more
              jvm 1    | Caused by: com.google.inject.ProvisionException: Guice provision errors:
              jvm 1    |
              jvm 1    | 1) Error starting: class org.sonatype.nexus.DefaultNexus
              jvm 1    |   while locating org.sonatype.nexus.DefaultNexus
              jvm 1    |
              jvm 1    | 1 error
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:952)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:978)
              jvm 1    |    at org.sonatype.guice.bean.reflect.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
              jvm 1    |    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
              jvm 1    |    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:996)
              jvm 1    |    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
              jvm 1    |    at com.google.inject.Scopes$1$1.get(Scopes.java:63)
              jvm 1    |    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:943)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:996)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:939)
              jvm 1    |    ... 47 more
              jvm 1    | Caused by: org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException: Could not start Nexus!
              jvm 1    |    at org.sonatype.nexus.DefaultNexus.start(DefaultNexus.java:651)
              jvm 1    |    at org.codehaus.plexus.PlexusLifecycleManager.start(PlexusLifecycleManager.java:229)
              jvm 1    |    at org.codehaus.plexus.PlexusLifecycleManager.manage(PlexusLifecycleManager.java:145)
              jvm 1    |    at org.sonatype.guice.plexus.binders.PlexusBeanBinder.afterInjection(PlexusBeanBinder.java:79)
              jvm 1    |    at com.google.inject.internal.MembersInjectorImpl.notifyListeners(MembersInjectorImpl.java:97)
              jvm 1    |    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:95)
              jvm 1    |    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:253)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:943)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:996)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:939)
              jvm 1    |    ... 58 more
              jvm 1    | Caused by: com.thoughtworks.xstream.converters.ConversionException: Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor : Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    | ---- Debugging information ----
              jvm 1    | message             : Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    | cause-exception     : com.thoughtworks.xstream.converters.reflection.ObjectAccessException
              jvm 1    | cause-message       : Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    | class               : org.sonatype.nexus.configuration.model.CRepository
              jvm 1    | required-type       : org.codehaus.plexus.util.xml.Xpp3Dom
              jvm 1    | path                : /org.sonatype.nexus.configuration.model.CRepository/externalConfiguration
              jvm 1    | line number         : 29
              jvm 1    | -------------------------------
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:89)
              jvm 1    |    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:63)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshallField(AbstractReflectionConverter.java:246)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:218)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:162)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
              jvm 1    |    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:63)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:60)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:137)
              jvm 1    |    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
              jvm 1    |    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:923)
              jvm 1    |    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:909)
              jvm 1    |    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:853)
              jvm 1    |    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:845)
              jvm 1    |    at org.sonatype.nexus.configuration.model.AbstractRevertableConfiguration.copyObject(AbstractRevertableConfiguration.java:85)
              jvm 1    |    at org.sonatype.nexus.configuration.model.AbstractRevertableConfiguration.getConfiguration(AbstractRevertableConfiguration.java:28)
              jvm 1    |    at org.sonatype.nexus.configuration.model.CRepositoryCoreConfiguration.getConfiguration(CRepositoryCoreConfiguration.java:39)
              jvm 1    |    at org.sonatype.nexus.proxy.repository.ConfigurableRepository.getCurrentConfiguration(ConfigurableRepository.java:25)
              jvm 1    |    at org.sonatype.nexus.proxy.repository.ConfigurableRepository.getCurrentConfiguration(ConfigurableRepository.java:17)
              jvm 1    |    at org.sonatype.nexus.configuration.AbstractConfigurable.configure(AbstractConfigurable.java:153)
              jvm 1    |    at org.sonatype.nexus.configuration.application.runtime.DefaultApplicationRuntimeConfigurationBuilder.createRepositoryFromModel(DefaultApplicationRuntimeConfigurationBuilder.java:46)
              jvm 1    |    at org.sonatype.nexus.configuration.application.DefaultNexusConfiguration.instantiateRepository(DefaultNexusConfiguration.java:506)
              jvm 1    |    at org.sonatype.nexus.configuration.application.DefaultNexusConfiguration.createRepositories(DefaultNexusConfiguration.java:472)
              jvm 1    |    at org.sonatype.nexus.configuration.application.DefaultNexusConfiguration.createInternals(DefaultNexusConfiguration.java:454)
              jvm 1    |    at org.sonatype.nexus.DefaultNexus.startService(DefaultNexus.java:685)
              jvm 1    |    at org.sonatype.nexus.DefaultNexus.start(DefaultNexus.java:647)
              jvm 1    |    ... 67 more
              jvm 1    | Caused by: com.thoughtworks.xstream.converters.reflection.ObjectAccessException: Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider.newInstance(PureJavaReflectionProvider.java:71)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.instantiateNewInstance(AbstractReflectionConverter.java:308)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:161)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
              jvm 1    |    ... 94 more
              jvm 1    | 2017-07-06 13:29:19 INFO  [er_start_runner] - org.mortbay.log               - Started SelectChannelConnector@0.0.0.0:8081
</code>```

答:
That stack trace is not coming from Nexus 3.x, none of the classes in the stack exist in that version.

It's coming from Nexus 1.x or 2.x, and it looks like you've starting a pretty old version, since you seem to be hitting this:

https://issues.sonatype.org/browse/NEXUS-4453

Body:
I'm currently working on configuring nexus on our server. I followed all the required steps steps but it seems that I'm missing something.

java version "1.8.0_121"

nexus version "3.2.1"

My complete log trace is below:

              jvm 1    | Caused by: org.codehaus.plexus.component.repository.exception.ComponentLookupException: com.google.inject.ProvisionException: Guice provision errors:
              jvm 1    |
              jvm 1    | 1) Error injecting: org.sonatype.nexus.DefaultNexus
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   while locating org.sonatype.nexus.Nexus
              jvm 1    |
              jvm 1    | 1 error
              jvm 1    |       role: org.sonatype.nexus.Nexus
              jvm 1    |   roleHint:
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:238)
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:226)
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:220)
              jvm 1    |    at org.sonatype.nexus.web.NexusBooterListener.contextInitialized(NexusBooterListener.java:43)
              jvm 1    |    ... 41 more
              jvm 1    | Caused by: com.google.inject.ProvisionException: Guice provision errors:
              jvm 1    |
              jvm 1    | 1) Error injecting: org.sonatype.nexus.DefaultNexus
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   at ClassRealm[plexus.core, parent: null]
              jvm 1    |   while locating org.sonatype.nexus.Nexus
              jvm 1    |
              jvm 1    | 1 error
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:952)
              jvm 1    |    at org.sonatype.guice.bean.locators.QualifiedBean.getValue(QualifiedBean.java:85)
              jvm 1    |    at org.sonatype.guice.plexus.locators.LazyPlexusBean.getValue(LazyPlexusBean.java:55)
              jvm 1    |    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:234)
              jvm 1    |    ... 44 more
              jvm 1    | Caused by: com.google.inject.ProvisionException: Guice provision errors:
              jvm 1    |
              jvm 1    | 1) Error starting: class org.sonatype.nexus.DefaultNexus
              jvm 1    |   while locating org.sonatype.nexus.DefaultNexus
              jvm 1    |
              jvm 1    | 1 error
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:952)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:978)
              jvm 1    |    at org.sonatype.guice.bean.reflect.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
              jvm 1    |    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
              jvm 1    |    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:996)
              jvm 1    |    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
              jvm 1    |    at com.google.inject.Scopes$1$1.get(Scopes.java:63)
              jvm 1    |    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:943)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:996)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:939)
              jvm 1    |    ... 47 more
              jvm 1    | Caused by: org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException: Could not start Nexus!
              jvm 1    |    at org.sonatype.nexus.DefaultNexus.start(DefaultNexus.java:651)
              jvm 1    |    at org.codehaus.plexus.PlexusLifecycleManager.start(PlexusLifecycleManager.java:229)
              jvm 1    |    at org.codehaus.plexus.PlexusLifecycleManager.manage(PlexusLifecycleManager.java:145)
              jvm 1    |    at org.sonatype.guice.plexus.binders.PlexusBeanBinder.afterInjection(PlexusBeanBinder.java:79)
              jvm 1    |    at com.google.inject.internal.MembersInjectorImpl.notifyListeners(MembersInjectorImpl.java:97)
              jvm 1    |    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:95)
              jvm 1    |    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:253)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:943)
              jvm 1    |    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:996)
              jvm 1    |    at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:939)
              jvm 1    |    ... 58 more
              jvm 1    | Caused by: com.thoughtworks.xstream.converters.ConversionException: Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor : Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    | ---- Debugging information ----
              jvm 1    | message             : Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    | cause-exception     : com.thoughtworks.xstream.converters.reflection.ObjectAccessException
              jvm 1    | cause-message       : Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    | class               : org.sonatype.nexus.configuration.model.CRepository
              jvm 1    | required-type       : org.codehaus.plexus.util.xml.Xpp3Dom
              jvm 1    | path                : /org.sonatype.nexus.configuration.model.CRepository/externalConfiguration
              jvm 1    | line number         : 29
              jvm 1    | -------------------------------
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:89)
              jvm 1    |    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:63)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshallField(AbstractReflectionConverter.java:246)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:218)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:162)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
              jvm 1    |    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:63)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:60)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:137)
              jvm 1    |    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
              jvm 1    |    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:923)
              jvm 1    |    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:909)
              jvm 1    |    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:853)
              jvm 1    |    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:845)
              jvm 1    |    at org.sonatype.nexus.configuration.model.AbstractRevertableConfiguration.copyObject(AbstractRevertableConfiguration.java:85)
              jvm 1    |    at org.sonatype.nexus.configuration.model.AbstractRevertableConfiguration.getConfiguration(AbstractRevertableConfiguration.java:28)
              jvm 1    |    at org.sonatype.nexus.configuration.model.CRepositoryCoreConfiguration.getConfiguration(CRepositoryCoreConfiguration.java:39)
              jvm 1    |    at org.sonatype.nexus.proxy.repository.ConfigurableRepository.getCurrentConfiguration(ConfigurableRepository.java:25)
              jvm 1    |    at org.sonatype.nexus.proxy.repository.ConfigurableRepository.getCurrentConfiguration(ConfigurableRepository.java:17)
              jvm 1    |    at org.sonatype.nexus.configuration.AbstractConfigurable.configure(AbstractConfigurable.java:153)
              jvm 1    |    at org.sonatype.nexus.configuration.application.runtime.DefaultApplicationRuntimeConfigurationBuilder.createRepositoryFromModel(DefaultApplicationRuntimeConfigurationBuilder.java:46)
              jvm 1    |    at org.sonatype.nexus.configuration.application.DefaultNexusConfiguration.instantiateRepository(DefaultNexusConfiguration.java:506)
              jvm 1    |    at org.sonatype.nexus.configuration.application.DefaultNexusConfiguration.createRepositories(DefaultNexusConfiguration.java:472)
              jvm 1    |    at org.sonatype.nexus.configuration.application.DefaultNexusConfiguration.createInternals(DefaultNexusConfiguration.java:454)
              jvm 1    |    at org.sonatype.nexus.DefaultNexus.startService(DefaultNexus.java:685)
              jvm 1    |    at org.sonatype.nexus.DefaultNexus.start(DefaultNexus.java:647)
              jvm 1    |    ... 67 more
              jvm 1    | Caused by: com.thoughtworks.xstream.converters.reflection.ObjectAccessException: Cannot construct org.codehaus.plexus.util.xml.Xpp3Dom as it does not have a no-args constructor
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider.newInstance(PureJavaReflectionProvider.java:71)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.instantiateNewInstance(AbstractReflectionConverter.java:308)
              jvm 1    |    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:161)
              jvm 1    |    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
              jvm 1    |    ... 94 more
              jvm 1    | 2017-07-06 13:29:19 INFO  [er_start_runner] - org.mortbay.log               - Started SelectChannelConnector@0.0.0.0:8081


问:
Javascript query returning 'undefined' on Sharepoint choice column
I'm querying a SharePoint list with a JavaScript files. Everything is returning fine except the query on a choice column called Devicetype which is coming back undefined and I can't see why. Any thoughts? JS below:

```<code>function getDeviceDetails() {
var txtTitle = "";
var txtName = "";
var txtOverview = "";
var txtAccessories = "";
var txtDevicetype = "";
var txtTypicalDeviceUsage ="";
var txtKnownSystemIssues ="";
var txtTrafficlight = "";
var imgDevicePicture = "";
var tempLCS2 = "";
var HTML = "<h3>Desktop</h3>";
var Laptop = "Y"
var Tabs="Y" ;
 var query = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=Priority&$filter=Id eq " + window.DeviceId + "";
 var call = $.ajax({
        url: query,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
        var tempID = item.Id;
        var NameofDevice = item.Title;
        var tempTitle = item.Title;
        var DeviceOverView = item.Description;
        var AccessDetails = item.Accessories;
        var DeviceKind = item.DevicetypeValue;
        var Usage = item.TypicalUsage;
        var DevicePriority = item.PriorityValue;
        var DeviceImage = item.DeviceImage;

        txtTitle = "<p>";
        txtName = "<p>" + NameofDevice + "</p>"; +  DeviceKind + "</p>";
        txtOverview = "<p>" + DeviceOverView + "</p>";
        txtAccessories = "<p>" + AccessDetails + "</p>";
        txtDevicetype = "<p>" + DeviceKind  + "</p>";
        txtTypicalDeviceUsage = "<p>" + Usage + "</p>";
        txtTrafficlight = "<p>" + DevicePriority + "</p>";
        imgDevicePicture = "<img src='" + DeviceImage + "'>";

    });
    $('#devicedetails').append($(txtTitle));
    $('#deviceoverview').append($(txtOverview));
    $('devicename').append(txtName);
    $('#devicekind').append(txtDevicetype);
    $('#deviceacc').append(txtAccessories);
    $('#deviceuse').append(txtTypicalDeviceUsage);
    $('#devicestatus').append(txtTrafficlight);
    $('#imageContainer').append("<img src='/sites/IT/SiteAssets/"+txtTrafficlight.replace(/<[^>]*>/g, '')+".png' />");
    $('.deviceimage').append(imgDevicePicture);

});
call.fail(function (jqXHR,textStatus,errorThrown){
    alert("Error retrieving data: " + jqXHR.responseText);
});
</code>```

}

getDevices file

```<code>function getDevices() {
var txtTitle = "";
var txtDeviceType = "";

var query = "http://collaboration.norgine.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title";
var call = $.ajax({
        url: query,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });

call.done(function (data,textStatus, jqXHR){
    $.each(data.d.results, function (i, result) {

        var tempID = result.Id;
        var tempTitle = result.Title;
        var tempDeviceType = result.DeviceTypeValue;
        txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle +  "</a> - " + tempDeviceType + "</p>";

    });
    $('#devices').append($(txtTitle));
});
call.fail(function (jqXHR,textStatus,errorThrown){
    alert("Error retrieving data: " + jqXHR.responseText);
});
</code>```

}

答:
You need to select the field in the URL:</p>

```<code>var query = "http://collaboration.norgine.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title,DeviceTypeValue";
</code>```

Body:
I'm querying a SharePoint list with a JavaScript files. Everything is returning fine except the query on a choice column called Devicetype which is coming back undefined and I can't see why. Any thoughts? JS below:

function getDeviceDetails() {
var txtTitle = "";
var txtName = "";
var txtOverview = "";
var txtAccessories = "";
var txtDevicetype = "";
var txtTypicalDeviceUsage ="";
var txtKnownSystemIssues ="";
var txtTrafficlight = "";
var imgDevicePicture = "";
var tempLCS2 = "";
var HTML = "
Desktop
";
var Laptop = "Y"
var Tabs="Y" ;
 var query = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=Priority&$filter=Id eq " + window.DeviceId + "";
 var call = $.ajax({
        url: query,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
        var tempID = item.Id;
        var NameofDevice = item.Title;
        var tempTitle = item.Title;
        var DeviceOverView = item.Description;
        var AccessDetails = item.Accessories;
        var DeviceKind = item.DevicetypeValue;
        var Usage = item.TypicalUsage;
        var DevicePriority = item.PriorityValue;
        var DeviceImage = item.DeviceImage;

        txtTitle = "
";
        txtName = "
" + NameofDevice + "
"; +  DeviceKind + "
";
        txtOverview = "
" + DeviceOverView + "
";
        txtAccessories = "
" + AccessDetails + "
";
        txtDevicetype = "
" + DeviceKind  + "
";
        txtTypicalDeviceUsage = "
" + Usage + "
";
        txtTrafficlight = "
" + DevicePriority + "
";
        imgDevicePicture = "";

    });
    $('#devicedetails').append($(txtTitle));
    $('#deviceoverview').append($(txtOverview));
    $('devicename').append(txtName);
    $('#devicekind').append(txtDevicetype);
    $('#deviceacc').append(txtAccessories);
    $('#deviceuse').append(txtTypicalDeviceUsage);
    $('#devicestatus').append(txtTrafficlight);
    $('#imageContainer').append("<img src='/sites/IT/SiteAssets/"+txtTrafficlight.replace(/<[^>]*>/g, '')+".png' />");
    $('.deviceimage').append(imgDevicePicture);

});
call.fail(function (jqXHR,textStatus,errorThrown){
    alert("Error retrieving data: " + jqXHR.responseText);
});

}

getDevices file

function getDevices() {
var txtTitle = "";
var txtDeviceType = "";

var query = "http://collaboration.norgine.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title";
var call = $.ajax({
        url: query,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });

call.done(function (data,textStatus, jqXHR){
    $.each(data.d.results, function (i, result) {

        var tempID = result.Id;
        var tempTitle = result.Title;
        var tempDeviceType = result.DeviceTypeValue;
        txtTitle = txtTitle + "
" + tempTitle +  " - " + tempDeviceType + "
";

    });
    $('#devices').append($(txtTitle));
});
call.fail(function (jqXHR,textStatus,errorThrown){
    alert("Error retrieving data: " + jqXHR.responseText);
});

}

Body:
You need to select the field in the URL:

var query = "http://collaboration.norgine.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title,DeviceTypeValue";


问:
Custom action on multiple selected files via a keyboard shortcut
I'm trying to trigger a call to a program directly from Windows Explorer with the selected files as parameter, and this with a key push (on F12 or Ctrl+E for example). The same kind of action as when you select more than one file and press F2 to rename them all. I was looking in the registry but with no success.

For example, when I open my src folder and select a few JS files I have to right-click on a file, select "Send To", and select the right shortcut to my "programme.exe" software (transcription from JS, import of a few environmental vars, etc.). It would be helpful if I could simply press Ctrl+E to transcript and edit those selected files.

An other similar thing I'm looking for is to press F12 and edit all my selected files (it's easier for me to use a keyboard than a mouse).

I'm on Windows 10 and don't think this is linked to desktop shortcuts or anything like that. I should have been more explicit; the external calls are done, but the link between the keyboard shortcut and these calls is the part I'm trying to deal with.

I've already created an AutoIt script that does this, but it should be possible within the Windows Explorer itself (and only when it's needed, not looping a script infinitely I mean), shouldn't it?

```<code>#include <Array.au3>
#include <WinAPI.au3>

; Init - stop
Global $stop = False
HotKeySet("{F4}", "stop")
Func stop()
    If $stop Then Exit
    $stop = True
EndFunc

; Init - trigger
Global $trigger = False
HotKeySet("^t", "trigger")
Func trigger()
    $trigger = True
EndFunc

; Event loop
While Not $stop
    Sleep(100)
    If $trigger Then
        action()
        $trigger = False
    EndIf
WEnd

Func action()
    ConsoleWrite(@CRLF)
    ; Check active window (explorer only)
    Local $handle = WinGetHandle("[ACTIVE]"), $class = _WinAPI_GetClassName($handle)
    ConsoleWrite("- Window:"&$class&" ")
    If $class <> "CabinetWClass" Then Return
    ; Get object linked to window
    Local $shell = ObjCreate("Shell.Application"), $window = 0
    For $object In $shell.Windows()
        If $object.HWND() = $handle Then
            $window = $object
            ExitLoop
        EndIf
    Next
    If $window = 0 Then Return
    ; Check active component (right filelist panel only)
    Local $control = ControlGetFocus($handle)
    If $control <> "DirectUIHWND3" Then Return
    ; Get selection (files selected in the right panel)
    Local $selected[1] = [0]
    For $element In $window.Document.SelectedItems()
        If $element.IsFolder Or $element.IsLink Then ContinueLoop
        Local $path = $element.Path
        For $i = 1 To $selected[0]
            If $path = $selected[$i] Then ContinueLoop 2
        Next
        $selected[0] = $selected[0]+1
        ReDim $selected[$selected[0]+1]
        $selected[$selected[0]] = $path
    Next
    ; Action : ###############################
EndFunc
</code>```

答:
Froggy!  :o)  I can tell you that your English is a heck of a lot better than my French, so don't even worry about that.

I think what you're going to need to do is to create a custom macro or VBScript to open the files using your desired EXE.  I'm not very good with VBScript myself, so that part I can't help with.

As for the rest of your request, there are instructions on the Microsoft site for how to do this.  I will paste them here just in case the link ever changes:

Step 1: Download the current version of IntelliType software

Visit the following Microsoft Web site:
http://www.microsoft.com/hardware/download/download.aspx?category=MK

Select your keyboard, and make the other appropriate selections to download the latest IntelliType software.

Step 2: Start the Keyboard wizard, and change the assignments

Open the Keyboard item in Control Panel.

In Windows 7 or in Windows Vista, click Start the Start button , type keyboard in the Start Search box, and then click Keyboard (or Microsoft Keyboard) in the Programs list.

In Windows XP and earlier versions of Windows, click Start, click Run, type Control keyboard, and then click OK.

On the Key Settings tab, select the key that you want to change.

To change the command or the program assignment, click Configure. To change or to assign a macro to the key, click Assign/Manage Macro.

Select the appropriate options, and then follow the instructions.

Notes

You can specify that a program open to a specific document, Web site, or other item by adding the appropriate parameter. For example:

iexplore.exe http://www.msn.com: Starts Microsoft Internet Explorer, and opens the MSN.com Web site

word.exe mydoc.doc: Starts Microsoft Word, and opens the mydoc file

Use Restore Defaults to remove all customized settings, and restart all assignments.

Under Custom Key Settings, you can rename each bank by using Options, or you can add a program for custom key assignments for that program by using Add.

Macros can be assigned or changed by using the Assign/Manage Macro button. See Help for more information.

This StackOverflow question might give you a little more guidance as well.

Additionally, this question on another website shows that it works for VBScripts, and gives an example of a VBScript.  I won't bother copy/pasting it all, it's just backup for what I've written above.

Body:
I'm trying to trigger a call to a program directly from Windows Explorer with the selected files as parameter, and this with a key push (on F12 or Ctrl+E for example). The same kind of action as when you select more than one file and press F2 to rename them all. I was looking in the registry but with no success.

For example, when I open my src folder and select a few JS files I have to right-click on a file, select "Send To", and select the right shortcut to my "programme.exe" software (transcription from JS, import of a few environmental vars, etc.). It would be helpful if I could simply press Ctrl+E to transcript and edit those selected files.

An other similar thing I'm looking for is to press F12 and edit all my selected files (it's easier for me to use a keyboard than a mouse).

I'm on Windows 10 and don't think this is linked to desktop shortcuts or anything like that. I should have been more explicit; the external calls are done, but the link between the keyboard shortcut and these calls is the part I'm trying to deal with.

I've already created an AutoIt script that does this, but it should be possible within the Windows Explorer itself (and only when it's needed, not looping a script infinitely I mean), shouldn't it?

#include <Array.au3>
#include <WinAPI.au3>

; Init - stop
Global $stop = False
HotKeySet("{F4}", "stop")
Func stop()
    If $stop Then Exit
    $stop = True
EndFunc

; Init - trigger
Global $trigger = False
HotKeySet("^t", "trigger")
Func trigger()
    $trigger = True
EndFunc

; Event loop
While Not $stop
    Sleep(100)
    If $trigger Then
        action()
        $trigger = False
    EndIf
WEnd

Func action()
    ConsoleWrite(@CRLF)
    ; Check active window (explorer only)
    Local $handle = WinGetHandle("[ACTIVE]"), $class = _WinAPI_GetClassName($handle)
    ConsoleWrite("- Window:"&$class&" ")
    If $class <> "CabinetWClass" Then Return
    ; Get object linked to window
    Local $shell = ObjCreate("Shell.Application"), $window = 0
    For $object In $shell.Windows()
        If $object.HWND() = $handle Then
            $window = $object
            ExitLoop
        EndIf
    Next
    If $window = 0 Then Return
    ; Check active component (right filelist panel only)
    Local $control = ControlGetFocus($handle)
    If $control <> "DirectUIHWND3" Then Return
    ; Get selection (files selected in the right panel)
    Local $selected[1] = [0]
    For $element In $window.Document.SelectedItems()
        If $element.IsFolder Or $element.IsLink Then ContinueLoop
        Local $path = $element.Path
        For $i = 1 To $selected[0]
            If $path = $selected[$i] Then ContinueLoop 2
        Next
        $selected[0] = $selected[0]+1
        ReDim $selected[$selected[0]+1]
        $selected[$selected[0]] = $path
    Next
    ; Action : ###############################
EndFunc


问:
How to get dynamic taxes from location in UBER API?
I want create a APP MOBILE and i need use a UBER API.

I need get dynamic taxes in my location.

I can find a Class or Method to get this infos in UBER API.

Can someone help me?

答: please see the documentation for Uber's API at developer.uber.com. If you are asking for a dynamic location of all Uber drivers around you, that is not something available through Uber's API. Thanks. </p>


问:
ansible ssh error during pre ping to cisco device
Could not connect to Cisco router using Ansible 2.3.1.0

straight from linux ssh cisco@172.1.1.2 works

but the ansible -m ping all doesnt.
Maybe it's clear where could be a problem from this output:

```<code>[osboxes@osboxes ~]$ ansible -m ping servers -vvv

Using /etc/ansible/ansible.cfg as config file
META: ran handlers
Using module file /usr/lib/python2.7/site-packages/ansible/modules/system/ping.py
<172.1.1.2> ESTABLISH SSH CONNECTION FOR USER: cisco
<172.1.1.2> SSH: EXEC sshpass -d12 ssh -C -o ControlMaster=auto -o ControlPersist=60s -o User=cisco -o ConnectTimeout=10 -o ControlPath=/home/osboxes/.ansible/cp/1ed8487ad4 172.1.1.2 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<172.1.1.2> (0, '\r\nLine has invalid autocommand "/bin/sh -c \'echo ~ && sleep 0\'"', '')
<172.1.1.2> ESTABLISH SSH CONNECTION FOR USER: cisco
<172.1.1.2> SSH: EXEC sshpass -d12 ssh -C -o ControlMaster=auto -o ControlPersist=60s -o User=cisco -o ConnectTimeout=10 -o ControlPath=/home/osboxes/.ansible/cp/1ed8487ad4 172.1.1.2 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo Line has invalid autocommand "/bin/sh -c '"'"'"'"'"'"'"'"'echo ~ && sleep 0'"'"'"'"'"'"'"'"'"/.ansible/tmp/ansible-tmp-1499178341.35-260752414357590 `" && echo ansible-tmp-1499178341.35-260752414357590="` echo Line has invalid autocommand "/bin/sh -c '"'"'"'"'"'"'"'"'echo ~ && sleep 0'"'"'"'"'"'"'"'"'"/.ansible/tmp/ansible-tmp-1499178341.35-260752414357590 `" ) && sleep 0'"'"''
<172.1.1.2> (0, '\r\nLine has invalid autocommand "/bin/sh -c \'( umask 77 && mkdir -p "` echo Line has invalid autocommand "/bin/sh -c \'"\'"\'echo ~ && sleep 0\'"\'"\'"/.ansible/tmp/ansible-tmp-1499178341.35-260752414357590 `" && echo ansible-tmp-1499178341.35-260752414357590="` echo Line has invalid autocomma"', 'muxclient: master hello exchange failed\r\n')
<172.1.1.2> PUT /tmp/tmpacZGSy TO "` echo Line has invalid autocomma"/ping.py
<172.1.1.2> SSH: EXEC sshpass -d12 sftp -o BatchMode=no -b - -C -o ControlMaster=auto -o ControlPersist=60s -o User=cisco -o ConnectTimeout=10 -o ControlPath=/home/osboxes/.ansible/cp/1ed8487ad4 '[172.1.1.2]'
<172.1.1.2> (255, '', 'Connection closed\r\n')
172.1.1.2 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Connection closed\r\n",
    "unreachable": true
</code>```

thanks for any tips.

答:
It looks as if you're connecting to a Cisco device. As IOS doesn't offer a /bin/sh command, you won't be able to use ansible's ping module (or any other standard module, for that matter).

You could however try to do something with the raw module, which allows to send commands without going through the module subsystem. There seem to be some bugs related to that module when it comes to Cisco devices, though, so you might need to update to a very recent ansible version.

Body:
Could not connect to Cisco router using Ansible 2.3.1.0

straight from linux ssh cisco@172.1.1.2 works

but the ansible -m ping all doesnt.
Maybe it's clear where could be a problem from this output:

[osboxes@osboxes ~]$ ansible -m ping servers -vvv

Using /etc/ansible/ansible.cfg as config file
META: ran handlers
Using module file /usr/lib/python2.7/site-packages/ansible/modules/system/ping.py
<172.1.1.2> ESTABLISH SSH CONNECTION FOR USER: cisco
<172.1.1.2> SSH: EXEC sshpass -d12 ssh -C -o ControlMaster=auto -o ControlPersist=60s -o User=cisco -o ConnectTimeout=10 -o ControlPath=/home/osboxes/.ansible/cp/1ed8487ad4 172.1.1.2 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<172.1.1.2> (0, '\r\nLine has invalid autocommand "/bin/sh -c \'echo ~ && sleep 0\'"', '')
<172.1.1.2> ESTABLISH SSH CONNECTION FOR USER: cisco
<172.1.1.2> SSH: EXEC sshpass -d12 ssh -C -o ControlMaster=auto -o ControlPersist=60s -o User=cisco -o ConnectTimeout=10 -o ControlPath=/home/osboxes/.ansible/cp/1ed8487ad4 172.1.1.2 '/bin/sh -c '"'"'( umask 77 && mkdir -p "` echo Line has invalid autocommand "/bin/sh -c '"'"'"'"'"'"'"'"'echo ~ && sleep 0'"'"'"'"'"'"'"'"'"/.ansible/tmp/ansible-tmp-1499178341.35-260752414357590 `" && echo ansible-tmp-1499178341.35-260752414357590="` echo Line has invalid autocommand "/bin/sh -c '"'"'"'"'"'"'"'"'echo ~ && sleep 0'"'"'"'"'"'"'"'"'"/.ansible/tmp/ansible-tmp-1499178341.35-260752414357590 `" ) && sleep 0'"'"''
<172.1.1.2> (0, '\r\nLine has invalid autocommand "/bin/sh -c \'( umask 77 && mkdir -p "` echo Line has invalid autocommand "/bin/sh -c \'"\'"\'echo ~ && sleep 0\'"\'"\'"/.ansible/tmp/ansible-tmp-1499178341.35-260752414357590 `" && echo ansible-tmp-1499178341.35-260752414357590="` echo Line has invalid autocomma"', 'muxclient: master hello exchange failed\r\n')
<172.1.1.2> PUT /tmp/tmpacZGSy TO "` echo Line has invalid autocomma"/ping.py
<172.1.1.2> SSH: EXEC sshpass -d12 sftp -o BatchMode=no -b - -C -o ControlMaster=auto -o ControlPersist=60s -o User=cisco -o ConnectTimeout=10 -o ControlPath=/home/osboxes/.ansible/cp/1ed8487ad4 '[172.1.1.2]'
<172.1.1.2> (255, '', 'Connection closed\r\n')
172.1.1.2 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Connection closed\r\n",
    "unreachable": true

thanks for any tips.


问:
Failed to load resource: The network connection was lost Safari
Making XMLHttpRequests in iOS WKWebView when idle (in background) and locking screen causes the request to error out and we get this in the safari console log:

Failed to load resource: The network connection was lost

Does anyone know why Safari closes the connection? Or is it the server closing the connection?

Any help would be greatly appreciated.

答:
Are you by chance using Angular and also getting this error:

```<code>0 -  {"isTrusted":true}
</code>```

I have been getting the error you are getting along with this one.

In any sense I found this answer helpful because it's probably a CORS issue:

{"isTrusted":true} exception in core.umd.js

Hope that at least points you in the right direction.

Body:
Are you by chance using Angular and also getting this error:

0 -  {"isTrusted":true}

I have been getting the error you are getting along with this one.

In any sense I found this answer helpful because it's probably a CORS issue:

{"isTrusted":true} exception in core.umd.js

Hope that at least points you in the right direction.


问:
ExoPlayer2 - How to release from fragment
I have one activity with 2 fragments (not a ViewPager) & want to use ExoPlayer2 in one of the fragments to play content. The initial fragment shows a list of content & when clicked the second fragment is shown to play the selected content. However when I click back to the initial fragment I can still hear the content playing; it's as though the second fragment is still open. I'm (trying to) release the player this way:

```<code>@Override
public void onStop() {
    super.onStop();
    releasePlayer();
}

public void releasePlayer() {

    if (player != null) {
        player.setPlayWhenReady(true);
        player.stop();
        player.release();
        player = null;
        trackSelector = null;
        simpleExoPlayerView.setPlayer(null);
        simpleExoPlayerView = null;
        System.out.println("releasePlayer");
    }
}
</code>```

I read this but it didn't provide much of a solution. Also, read several posts where ExoPlayer is used in ViewPager fragments but not exactly sure how those examples released the player. Followed the releasePlayer() method from the demo app found here but no luck. Called releasePlayer() from onPause(), onDetach(), onDestroyView() but it made no difference.

Here's some logging set up after the listener is added to the player but don't see anything to explain why it's not releasing...

```<code>07-05 19:01:07.216 2529-2643/? V/RenderScript: 0xe0494000 Launching thread(s), CPUs 4
07-05 19:01:11.871 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.876 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:12.467 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:12.468 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:12.515 3064-3099/? V/SoftFFmpegVideo: got OMX_IndexParamPortDefinition, width: 320, height: 180
07-05 19:01:12.708 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:12.708 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:13.380 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:13.655 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:18.528 3064-3099/? V/SoftFFmpegVideo: ~SoftFFmpegVideo
</code>```

Tried the button click but it failed

```<code>fragmentExoBinding.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println("button click");
            releasePlayer();
        }
    });
</code>```

It was crashing everytime I shut it down (using back press, home or recent) b/c there's no longer a player. Updated the releasePlayer() method with if (player != null) but can still hear the content playing even after button click.

答:
I have a theory, but I’m not sure. To avoid writing over 9000 comments, I’ll post it is an answer.

Does the player stop (and gets released) if you add a <Button> to your Layout and onClick() call releasePlayer(); ?

If the above works, then override your activity’s onBackPressed() and before calling super.onBackPressed(), get your fragment’s instance and call the releasePlayer(). You can have your fragment implement some interface if you wanna please the Java people and pretend one day you will unit test that… or you can make the method public and cast it to your fragment and spend 5 seconds instead of wasting 5 minutes and 16kb of memory :)

Anyway, interface example:

```<code>public interface BackHandlerListener {
    void onBackPressed();
}
</code>```

Then have your fragment…

```<code>class MyFragment extends Fragment implements BackHandlerListener {
    @Override
    public void onBackPressed() {
        releasePlayer();
    }
}
</code>```

and your activity…

```<code>    @Override
    public void onBackPressed() {
        // get your fragment’s instance
        Fragment fragment =
         getSupportFragmentManager()
            .findFragmentById(R.id.your_fragment_container);

        if (fragment instanceof BackHandlerListener) {
            ((BackHandlerListener) fragment).onBackPressed();
        }

        super.onBackPressed();
    }
</code>```

You get the drill.

If #1 didn’t work, then there’s something weird going on with your player, that refuses to stop, but seems to be somewhat unrelated to the Fragment’s lifecycle. (*)

(*) Unless the problem is that the media player is dying when the fragment gets stopped and the reference gets leaked (because it’s native code). If this is the case, I’m afraid I’d have to read more about how ExoPlayer2 works these days (last time I used media player, ExoPlayer1 was a “beta” thing that promised a better experience, but didn’t work well with all devices). In those days, I had to use an Android Service to keep the MediaPlayer around and playing and send broadcast intents to my service to command it. ¯_(ツ)_/¯

Body:
I have one activity with 2 fragments (not a ViewPager) & want to use ExoPlayer2 in one of the fragments to play content. The initial fragment shows a list of content & when clicked the second fragment is shown to play the selected content. However when I click back to the initial fragment I can still hear the content playing; it's as though the second fragment is still open. I'm (trying to) release the player this way:

@Override
public void onStop() {
    super.onStop();
    releasePlayer();
}

public void releasePlayer() {

    if (player != null) {
        player.setPlayWhenReady(true);
        player.stop();
        player.release();
        player = null;
        trackSelector = null;
        simpleExoPlayerView.setPlayer(null);
        simpleExoPlayerView = null;
        System.out.println("releasePlayer");
    }
}

I read this but it didn't provide much of a solution. Also, read several posts where ExoPlayer is used in ViewPager fragments but not exactly sure how those examples released the player. Followed the releasePlayer() method from the demo app found here but no luck. Called releasePlayer() from onPause(), onDetach(), onDestroyView() but it made no difference.

Here's some logging set up after the listener is added to the player but don't see anything to explain why it's not releasing...

07-05 19:01:07.216 2529-2643/? V/RenderScript: 0xe0494000 Launching thread(s), CPUs 4
07-05 19:01:11.871 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.876 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:11.904 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:12.467 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:12.468 3064-3064/? V/MediaCodecInfo: Listener-onTimelineChanged...
07-05 19:01:12.515 3064-3099/? V/SoftFFmpegVideo: got OMX_IndexParamPortDefinition, width: 320, height: 180
07-05 19:01:12.708 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:12.708 3064-3064/? V/MediaCodecInfo: Listener-onPlayerStateChanged...
07-05 19:01:13.380 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:13.655 3064-3064/? V/MediaCodecInfo: Listener-onLoadingChanged...
07-05 19:01:18.528 3064-3099/? V/SoftFFmpegVideo: ~SoftFFmpegVideo

Tried the button click but it failed

fragmentExoBinding.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println("button click");
            releasePlayer();
        }
    });

It was crashing everytime I shut it down (using back press, home or recent) b/c there's no longer a player. Updated the releasePlayer() method with if (player != null) but can still hear the content playing even after button click.

Body:
I have a theory, but I’m not sure. To avoid writing over 9000 comments, I’ll post it is an answer.

Does the player stop (and gets released) if you add a <Button> to your Layout and onClick() call releasePlayer(); ?

If the above works, then override your activity’s onBackPressed() and before calling super.onBackPressed(), get your fragment’s instance and call the releasePlayer(). You can have your fragment implement some interface if you wanna please the Java people and pretend one day you will unit test that… or you can make the method public and cast it to your fragment and spend 5 seconds instead of wasting 5 minutes and 16kb of memory :)

Anyway, interface example:

public interface BackHandlerListener {
    void onBackPressed();
}

Then have your fragment…

class MyFragment extends Fragment implements BackHandlerListener {
    @Override
    public void onBackPressed() {
        releasePlayer();
    }
}

and your activity…

    @Override
    public void onBackPressed() {
        // get your fragment’s instance
        Fragment fragment =
         getSupportFragmentManager()
            .findFragmentById(R.id.your_fragment_container);

        if (fragment instanceof BackHandlerListener) {
            ((BackHandlerListener) fragment).onBackPressed();
        }

        super.onBackPressed();
    }

You get the drill.

If #1 didn’t work, then there’s something weird going on with your player, that refuses to stop, but seems to be somewhat unrelated to the Fragment’s lifecycle. (*)

(*) Unless the problem is that the media player is dying when the fragment gets stopped and the reference gets leaked (because it’s native code). If this is the case, I’m afraid I’d have to read more about how ExoPlayer2 works these days (last time I used media player, ExoPlayer1 was a “beta” thing that promised a better experience, but didn’t work well with all devices). In those days, I had to use an Android Service to keep the MediaPlayer around and playing and send broadcast intents to my service to command it. ¯_(ツ)_/¯


问:
Splitting Column Header Into Row Elements In R
After performing data analysis on a larger data set using R, I get output as shown in following sample data:

```<code>   A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1
</code>```

Currently, I am trying to split the column header into such that they appear in two different column as element, and I get the sum of the column they represented. It will look something like this:

```<code>   P1  P2  Sum
1   A   B   4
2   C   D   2
3   E   F   3
4   G   H   5
</code>```

For sum of each column, I can directly make use of colSums(), however I am getting tangled on how splitting the column header and making them appear as cell element described above.

Please let me know any suggestions on how I can approach this, thanks.

答:
This is my solution     </p>

```<code>library(tidyr)
library(dplyr)
df1=data.frame(melt(df))%>%group_by(variable)%>%dplyr::summarise(value=sum(value))
df2 <- separate(df1, variable, into = c("P1","P2"), sep = "_", extra = "merge")

     P1    P2 value
* <chr> <chr> <int>
1     A     B     4
2     C     D     2
3     E     F     3
4     G     H     5
</code>```

Body:
After performing data analysis on a larger data set using R, I get output as shown in following sample data:

   A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1

Currently, I am trying to split the column header into such that they appear in two different column as element, and I get the sum of the column they represented. It will look something like this:

   P1  P2  Sum
1   A   B   4
2   C   D   2
3   E   F   3
4   G   H   5

For sum of each column, I can directly make use of colSums(), however I am getting tangled on how splitting the column header and making them appear as cell element described above.

Please let me know any suggestions on how I can approach this, thanks.

Body:
This is my solution

library(tidyr)
library(dplyr)
df1=data.frame(melt(df))%>%group_by(variable)%>%dplyr::summarise(value=sum(value))
df2 <- separate(df1, variable, into = c("P1","P2"), sep = "_", extra = "merge")

     P1    P2 value
* <chr> <chr> <int>
1     A     B     4
2     C     D     2
3     E     F     3
4     G     H     5


问:
Unable to return nil in generic function
I am trying to understand generics better and am writing a function, that finds a key in a given dictionary with a given value.
If the value is not found it should return nil.

```<code>func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil //ERROR: Nil is incompatible with Type 'Key'
}
</code>```

I reveice this error:

Nil is incompatible with Type 'Key'

答:
Alternative implementation:

```<code>extension Dictionary where Value: Equatable {
    func key(forValue v: Value) -> Key? {
        return self.first(where: { $0.value == v})?.key
    }
}

["a": 1, "b": 2, "c": 3].key(forValue: 3) // => Optional("c")
</code>```

Note that in the case where two Keys map to the same Value v, it's not deterministic which of the two Keys will be returned. To get all Keys mapping the Value v, you can do this:

```<code>extension Dictionary where Value: Equatable {
    func keys(forValue v: Value) -> [Key] {
        return self.filter{ $0.value == v}.map{ $0.key }
    }
}

["a": 1, "b": 2, "c": 3, "d": 3].keys(forValue: 3) // => ["d", "c"]
</code>```

Body:
I am trying to understand generics better and am writing a function, that finds a key in a given dictionary with a given value.
If the value is not found it should return nil.

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key {
    for set in dictionary {
        if set.value == value {
            return set.key
        }
    }
    return nil //ERROR: Nil is incompatible with Type 'Key'
}

I reveice this error:

Nil is incompatible with Type 'Key'

Body:
Alternative implementation:

extension Dictionary where Value: Equatable {
    func key(forValue v: Value) -> Key? {
        return self.first(where: { $0.value == v})?.key
    }
}

["a": 1, "b": 2, "c": 3].key(forValue: 3) // => Optional("c")

Note that in the case where two Keys map to the same Value v, it's not deterministic which of the two Keys will be returned. To get all Keys mapping the Value v, you can do this:

extension Dictionary where Value: Equatable {
    func keys(forValue v: Value) -> [Key] {
        return self.filter{ $0.value == v}.map{ $0.key }
    }
}

["a": 1, "b": 2, "c": 3, "d": 3].keys(forValue: 3) // => ["d", "c"]


问:
EXCEL: COUNTIFS with multiple criteria and or logic
Attempting to count a named range "STATUS" if the value of the cells equals Reserved, Blocked, Pending OR Archive with multiple other countif criteria.

Everything else works, but the array formula I used for counting the status is only returning a count if the cell value = Reserved.

Here is the formula I'm using:

=(COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,{"Reserved","Blocked","Pending","Archive"}))

Any help would be greatly appreciated. Thank you in advance.

答:
Us Sum to countifs</p>

```<code>=SUM((COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,{"Reserved","Blocked","Pending","Archive"})))
</code>```

Body:
Us Sum to countifs

=SUM((COUNTIFS(DATES,">="&A3,DATES,"<"&EDATE(A3,1),AGENT,"TEST",COMPANY,"TEST",STATUS,{"Reserved","Blocked","Pending","Archive"})))


问:
why NPOI created cell drop down list always split by comma
I use NPOI(the .net version of java - Apache POI) created excel sheet. I need to add some dropdown, but I found no matter what list I passed into it, it always split the item value by comma, thus make a new line. In any chance, do you know how to avoid this happen?
Here is my code

```<code>CellRangeAddressList cellRange = new CellRangeAddressList(cell.RowIndex,
                        cell.RowIndex, cell.ColumnIndex, cell.ColumnIndex);
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(new string[]
                       {"$400","$1,900"});
HSSFDataValidation validation = new HSSFDataValidation(cellRange, constraint);
validation.SuppressDropDownArrow = false;
sheet.AddValidationData(validation);
</code>```

It always break $1,900 into two items as $1 and 900, here is the screenshot

答:
While passing the values to constraint you just pass the values without comma and $ sign  like this </p>

```<code>DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(new string[]{"400","1900"});
</code>```

<p>and below formatting approach will take care  of appearance of value in dropdown </p>

```<code>  XSSFCellStyle yourCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
    XSSFDataFormat yourDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
    yourCellStyle.SetDataFormat(yourDataFormat.GetFormat("$#,###.00"));
    sheet.SetDefaultColumnStyle(col, yourCellStyle);
</code>```

Body:
I use NPOI(the .net version of java - Apache POI) created excel sheet. I need to add some dropdown, but I found no matter what list I passed into it, it always split the item value by comma, thus make a new line. In any chance, do you know how to avoid this happen?
Here is my code

CellRangeAddressList cellRange = new CellRangeAddressList(cell.RowIndex,
                        cell.RowIndex, cell.ColumnIndex, cell.ColumnIndex);
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(new string[]
                       {"$400","$1,900"});
HSSFDataValidation validation = new HSSFDataValidation(cellRange, constraint);
validation.SuppressDropDownArrow = false;
sheet.AddValidationData(validation);

It always break $1,900 into two items as $1 and 900, here is the screenshot

Body:
While passing the values to constraint you just pass the values without comma and $ sign  like this

DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(new string[]{"400","1900"});

and below formatting approach will take care  of appearance of value in dropdown

  XSSFCellStyle yourCellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
    XSSFDataFormat yourDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
    yourCellStyle.SetDataFormat(yourDataFormat.GetFormat("$#,###.00"));
    sheet.SetDefaultColumnStyle(col, yourCellStyle);