问:
How to create a sub array from another array in Java?
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

```<code>methodName(object array, int start, int end)
</code>```

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

```<code>import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}
</code>```

答:
You can use

JDK > 1.5

```<code>Arrays.copyOfRange(Object[] src, int from, int to)
</code>```

Javadoc

JDK <= 1.5

```<code>System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices);
</code>```

Javadoc

Body:
How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end)

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;

public class testing
{
    public static void main(String [] arg)
    {
        int[] src = new int[] {1, 2, 3, 4, 5};
        int b1[] = Arrays.copyOfRange(src, 0, 2);
    }
}

Body:
You can use

JDK > 1.5

Arrays.copyOfRange(Object[] src, int from, int to)

Javadoc

JDK <= 1.5

System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices);

Javadoc


来源: stackexchange

问:
Using firebase jwt to authenticate users to external server\service?
Okay so in my iOS app I log the user into firebase, then get the jwt token. So now I have my server with an api which accepts an idtoken in the header of the GET.

What do I do here?  Certainly I wouldn't be validating the JWT againt firebase on every single API call right?  I mean its fast, but that adds latency with a second external check, no?  How does one simply just decode that guy in C#?  I have an Auth0 layer already and that decodes the JWT with my server-stored secret, but that same code doesn't work for the Firebase token.

Could it just be decoded then extract the user details from that, maybe just check expiry and if expiry > X months it's still okay?

答:
In order to verify Firebase ID tokens and JWTs in general, you only make a network call on your server to get the public certs which are usually not updated for several hours. You could cache that and try to verify with an ID token and if it fails, only then, load the new public certs.

And yes, you must verify the ID token on each call especially since Firebase ID tokens expire after typically an hour and need to be refreshed continuously.

ContentLicense: CC BY-SA 3.0


问:
How to display ajax returned message using toaster in C#?
As being the beginner in C#, I am struggling on displaying a toast message. I have an aspx page in which I have to display toast message once a button is clicked. I had added a hidden field for toast message:

```<code><button class="BtnCart" onclick="return addToCart(event)" title="Add"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Add to Cart </button>
<asp:HiddenField runat="server" Value="0"/>
</code>```

I have a ajax call which returns the message that I need to display in the toast. I had initiated doing as following please help me out here.

```<code><script src="scripts/toastr.min.js" type="text/javascript"></script>
   <script type="text/javascript">
        $(document).ready(function () {
            $(".showToast").click(function () {
            });
        });
        function addToCart(event) {
            console.log(event.target);
            var Id = $(event.target).parent().find('.Id').val();
            var qty = $(event.target).parents('#searchbottom').find('#qty').val();

            console.log(Id);
            console.log(qty);
            var item = {};
            item.Id = Id;
            item.quantity = qty;

            $.ajax({
                type: 'POST',
                url: '/api/shop/Add',
                data: JSON.stringify(item),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json'
            }).done(log);

            return false;
        }
        function log(data) {
            console.log(data);
           // alert(data.message);
        }

        function pageLoad(sender, args) {
            if (args.get_isPartialLoad()) {

                toastr.options = {
                    "closeButton": false,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast",
                    "preventDuplicates": false,
                    "onclick": null,
                    "showDuration": "10",
                    "hideDuration": "10",
                    "timeOut": "5000",
                    "extendedTimeOut": "10",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut",
                    'body-output-type': 'trustedHtml'
                }
                toastr.success(data.value);
</code>```

答:
Change your tag button like this:

<button class="BtnCart" id="AddToCart" title="Add"> Add to Cart </button>```
</div>
</div>
</p>

<p>And your script like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script src="scripts/toastr.min.js" type="text/javascrip"></script>
<script type="text/javascript">

$(function(){
 toastr.options = {
  "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": false,
        "positionClass": "toast-top-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "100000",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut",
        'body-output-type': 'trustedHtml'
    };

    $("#AddToCart").on("click", function (event) {
        console.log(event.target);
        var Id = $(event.target).parent().find('.Id').val();
        var qty = $(event.target).parents('#searchbottom').find('#qty').val();

        console.log(Id);
        console.log(qty);
        var item = {};
        item.Id = Id;
        item.quantity = qty;

        $.ajax({
            type: 'POST',
            url: '/api/shop/Add',
            data: JSON.stringify(item),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        }).done(function (data) {
   log(data);//console.log(data);
   toastr.success(data.value);//you display your message in here
  });

        return;
    });

    function log(data) {
        console.log(data);//I see this unnecessary
    };
});
</script></code>```

Body:
As being the beginner in C#, I am struggling on displaying a toast message. I have an aspx page in which I have to display toast message once a button is clicked. I had added a hidden field for toast message:

<button class="BtnCart" onclick="return addToCart(event)" title="Add"> Add to Cart </button>
<asp:HiddenField runat="server" Value="0"/>

I have a ajax call which returns the message that I need to display in the toast. I had initiated doing as following please help me out here.

Body:
Change your tag button like this:

<button class="BtnCart" id="AddToCart" title="Add"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Add to Cart </button>

And your script like this:

<script src="scripts/toastr.min.js" type="text/javascrip"></script>
<script type="text/javascript">

$(function(){
 toastr.options = {
  "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": false,
        "positionClass": "toast-top-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "100000",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut",
        'body-output-type': 'trustedHtml'
    };

    $("#AddToCart").on("click", function (event) {
        console.log(event.target);
        var Id = $(event.target).parent().find('.Id').val();
        var qty = $(event.target).parents('#searchbottom').find('#qty').val();

        console.log(Id);
        console.log(qty);
        var item = {};
        item.Id = Id;
        item.quantity = qty;

        $.ajax({
            type: 'POST',
            url: '/api/shop/Add',
            data: JSON.stringify(item),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        }).done(function (data) {
   log(data);//console.log(data);
   toastr.success(data.value);//you display your message in here
  });

        return;
    });

    function log(data) {
        console.log(data);//I see this unnecessary
    };
});
</script>


问:
reversing order of CSS transitions
I have a menu button, and a hidden list. I'm toggling classes to create a drop-down effect.

When the classes are added, it opens the drop-down just fine.

However on the removal of the classes, as you'll see in the following code snippet, the transition isn't as seamless. Basically what I'd like to do is reverse the order the transitions happen in, but I'm not sure how to accomplish this.

Thanks for the help.

$('.contact-menu-button').children('svg').click(function (event) {
 event.stopPropagation();
  $('.contact-menu-items').toggleClass('show');
  $('.contact-menu-button').children('svg').toggleClass('rotate');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Kanit:200,400);

* {
  font-family: Kanit, sans-serif;
}

div {
  display: inline-block;
  padding: 5px;
}

.container {
  width: 90%;
  color: #fff;
  background-color: #4a7ff7;
  border-radius: 8px 8px 0 0;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.4);
}

.active-contact {
  padding-right: 0;
}

.contact-menu {
  position: relative;
  padding-left: 0;
}

.contact-menu-button {
  background-color: transparent;
  border: none;
  border-radius: 4px;
  outline: none;
  color: #fff;
  padding: 0;
  width: 25px;
  cursor: pointer;
  transform: translateY(3px);
}

.contact-menu-button > svg {
    height: 20px;
    width: 20px;
    border-radius: 15px;
    stroke: #fff;
    transition: transform 250ms linear, border-radius 250ms ease-in 275ms;
}

.contact-menu-button > svg:hover {
  background-color: #fff;
  stroke: #4a7ff7;
}

.contact-menu-button > svg:active {
    stroke: #fff;
    background-color: #000;
}

.contact-menu-button > .rotate {
    background-color: #000;
    border-radius: 0 0 15px 15px;
    transform: rotate(180deg);
}

.contact-menu-button > .rotate:hover {
  background-color: #000;
  stroke: #fff;
}

.contact-menu-items {
    visibility: hidden;
    height: 0;
    overflow: hidden;
    color: #fff;
    position: absolute;
    list-style-type: none;
    padding: 10px 0;
    margin: 0 5px 5px 5px;
    border-radius: 6px 0 6px 6px;
    background-color: #000;
    transform: translate(-57px, -6px);
    transition: visibility 250ms ease-out 550ms, height 250ms ease-out 550ms;
}

.contact-menu-items > li {
    padding: 1px 15px 1px 15px;
}

.contact-menu-items.show {
    visibility: visible;
    height: 50px;
}

.contact-menu-items > li:hover {
    background-color: #fff;
    color: #000;
}</code>```

    John Smith

    <button class="contact-menu-button">
      <svg>
        <path d="M4 9 l 6 5 l 6 -5" stroke-width="1.5" fill="none" />
      </svg>
    </button>

        Edit

        Delete

```

答:
You can set the transition times both on the base and the transformed state:

$('.contact-menu-button').children('svg').click(function (event) {
 event.stopPropagation();
  $('.contact-menu-items').toggleClass('show');
  $('.contact-menu-button').children('svg').toggleClass('rotate');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Kanit:200,400);

* {
  font-family: Kanit, sans-serif;
}

div {
  display: inline-block;
  padding: 5px;
}

.container {
  width: 90%;
  color: #fff;
  background-color: #4a7ff7;
  border-radius: 8px 8px 0 0;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.4);
}

.active-contact {
  padding-right: 0;
}

.contact-menu {
  position: relative;
  padding-left: 0;
}

.contact-menu-button {
  background-color: transparent;
  border: none;
  border-radius: 4px;
  outline: none;
  color: #fff;
  padding: 0;
  width: 25px;
  cursor: pointer;
  transform: translateY(3px);
}

.contact-menu-button > svg {
    height: 20px;
    width: 20px;
    border-radius: 15px;
    stroke: #fff;
    transition: transform 250ms linear 275ms, border-radius 250ms ease-in 0ms;
}

.contact-menu-button > svg:hover {
  background-color: #fff;
  stroke: #4a7ff7;
}

.contact-menu-button > svg:active {
    stroke: #fff;
    background-color: #000;
}

.contact-menu-button > .rotate {
    background-color: #000;
    border-radius: 0 0 15px 15px;
    transform: rotate(180deg);
    transition: transform 250ms linear, border-radius 250ms ease-in 275ms;
}

.contact-menu-button > .rotate:hover {
  background-color: #000;
  stroke: #fff;
}

.contact-menu-items {
    visibility: hidden;
    height: 0;
    overflow: hidden;
    color: #fff;
    position: absolute;
    list-style-type: none;
    padding: 10px 0;
    margin: 0 5px 5px 5px;
    border-radius: 6px 0 6px 6px;
    background-color: #000;
    transform: translate(-57px, -6px);
    transition: visibility 250ms ease-out, height 250ms ease-out;
}

.contact-menu-items > li {
    padding: 1px 15px 1px 15px;
}

.contact-menu-items.show {
    visibility: visible;
    height: 50px;
    transition: visibility 250ms ease-out 550ms, height 250ms ease-out 550ms;
}

.contact-menu-items > li:hover {
    background-color: #fff;
    color: #000;
}</code>```

    John Smith

    <button class="contact-menu-button">
      <svg>
        <path d="M4 9 l 6 5 l 6 -5" stroke-width="1.5" fill="none" />
      </svg>
    </button>

        Edit

        Delete

```

Title: reversing order of CSS transitions

Body:
I have a menu button, and a hidden list. I'm toggling classes to create a drop-down effect.

When the classes are added, it opens the drop-down just fine.

However on the removal of the classes, as you'll see in the following code snippet, the transition isn't as seamless. Basically what I'd like to do is reverse the order the transitions happen in, but I'm not sure how to accomplish this.

Thanks for the help.

$('.contact-menu-button').children('svg').click(function (event) {
 event.stopPropagation();
  $('.contact-menu-items').toggleClass('show');
  $('.contact-menu-button').children('svg').toggleClass('rotate');
});

@import url(https://fonts.googleapis.com/css?family=Kanit:200,400);

* {
  font-family: Kanit, sans-serif;
}

div {
  display: inline-block;
  padding: 5px;
}

.container {
  width: 90%;
  color: #fff;
  background-color: #4a7ff7;
  border-radius: 8px 8px 0 0;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.4);
}

.active-contact {
  padding-right: 0;
}

.contact-menu {
  position: relative;
  padding-left: 0;
}

.contact-menu-button {
  background-color: transparent;
  border: none;
  border-radius: 4px;
  outline: none;
  color: #fff;
  padding: 0;
  width: 25px;
  cursor: pointer;
  transform: translateY(3px);
}

.contact-menu-button > svg {
    height: 20px;
    width: 20px;
    border-radius: 15px;
    stroke: #fff;
    transition: transform 250ms linear, border-radius 250ms ease-in 275ms;
}

.contact-menu-button > svg:hover {
  background-color: #fff;
  stroke: #4a7ff7;
}

.contact-menu-button > svg:active {
    stroke: #fff;
    background-color: #000;
}

.contact-menu-button > .rotate {
    background-color: #000;
    border-radius: 0 0 15px 15px;
    transform: rotate(180deg);
}

.contact-menu-button > .rotate:hover {
  background-color: #000;
  stroke: #fff;
}

.contact-menu-items {
    visibility: hidden;
    height: 0;
    overflow: hidden;
    color: #fff;
    position: absolute;
    list-style-type: none;
    padding: 10px 0;
    margin: 0 5px 5px 5px;
    border-radius: 6px 0 6px 6px;
    background-color: #000;
    transform: translate(-57px, -6px);
    transition: visibility 250ms ease-out 550ms, height 250ms ease-out 550ms;
}

.contact-menu-items > li {
    padding: 1px 15px 1px 15px;
}

.contact-menu-items.show {
    visibility: visible;
    height: 50px;
}

.contact-menu-items > li:hover {
    background-color: #fff;
    color: #000;
}

    John Smith

    <button class="contact-menu-button">
      <svg>
        <path d="M4 9 l 6 5 l 6 -5" stroke-width="1.5" fill="none" />
      </svg>
    </button>

        Edit

        Delete

Body:
You can set the transition times both on the base and the transformed state:

$('.contact-menu-button').children('svg').click(function (event) {
 event.stopPropagation();
  $('.contact-menu-items').toggleClass('show');
  $('.contact-menu-button').children('svg').toggleClass('rotate');
});

@import url(https://fonts.googleapis.com/css?family=Kanit:200,400);

* {
  font-family: Kanit, sans-serif;
}

div {
  display: inline-block;
  padding: 5px;
}

.container {
  width: 90%;
  color: #fff;
  background-color: #4a7ff7;
  border-radius: 8px 8px 0 0;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.4);
}

.active-contact {
  padding-right: 0;
}

.contact-menu {
  position: relative;
  padding-left: 0;
}

.contact-menu-button {
  background-color: transparent;
  border: none;
  border-radius: 4px;
  outline: none;
  color: #fff;
  padding: 0;
  width: 25px;
  cursor: pointer;
  transform: translateY(3px);
}

.contact-menu-button > svg {
    height: 20px;
    width: 20px;
    border-radius: 15px;
    stroke: #fff;
    transition: transform 250ms linear 275ms, border-radius 250ms ease-in 0ms;
}

.contact-menu-button > svg:hover {
  background-color: #fff;
  stroke: #4a7ff7;
}

.contact-menu-button > svg:active {
    stroke: #fff;
    background-color: #000;
}

.contact-menu-button > .rotate {
    background-color: #000;
    border-radius: 0 0 15px 15px;
    transform: rotate(180deg);
    transition: transform 250ms linear, border-radius 250ms ease-in 275ms;
}

.contact-menu-button > .rotate:hover {
  background-color: #000;
  stroke: #fff;
}

.contact-menu-items {
    visibility: hidden;
    height: 0;
    overflow: hidden;
    color: #fff;
    position: absolute;
    list-style-type: none;
    padding: 10px 0;
    margin: 0 5px 5px 5px;
    border-radius: 6px 0 6px 6px;
    background-color: #000;
    transform: translate(-57px, -6px);
    transition: visibility 250ms ease-out, height 250ms ease-out;
}

.contact-menu-items > li {
    padding: 1px 15px 1px 15px;
}

.contact-menu-items.show {
    visibility: visible;
    height: 50px;
    transition: visibility 250ms ease-out 550ms, height 250ms ease-out 550ms;
}

.contact-menu-items > li:hover {
    background-color: #fff;
    color: #000;
}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="container">
  <div class="active-contact">
    John Smith
  </div>
  <div class="contact-menu">
    <button class="contact-menu-button">
      <svg>
        <path d="M4 9 l 6 5 l 6 -5" stroke-width="1.5" fill="none" />
      </svg>
    </button>
    <ul class="contact-menu-items">
      <li>
        <a>Edit</a>
      </li>
      <li>
        <a>Delete</a>
      </li>
    </ul>
  </div>
</div>


问:
How to get CNTK Parallel Speedup on SequenceToSequence Example
I cloned the CNTK repository last week and built it using Nvidia-docker running on a p2.8xlarge instance on AWS. Everything appears to be working, except that I'm not getting a speedup from running multiple GPUs when enabling 1-bit SGD. I'm running the CMUDict Sequence2Sequence_distributed.py example. Here is my transcript when I run it on one GPU:

```<code>root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# python Sequence2Sequence_Distributed.py
Selected GPU[0] Tesla K80 as the process wide default device.
ping [requestnodes (before change)]: 1 nodes pinging each other
ping [requestnodes (after change)]: 1 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 1 out of 1 MPI nodes on a single host (1 requested); we (0) are in (participating)
ping [mpihelper]: 1 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------
Finished Epoch[1 of 160]: [Training] loss = 4.234002 * 64, metric = 98.44% * 64 3.014s ( 21.2 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.231473 * 71, metric = 85.92% * 71 1.013s ( 70.1 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.227827 * 61, metric = 81.97% * 61 0.953s ( 64.0 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.227088 * 68, metric = 86.76% * 68 0.970s ( 70.1 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.222957 * 62, metric = 88.71% * 62 0.922s ( 67.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.221479 * 63, metric = 84.13% * 63 0.950s ( 66.3 samples/s);
</code>```

Here's the transcript when I run two GPUs:

```<code>root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# mpiexec --allow-run-as-root --npernode 2 python Sequence2Sequence_Distributed.py -q 1

Selected GPU[0] Tesla K80 as the process wide default device.
Selected CPU as the process wide default device.
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (0) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (1) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------

-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------
</code>```

Here's an error message -- does this mean the GPUs are not being utilized when I run the job as two MPI processes? How would I fix this?

```<code>NcclComm: disabled, at least one rank using CPU device
NcclComm: disabled, at least one rank using CPU device
</code>```

You can see the number of samples/s is down:

```<code>Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.377s ( 13.6 samples/s);
Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.877s ( 12.4 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.196s ( 30.5 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.197s ( 30.5 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.667s ( 27.6 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.666s ( 27.6 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);
</code>```

答:
By default Sequence2Sequence_distributed.py runs data parallel SGD with 32-bit. Can you try other distributed training algorithms, like block momentum with a warm-start?

Besides, consider increase your minibatch size (the default is 16) if you want better parallelism with multiple GPU. You can use nvidia-smi to check GPU utilization and memory usage.

Body:
I cloned the CNTK repository last week and built it using Nvidia-docker running on a p2.8xlarge instance on AWS. Everything appears to be working, except that I'm not getting a speedup from running multiple GPUs when enabling 1-bit SGD. I'm running the CMUDict Sequence2Sequence_distributed.py example. Here is my transcript when I run it on one GPU:

root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# python Sequence2Sequence_Distributed.py
Selected GPU[0] Tesla K80 as the process wide default device.
ping [requestnodes (before change)]: 1 nodes pinging each other
ping [requestnodes (after change)]: 1 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 1 out of 1 MPI nodes on a single host (1 requested); we (0) are in (participating)
ping [mpihelper]: 1 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------
Finished Epoch[1 of 160]: [Training] loss = 4.234002 * 64, metric = 98.44% * 64 3.014s ( 21.2 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.231473 * 71, metric = 85.92% * 71 1.013s ( 70.1 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.227827 * 61, metric = 81.97% * 61 0.953s ( 64.0 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.227088 * 68, metric = 86.76% * 68 0.970s ( 70.1 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.222957 * 62, metric = 88.71% * 62 0.922s ( 67.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.221479 * 63, metric = 84.13% * 63 0.950s ( 66.3 samples/s);

Here's the transcript when I run two GPUs:

root@cb3aab88d4e9:/cntk/Examples/SequenceToSequence/CMUDict/Python# mpiexec --allow-run-as-root --npernode 2 python Sequence2Sequence_Distributed.py -q 1

Selected GPU[0] Tesla K80 as the process wide default device.
Selected CPU as the process wide default device.
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (before change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
ping [requestnodes (after change)]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (0) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
requestnodes [MPIWrapperMpi]: using 2 out of 2 MPI nodes on a single host (2 requested); we (1) are in (participating)
ping [mpihelper]: 2 nodes pinging each other
-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------

-------------------------------------------------------------------
Build info:

                Built time: Jun  2 2017 19:46:11
                Last modified date: Fri Jun  2 19:21:14 2017
                Build type: release
                Build target: GPU
                With 1bit-SGD: yes
                With ASGD: yes
                Math lib: mkl
                CUDA_PATH: /usr/local/cuda
                CUB_PATH: /usr/local/cub-1.4.1
                CUDNN_PATH: /usr/local/cudnn
                Build Branch: master
                Build SHA1: 2bcdc9dff6dc6393813f6043d80e167fb31aed72
                Built by Source/CNTK/buildinfo.h$$0 on 72cb11c66133
                Build Path: /cntk
                MPI distribution: Open MPI
                MPI version: 1.10.3
-------------------------------------------------------------------

Here's an error message -- does this mean the GPUs are not being utilized when I run the job as two MPI processes? How would I fix this?

NcclComm: disabled, at least one rank using CPU device
NcclComm: disabled, at least one rank using CPU device

You can see the number of samples/s is down:

Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.377s ( 13.6 samples/s);
Finished Epoch[1 of 160]: [Training] loss = 4.233786 * 73, metric = 97.26% * 73 5.877s ( 12.4 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.196s ( 30.5 samples/s);
Finished Epoch[2 of 160]: [Training] loss = 4.232235 * 67, metric = 94.03% * 67 2.197s ( 30.5 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[3 of 160]: [Training] loss = 4.229795 * 54, metric = 83.33% * 54 2.227s ( 24.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[4 of 160]: [Training] loss = 4.229072 * 83, metric = 87.95% * 83 2.229s ( 37.2 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.667s ( 27.6 samples/s);
Finished Epoch[5 of 160]: [Training] loss = 4.227438 * 46, metric = 86.96% * 46 1.666s ( 27.6 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);
Finished Epoch[6 of 160]: [Training] loss = 4.225661 * 65, metric = 84.62% * 65 2.388s ( 27.2 samples/s);


问:
Key hash for Android-Facebook app
I'm working on an Android app, in which I want to integrate a Facebook
posting feature. I downloaded the Facebook-Android SDK, and I got
the readme.md (text file) in there, in which it is mentioned to generate
the key hash for Android. How do I generate it?</p>

答:
1) Create a key to sign your application, and remember the alias.

2) Install OpenSSL.

3) Put the bin folder of OpenSSL in your path.

4) Follow the steps mentioned under "Setup Single Sign-On" on the FB-Android-SDK page, and generate your Hash Key. Make sure you put the correct alias and keystore file name.

5) Create an application on Facebok, and under Mobile Devices tab, enter this Hash Key.

Title: Key hash for Android-Facebook app

ContentLicense: CC BY-SA 2.5


问:
How to include double quotes in spark sql concat?
I am trying to concat two columns with double quotes gets prefix and suffix at both these two columns . The code works ,but it gives me extra double quotes .

Input :

```<code>campaign_file_name_1, campaign_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,    1
campaign_file_name_1, campaign_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,    2
</code>```

Expected Output :

```<code> campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   "campaign_name_1"="1",  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   "campaign_name_1"="2",  2017-06-06 17:09:31
</code>```

Actual Output as Per code :

```<code> campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   """campaign_name_1""=""1""",  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   """campaign_name_1""=""2""",  2017-06-06 17:09:31
</code>```

Spark Code :

```<code> object campaignResultsMergerETL extends BaseETL {

      val now  = ApplicationUtil.getCurrentTimeStamp()
      val conf = new Configuration()
      val fs  = FileSystem.get(conf)
      val log = LoggerFactory.getLogger(this.getClass.getName)

           def main(args: Array[String]): Unit = {
               //---------------------
                  code for sqlContext Initialization

              //---------------------
            val campaignResultsDF  = sqlContext.read.format("com.databricks.spark.avro").load(campaignResultsLoc)
           campaignResultsDF.registerTempTable("campaign_results")
           val campaignGroupedDF =  sqlContext.sql(
  """
    |SELECT campaign_file_name,
    |campaign_name,
    |tracker_id,
    |SUM(campaign_measure) AS campaign_measure
    |FROM campaign_results
    |GROUP BY campaign_file_name,campaign_name,tracker_id
  """.stripMargin)

campaignGroupedDF.registerTempTable("campaign_results_full")

            val campaignMergedDF =  sqlContext.sql(
      s"""
        |SELECT campaign_file_name,
        |tracker_id,
        |CONCAT('\"',campaign_name, '\"','=','\"',campaign_measure,'\"'),
        |"$now" AS audit_timestamp
        |FROM campaign_results_full
""".stripMargin)

    saveAsCSVFiles(campaignMergedDF,campaignResultsExportLoc,numPartitions)

 }

     def saveAsCSVFiles(campaignMeasureDF:DataFrame,hdfs_output_loc:String,numPartitions:Int): Unit =
         {
              log.info("saveAsCSVFile method started")
              if (fs.exists(new Path(hdfs_output_loc))){
              fs.delete(new Path(hdfs_output_loc), true)
         }
         campaignMeasureDF.repartition(numPartitions).write.format("com.databricks.spark.csv").save(hdfs_output_loc)
        log.info("saveAsCSVFile method ended")
       }

    }
</code>```

Could someone help me to fix this issue?

答:
It looks like you enclosed = incorrectly in your CONCAT arguments.  Try:

```<code>|CONCAT('\"',campaign_name, '\"','=','\"',campaign_measure,'\"'),
</code>```

[UPDATE]

Maybe your Spark version is different from mine, it seems to work as expected for me:

```<code>val df = Seq(("x", "y")).toDF("a", "b")

df.createOrReplaceTempView("df")

val df2 = spark.sqlContext.sql("""SELECT a, b, CONCAT('"', a, '"="', b, '"') as a_eq_b FROM df""")

df2.show
+---+---+-------+
|  a|  b| a_eq_b|
+---+---+-------+
|  x|  y|"x"="y"|
+---+---+-------+

df2.coalesce(1).write.option("header", "true").csv("/path/to/df2.csv")

/path/to/df2.csv content:
a,b,a_eq_b
x,y,"\"x\"=\"y\""
</code>```

Now, you could optionally make quote null like in the following:

```<code>df2.coalesce(1).write.option("header", "true").option("quote", "\u0000").csv("/path/to/df2null.csv")

/path/to/df2null.csv content:
a,b,a_eq_b
x,y,"x"="y"
</code>```

Note that, though, if you need to read the CSV back on Spark, make sure you include the same quote option.

Body:
I am trying to concat two columns with double quotes gets prefix and suffix at both these two columns . The code works ,but it gives me extra double quotes .

Input :

campaign_file_name_1, campaign_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,    1
campaign_file_name_1, campaign_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,    2

Expected Output :

 campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   "campaign_name_1"="1",  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   "campaign_name_1"="2",  2017-06-06 17:09:31

Actual Output as Per code :

 campaign_file_name_1, shagdhsjagdhjsagdhrSqpaKa5saoaus89,   """campaign_name_1""=""1""",  2017-06-06 17:09:31
 campaign_file_name_1, sagdhsagdhasjkjkasihdklas872hjsdjk,   """campaign_name_1""=""2""",  2017-06-06 17:09:31

Spark Code :

 object campaignResultsMergerETL extends BaseETL {

      val now  = ApplicationUtil.getCurrentTimeStamp()
      val conf = new Configuration()
      val fs  = FileSystem.get(conf)
      val log = LoggerFactory.getLogger(this.getClass.getName)

           def main(args: Array[String]): Unit = {
               //---------------------
                  code for sqlContext Initialization

              //---------------------
            val campaignResultsDF  = sqlContext.read.format("com.databricks.spark.avro").load(campaignResultsLoc)
           campaignResultsDF.registerTempTable("campaign_results")
           val campaignGroupedDF =  sqlContext.sql(
  """
    |SELECT campaign_file_name,
    |campaign_name,
    |tracker_id,
    |SUM(campaign_measure) AS campaign_measure
    |FROM campaign_results
    |GROUP BY campaign_file_name,campaign_name,tracker_id
  """.stripMargin)

campaignGroupedDF.registerTempTable("campaign_results_full")

            val campaignMergedDF =  sqlContext.sql(
      s"""
        |SELECT campaign_file_name,
        |tracker_id,
        |CONCAT('\"',campaign_name, '\"','=','\"',campaign_measure,'\"'),
        |"$now" AS audit_timestamp
        |FROM campaign_results_full
""".stripMargin)

    saveAsCSVFiles(campaignMergedDF,campaignResultsExportLoc,numPartitions)

 }

     def saveAsCSVFiles(campaignMeasureDF:DataFrame,hdfs_output_loc:String,numPartitions:Int): Unit =
         {
              log.info("saveAsCSVFile method started")
              if (fs.exists(new Path(hdfs_output_loc))){
              fs.delete(new Path(hdfs_output_loc), true)
         }
         campaignMeasureDF.repartition(numPartitions).write.format("com.databricks.spark.csv").save(hdfs_output_loc)
        log.info("saveAsCSVFile method ended")
       }

    }

Could someone help me to fix this issue?

Body:
It looks like you enclosed = incorrectly in your CONCAT arguments.  Try:

|CONCAT('\"',campaign_name, '\"','=','\"',campaign_measure,'\"'),

[UPDATE]

Maybe your Spark version is different from mine, it seems to work as expected for me:

val df = Seq(("x", "y")).toDF("a", "b")

df.createOrReplaceTempView("df")

val df2 = spark.sqlContext.sql("""SELECT a, b, CONCAT('"', a, '"="', b, '"') as a_eq_b FROM df""")

df2.show
+---+---+-------+
|  a|  b| a_eq_b|
+---+---+-------+
|  x|  y|"x"="y"|
+---+---+-------+

df2.coalesce(1).write.option("header", "true").csv("/path/to/df2.csv")

/path/to/df2.csv content:
a,b,a_eq_b
x,y,"\"x\"=\"y\""

Now, you could optionally make quote null like in the following:

df2.coalesce(1).write.option("header", "true").option("quote", "\u0000").csv("/path/to/df2null.csv")

/path/to/df2null.csv content:
a,b,a_eq_b
x,y,"x"="y"

Note that, though, if you need to read the CSV back on Spark, make sure you include the same quote option.


问:
android custom Dialog with Button onClick event
i have CustomDialog.java like this :

```<code>public class CustomDialog {
Dialog dl;
public void ShowDialog(Context context, String message) {
    dl = new Dialog(context);
    dl.setContentView(R.layout.custom_dialog);

    TextView tv_message = (TextView) dl.findViewById(R.id.textViewMessage);

    tv_message.setText(message);

    Button bt_yes = (Button)dl.findViewById(R.id.buttonYes);
    Button bt_no = (Button)dl.findViewById(R.id.buttonNo);

    bt_yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckYes();
        }
    });
    bt_no.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dl.dismiss();
        }
    });
    dl.show();

}

public Boolean CheckYesNo(Boolean check){
    return check;
}

public Boolean CheckYes() {
    return true;
}

public void CloseDialog() {
    dl.dismiss();
}
</code>```

}

this is code in Activity to use CustomDialog :

```<code>CustomDialog cdl = new CustomDialog ();
                        cdl.ShowDialog(Activity1.this, "test");
                        if (cdl.CheckYesNo(true)) {
                            // doing something with data and go to Activity 2
                        }
                        else {
                            cdl.CloseDialog();
                        }
</code>```

I want like this :

1. In Activity1, when click ImageButton, CustomDialog will show.

2. after CustomDialog show, if click Button yes, it doing something with data and go to Activity2.

3. if click Button no, CustomDialog will close and don't doing something with data.

but my problem is :

when click ImageButton, CustomDialog show, the code I want to do with data will doing and auto go to Activity2.

I can't choose yes or no to click.

I think problem in Button yes onClick event.

how to fix it?

答:
For me I had to make sure that the dialog was created before accessing using findViewById on the dialog. Inside the inner class that I made the dialog in, in the OnStart callback function is where I accessed the buttons. I tried doing it outside the class when I said .show() but it was giving me a null pointer exception.

For me I the only way I could access buttons iD's in the dialog was through the dialog. I couldn't just do getActivity().findViewById(R.id.blah)

Here's the code I used:

```<code>        @Override
    public void onStart(){
        super.onStart();

        if(getDialog() == null){
            return;
        }
        else {

            ImageButton closeButton = (ImageButton)getDialog().findViewById(R.id.closeButton);

            closeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getDialog().dismiss();
                }
            });

        }
</code>```

Body:
i have CustomDialog.java like this :

public class CustomDialog {
Dialog dl;
public void ShowDialog(Context context, String message) {
    dl = new Dialog(context);
    dl.setContentView(R.layout.custom_dialog);

    TextView tv_message = (TextView) dl.findViewById(R.id.textViewMessage);

    tv_message.setText(message);

    Button bt_yes = (Button)dl.findViewById(R.id.buttonYes);
    Button bt_no = (Button)dl.findViewById(R.id.buttonNo);

    bt_yes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckYes();
        }
    });
    bt_no.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dl.dismiss();
        }
    });
    dl.show();

}

public Boolean CheckYesNo(Boolean check){
    return check;
}

public Boolean CheckYes() {
    return true;
}

public void CloseDialog() {
    dl.dismiss();
}

}

this is code in Activity to use CustomDialog :

CustomDialog cdl = new CustomDialog ();
                        cdl.ShowDialog(Activity1.this, "test");
                        if (cdl.CheckYesNo(true)) {
                            // doing something with data and go to Activity 2
                        }
                        else {
                            cdl.CloseDialog();
                        }

I want like this :

1. In Activity1, when click ImageButton, CustomDialog will show.

2. after CustomDialog show, if click Button yes, it doing something with data and go to Activity2.

3. if click Button no, CustomDialog will close and don't doing something with data.

but my problem is :

when click ImageButton, CustomDialog show, the code I want to do with data will doing and auto go to Activity2.

I can't choose yes or no to click.

I think problem in Button yes onClick event.

how to fix it?

Body:
For me I had to make sure that the dialog was created before accessing using findViewById on the dialog. Inside the inner class that I made the dialog in, in the OnStart callback function is where I accessed the buttons. I tried doing it outside the class when I said .show() but it was giving me a null pointer exception.

For me I the only way I could access buttons iD's in the dialog was through the dialog. I couldn't just do getActivity().findViewById(R.id.blah)

Here's the code I used:

        @Override
    public void onStart(){
        super.onStart();

        if(getDialog() == null){
            return;
        }
        else {

            ImageButton closeButton = (ImageButton)getDialog().findViewById(R.id.closeButton);

            closeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getDialog().dismiss();
                }
            });

        }


问:
How can I use System.Net.WebClient like PowerShell New-WebServiceProxy?
The issue I am having connecting to a service via PowerShell, versus using C#, is that the service is expecting a key passed in the header.

I can use new-WebServiceProxy with the URI and have it pass the default credentials. I can then get the time-limited service key, but for subsequent calls to the service, there is no way to pass the key, which results in an error that there is no valid service key.

I know the cmdlet uses the System.Net.WebClient class and that had a settable headers property that I want to try using. I just can't seem to get that class to behave the same way as the cmdlet and return an object. Does anyone know how?

This is what I am using but which to implement in .Net directly from PowerShell:

$QMSService = New-WebServiceProxy -Uri http://localhost:4799/QMS/Service -Namespace QlikViewServer -UseDefaultCredential
```

<p>That is the Powershell cmdlet I use to access the service. I would like to accomplish the same using:</p>

```$Client = New-Object System.Net.WebClient
$Client.UseDefaultCredentials = $true
$Client.BaseAddress = "http://localhost:4799/QMS/Service"
```

<p>I just can't figure out how to create a proxy object that gives me access to all the members the service provides, using System.Net.WebClient.  Once I set that, I can grab the TimeLimitedServiceKey and do this:</p>

```$ServiceKey = $ProxyObjectCreatedFromClient.GetTimeLimitedServiceKey()
$Client.Headers = "X-Service-Key", $ServiceKey
```

If someone could please help me on how to create the Proxy Object.

答:
It appears that the GetTimeLimitedServiceKey() method is from the QMSClient API:  https://help.qlik.com/en-US/qlikview-developer/12.1/apis/QMS%20API/html/2be1e405-a7e5-4a43-b1b6-9540b23a6226.htm

...meaning, you'll need to reference that third-party API directly (New-Object, Add-Type, Add-Type w/p/invoke, etc.) and then make the call to GetTimeLimitedServiceKey()

```<code>$service = New-WebServiceProxy -Uri http://someHost:4799/QMS/Service -Namespace QlikViewServer -Credential (get-credential)
$serviceKey = $service.GetTimeLimitedServiceKey()
</code>```

https://community.qlik.com/thread/143003

Body:
The issue I am having connecting to a service via PowerShell, versus using C#, is that the service is expecting a key passed in the header.

I can use new-WebServiceProxy with the URI and have it pass the default credentials. I can then get the time-limited service key, but for subsequent calls to the service, there is no way to pass the key, which results in an error that there is no valid service key.

I know the cmdlet uses the System.Net.WebClient class and that had a settable headers property that I want to try using. I just can't seem to get that class to behave the same way as the cmdlet and return an object. Does anyone know how?

This is what I am using but which to implement in .Net directly from PowerShell:

$QMSService = New-WebServiceProxy -Uri http://localhost:4799/QMS/Service -Namespace QlikViewServer -UseDefaultCredential

That is the Powershell cmdlet I use to access the service. I would like to accomplish the same using:

$Client = New-Object System.Net.WebClient
$Client.UseDefaultCredentials = $true
$Client.BaseAddress = "http://localhost:4799/QMS/Service"

I just can't figure out how to create a proxy object that gives me access to all the members the service provides, using System.Net.WebClient.  Once I set that, I can grab the TimeLimitedServiceKey and do this:

$ServiceKey = $ProxyObjectCreatedFromClient.GetTimeLimitedServiceKey()
$Client.Headers = "X-Service-Key", $ServiceKey

If someone could please help me on how to create the Proxy Object.

Body:
It appears that the GetTimeLimitedServiceKey() method is from the QMSClient API:  https://help.qlik.com/en-US/qlikview-developer/12.1/apis/QMS%20API/html/2be1e405-a7e5-4a43-b1b6-9540b23a6226.htm

...meaning, you'll need to reference that third-party API directly (New-Object, Add-Type, Add-Type w/p/invoke, etc.) and then make the call to GetTimeLimitedServiceKey()

$service = New-WebServiceProxy -Uri http://someHost:4799/QMS/Service -Namespace QlikViewServer -Credential (get-credential)
$serviceKey = $service.GetTimeLimitedServiceKey()

https://community.qlik.com/thread/143003


问:
Best way to export Express route methods for promise chains?
I have an API route that is being refactored to use ES6 promises to avoid callback hell.

After successfully converting to a promise chain, I wanted to export my .then() functions to a separate file for cleanliness and clarity.

The route file:

The functions file:

This works fine. However, what I'd like to do is move the functions declared in the Class constructor() function into independent methods, which can reference the values instantiated by the constructor. That way it all reads nicer.

But, when I do, I run into scoping problems - this is not defined, etc. What is the correct way to do this? Is an ES6 appropriate to use here, or should I use some other structure?

RAW CODE:

route...

```<code>.post((req, res) => {

  let SubmitRouteFunctions = require('./functions/submitFunctions.js');
  let fn = new SubmitRouteFunctions(req, res);

  // *******************************************
  // ***** THIS IS WHERE THE MAGIC HAPPENS *****
  // *******************************************
  Promise.all([fn.redundancyCheck, fn.getLocationInfo])
         .then(fn.resetRedundantID)
         .then(fn.constructSurveyResult)
         .then(fn.storeResultInDB)
         .then(fn.redirectToUniqueURL)
         .catch((err) => {
           console.log(err);
           res.send("ERROR SUBMITTING YOUR RESULT: ", err);
         });
  })
</code>```

exported functions...

```<code>module.exports = class SubmitRouteFunctions {

   constructor (req, res) {
this.res = res;
this.initialData = {
  answers    : req.body.responses,
  coreFit    : req.body.coreFit,
  secondFit  : req.body.secondFit,
  modules    : req.body.modules,
};

this.newId = shortid.generate();
this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false}).debug();
this.clientIp = requestIp.getClientIp(req);

this.redundancyCheck = mongoose.model('Result').findOne({quizId: this.newId});
this.getLocationInfo = request.get('http://freegeoip.net/json/' + this.clientIp).catch((err) => err);

this.resetRedundantID = ([mongooseResult, clientLocationPromise]) => {

    console.log(mongooseResult);
    if (mongooseResult != null) {
      console.log('REDUNDANT ID FOUND - GENERATING NEW ONE')
      this.newId = shortid.generate();
      this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false});
      console.log('NEW ID: ', this.newId);
    };
    return clientLocationPromise.data;
  }

this.constructSurveyResult = (clientLocation) => {
    let additionalData = {quizId: this.newId, location: clientLocation};
    return Object.assign({}, this.initialData, additionalData);
  }

this.storeResultInDB = (newResult) => mongoose.model('Result').create(newResult).then((result) => result).catch((err) => err);

this.redirectToUniqueURL = (mongooseResult) => {
  let parsedId = '?' + queryString.stringify({id: mongooseResult.quizId});
  let customUrl = 'http://explore-your-fit.herokuapp.com/results' + parsedId;
  this.res.send('/results' + parsedId);
}
  }
}
</code>```

答:
ALTERNATIVE #1:

Rather than using ES6 classes, an alternate way to perform the same behavior that cleans up the code just a little bit is to export an anonymous function as described by Nick Panov here: In Node.js, how do I "include" functions from my other files?

FUNCTIONS FILE:

```<code>module.exports = function (req, res) {

    this.initialData = {
      answers    : req.body.responses,
      coreFit    : req.body.coreFit,
      secondFit  : req.body.secondFit,
      modules    : req.body.modules,
    };

    this.newId = shortid.generate();
    this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false}).debug();
    this.clientIp = requestIp.getClientIp(req);

    this.redundancyCheck = mongoose.model('Result').findOne({quizId: this.newId});
    this.getLocationInfo = request.get('http://freegeoip.net/json/' + this.clientIp).catch((err) => err);

    this.resetRedundantID = ([mongooseResult, clientLocationPromise]) => {
        if (mongooseResult != null) {
          console.log('REDUNDANT ID FOUND - GENERATING NEW ONE')
          this.newId = shortid.generate();
          this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false});
          console.log('NEW ID: ', this.newId);
        };
        return clientLocationPromise.data;
      }

    this.constructSurveyResult = (clientLocation) => {
        let additionalData = {quizId: this.newId, location: clientLocation};
        return Object.assign({}, this.initialData, additionalData);
      }

    this.storeResultInDB = (newResult) => mongoose.model('Result').create(newResult).then((result) => result).catch((err) => err);

    this.redirectToUniqueURL = (mongooseResult) => {
      let parsedId = '?' + queryString.stringify({id: mongooseResult.quizId});
      let customUrl = 'http://explore-your-fit.herokuapp.com/results' + parsedId;
      res.send('/results' + parsedId);
    }
}
</code>```

Although this does not avoid having to tag each method with this.someFn()..., as I originally wanted, it does take an extra step in the routing file - doing things this way prevents me from having to assign a specific namespace to the methods.

ROUTES FILE

```<code>.post((req, res) => {
          require('./functions/submitFunctions_2.js')(req, res);

          Promise.all([redundancyCheck, getLocationInfo])
                 .then(resetRedundantID)
                 .then(constructSurveyResult)
                 .then(storeResultInDB)
                 .then(redirectToUniqueURL)
                 .catch((err) => {
                   console.log(err);
                   res.send("ERROR SUBMITTING YOUR RESULT: ", err);
                 });
      })
</code>```

The functions are reset to reflect each new req and res objects as POST requests hit the route, and the this keyword is apparently bound to the POST route callback in each of the imported methods.

IMPORTANT NOTE: You cannot export an arrow function using this method. The exported function must be a traditional, anonymous function. Here's why, per Udo G's comment on the same thread:

It should be worth to note that this works because this in a function is the global scope when the function is called directly (not bound in any way).

ALTERNATIVE #2:

Another option, courtesy of Bergi from: How to use arrow functions (public class fields) as class methods?

What I am looking for, really, is an experimental feature....

There is an proposal which might allow you to omit the constructor() and directly put the assignment in the class scope with the same functionality, but I wouldn't recommend to use that as it's highly experimental.

However, there is still a way to separate the methods:

Alternatively, you can always use .bind, which allows you to declare the method on the prototype and then bind it to the instance in the constructor. This approach has greater flexibility as it allows modifying the method from the outside of your class.

Based on Bergi's example:

```<code>module.exports = class SomeClass {

  constructor() {
    this.someMethod= this.someMethod.bind(this);
    this.someOtherMethod= this.someOtherMethod.bind(this);
    …
  }

  someMethod(val) {
    // Do something with val
  }

  someOtherMethod(val2) {
    // Do something with val2
  }
}
</code>```

Obviously, this is more in-line with what I was originally looking for, as it enhances the overall readability of the exported code. BUT doing so will require that you assign a namespace to the new class in your routes file like I did originally:

```<code>let SubmitRouteFunctions = require('./functions/submitFunctions.js');
let fn = new SubmitRouteFunctions(req, res);

Promise.all([fn.redundancyCheck, fn.getLocationInfo])
       .then(...)
</code>```

PROPOSED / EXPERIMENTAL FEATURE:

This is not really my wheelhouse, but per Bergi, there is currently a Stage-2 proposal (https://github.com/tc39/proposal-class-public-fields) that is attempting to get "class instance fields" added to the next ES spec.

"Class instance fields" describe properties intended to exist on
  instances of a class (and may optionally include initializer
  expressions for said properties)

As I understand it, this would solve the issue described here entirely, by allowing methods attached to class objects to reference each instantiation of itself. Therefore, this issues would disappear and methods could optionally be bound automatically.

My (limited) understanding is that the arrow function would be used to accomplish this, like so:

```<code>  class SomeClass {
      constructor() {...}
      someMethod (val) => {
        // Do something with val
        // Where 'this' is bound to the current instance of SomeClass
      }
    }
</code>```

Apparently this can be done now using a Babel compiler, but is obviously experimental and risky. Plus, in this case we're trying to do this in Node / Express which makes that almost a moot point :)

Body:
I have an API route that is being refactored to use ES6 promises to avoid callback hell.

After successfully converting to a promise chain, I wanted to export my .then() functions to a separate file for cleanliness and clarity.

The route file:

The functions file:

This works fine. However, what I'd like to do is move the functions declared in the Class constructor() function into independent methods, which can reference the values instantiated by the constructor. That way it all reads nicer.

But, when I do, I run into scoping problems - this is not defined, etc. What is the correct way to do this? Is an ES6 appropriate to use here, or should I use some other structure?

RAW CODE:

route...

.post((req, res) => {

  let SubmitRouteFunctions = require('./functions/submitFunctions.js');
  let fn = new SubmitRouteFunctions(req, res);

  // *******************************************
  // ***** THIS IS WHERE THE MAGIC HAPPENS *****
  // *******************************************
  Promise.all([fn.redundancyCheck, fn.getLocationInfo])
         .then(fn.resetRedundantID)
         .then(fn.constructSurveyResult)
         .then(fn.storeResultInDB)
         .then(fn.redirectToUniqueURL)
         .catch((err) => {
           console.log(err);
           res.send("ERROR SUBMITTING YOUR RESULT: ", err);
         });
  })

exported functions...

module.exports = class SubmitRouteFunctions {

   constructor (req, res) {
this.res = res;
this.initialData = {
  answers    : req.body.responses,
  coreFit    : req.body.coreFit,
  secondFit  : req.body.secondFit,
  modules    : req.body.modules,
};

this.newId = shortid.generate();
this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false}).debug();
this.clientIp = requestIp.getClientIp(req);

this.redundancyCheck = mongoose.model('Result').findOne({quizId: this.newId});
this.getLocationInfo = request.get('http://freegeoip.net/json/' + this.clientIp).catch((err) => err);

this.resetRedundantID = ([mongooseResult, clientLocationPromise]) => {

    console.log(mongooseResult);
    if (mongooseResult != null) {
      console.log('REDUNDANT ID FOUND - GENERATING NEW ONE')
      this.newId = shortid.generate();
      this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false});
      console.log('NEW ID: ', this.newId);
    };
    return clientLocationPromise.data;
  }

this.constructSurveyResult = (clientLocation) => {
    let additionalData = {quizId: this.newId, location: clientLocation};
    return Object.assign({}, this.initialData, additionalData);
  }

this.storeResultInDB = (newResult) => mongoose.model('Result').create(newResult).then((result) => result).catch((err) => err);

this.redirectToUniqueURL = (mongooseResult) => {
  let parsedId = '?' + queryString.stringify({id: mongooseResult.quizId});
  let customUrl = 'http://explore-your-fit.herokuapp.com/results' + parsedId;
  this.res.send('/results' + parsedId);
}
  }
}

Body:
ALTERNATIVE #1:

Rather than using ES6 classes, an alternate way to perform the same behavior that cleans up the code just a little bit is to export an anonymous function as described by Nick Panov here: In Node.js, how do I "include" functions from my other files?

FUNCTIONS FILE:

module.exports = function (req, res) {

    this.initialData = {
      answers    : req.body.responses,
      coreFit    : req.body.coreFit,
      secondFit  : req.body.secondFit,
      modules    : req.body.modules,
    };

    this.newId = shortid.generate();
    this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false}).debug();
    this.clientIp = requestIp.getClientIp(req);

    this.redundancyCheck = mongoose.model('Result').findOne({quizId: this.newId});
    this.getLocationInfo = request.get('http://freegeoip.net/json/' + this.clientIp).catch((err) => err);

    this.resetRedundantID = ([mongooseResult, clientLocationPromise]) => {
        if (mongooseResult != null) {
          console.log('REDUNDANT ID FOUND - GENERATING NEW ONE')
          this.newId = shortid.generate();
          this.visitor = ua('UA-83723251-1', this.newId, {strictCidFormat: false});
          console.log('NEW ID: ', this.newId);
        };
        return clientLocationPromise.data;
      }

    this.constructSurveyResult = (clientLocation) => {
        let additionalData = {quizId: this.newId, location: clientLocation};
        return Object.assign({}, this.initialData, additionalData);
      }

    this.storeResultInDB = (newResult) => mongoose.model('Result').create(newResult).then((result) => result).catch((err) => err);

    this.redirectToUniqueURL = (mongooseResult) => {
      let parsedId = '?' + queryString.stringify({id: mongooseResult.quizId});
      let customUrl = 'http://explore-your-fit.herokuapp.com/results' + parsedId;
      res.send('/results' + parsedId);
    }
}

Although this does not avoid having to tag each method with this.someFn()..., as I originally wanted, it does take an extra step in the routing file - doing things this way prevents me from having to assign a specific namespace to the methods.

ROUTES FILE

.post((req, res) => {
          require('./functions/submitFunctions_2.js')(req, res);

          Promise.all([redundancyCheck, getLocationInfo])
                 .then(resetRedundantID)
                 .then(constructSurveyResult)
                 .then(storeResultInDB)
                 .then(redirectToUniqueURL)
                 .catch((err) => {
                   console.log(err);
                   res.send("ERROR SUBMITTING YOUR RESULT: ", err);
                 });
      })

The functions are reset to reflect each new req and res objects as POST requests hit the route, and the this keyword is apparently bound to the POST route callback in each of the imported methods.

IMPORTANT NOTE: You cannot export an arrow function using this method. The exported function must be a traditional, anonymous function. Here's why, per Udo G's comment on the same thread:

It should be worth to note that this works because this in a function is the global scope when the function is called directly (not bound in any way).

ALTERNATIVE #2:

Another option, courtesy of Bergi from: How to use arrow functions (public class fields) as class methods?

What I am looking for, really, is an experimental feature....

There is an proposal which might allow you to omit the constructor() and directly put the assignment in the class scope with the same functionality, but I wouldn't recommend to use that as it's highly experimental.

However, there is still a way to separate the methods:

Alternatively, you can always use .bind, which allows you to declare the method on the prototype and then bind it to the instance in the constructor. This approach has greater flexibility as it allows modifying the method from the outside of your class.

Based on Bergi's example:

module.exports = class SomeClass {

  constructor() {
    this.someMethod= this.someMethod.bind(this);
    this.someOtherMethod= this.someOtherMethod.bind(this);
    …
  }

  someMethod(val) {
    // Do something with val
  }

  someOtherMethod(val2) {
    // Do something with val2
  }
}

Obviously, this is more in-line with what I was originally looking for, as it enhances the overall readability of the exported code. BUT doing so will require that you assign a namespace to the new class in your routes file like I did originally:

let SubmitRouteFunctions = require('./functions/submitFunctions.js');
let fn = new SubmitRouteFunctions(req, res);

Promise.all([fn.redundancyCheck, fn.getLocationInfo])
       .then(...)

PROPOSED / EXPERIMENTAL FEATURE:

This is not really my wheelhouse, but per Bergi, there is currently a Stage-2 proposal (https://github.com/tc39/proposal-class-public-fields) that is attempting to get "class instance fields" added to the next ES spec.

"Class instance fields" describe properties intended to exist on
  instances of a class (and may optionally include initializer
  expressions for said properties)

As I understand it, this would solve the issue described here entirely, by allowing methods attached to class objects to reference each instantiation of itself. Therefore, this issues would disappear and methods could optionally be bound automatically.

My (limited) understanding is that the arrow function would be used to accomplish this, like so:

  class SomeClass {
      constructor() {...}
      someMethod (val) => {
        // Do something with val
        // Where 'this' is bound to the current instance of SomeClass
      }
    }

Apparently this can be done now using a Babel compiler, but is obviously experimental and risky. Plus, in this case we're trying to do this in Node / Express which makes that almost a moot point :)


问:
Reference View From Included Layout
I have a fragment layout with the following include tag:

```<code><include
    android:id="@+id/ivRemoveData"
    layout="@layout/item_menu"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_margin="16dp"
    android:visibility="visible"/>
</code>```

item_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ImageView
    android:id="@+id/ivIcon"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_centerInParent="true"

    android:visibility="gone"
    android:background="@drawable/not_passed_circle_level_item"
    android:clipChildren="false"
    android:clipToPadding="false"/>
</code>```

I need to use method ivIcon.setImageResource().

My fragment class:

```<code>import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_options.*
import kotlinx.android.synthetic.main.item_menu.view.*

class OptionsFragment : BaseFragment(), OptionsMVP.View
{
    override fun onCreateView(inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle?) : View?
    {
        val view = inflater.inflate(R.layout.fragment_options, container, false)
        return view
    }

    override fun onViewCreated(view : View?, savedInstanceState : Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)

        ivRemoveData.ivIcon.setImageResource(R.drawable.ic_delete)
    }
}
</code>```

I am getting an error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
      at hobbajt.com.BubbleQuiz.Options.OptionsFragment.onViewCreated(OptionsFragment.kt:29)
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)
</code>```

It seems that ivIcon is null, even though it's in the included layout. How can I reference this ImageView?

答:
If you give an id to <include/> tag it will override the id of parent included layout.

In your case most probably

```<code>android:id="@+id/ivRemoveData"
</code>```

overrides the id of your imageView. And the id ivIcon could not be found.

You can change your xml like that:

```<code><include
    android:id="@+id/ivIcon"
    layout="@layout/item_menu"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_margin="16dp"
    android:visibility="visible"/>
</code>```

Title: Reference View From Included Layout

Body:
I have a fragment layout with the following include tag:

<include
    android:id="@+id/ivRemoveData"
    layout="@layout/item_menu"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_margin="16dp"
    android:visibility="visible"/>

item_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    android:id="@+id/ivIcon"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_centerInParent="true"

    android:visibility="gone"
    android:background="@drawable/not_passed_circle_level_item"
    android:clipChildren="false"
    android:clipToPadding="false"/>

I need to use method ivIcon.setImageResource().

My fragment class:

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_options.*
import kotlinx.android.synthetic.main.item_menu.view.*

class OptionsFragment : BaseFragment(), OptionsMVP.View
{
    override fun onCreateView(inflater : LayoutInflater, container : ViewGroup?, savedInstanceState : Bundle?) : View?
    {
        val view = inflater.inflate(R.layout.fragment_options, container, false)
        return view
    }

    override fun onViewCreated(view : View?, savedInstanceState : Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)

        ivRemoveData.ivIcon.setImageResource(R.drawable.ic_delete)
    }
}

I am getting an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
      at hobbajt.com.BubbleQuiz.Options.OptionsFragment.onViewCreated(OptionsFragment.kt:29)
      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)

It seems that ivIcon is null, even though it's in the included layout. How can I reference this ImageView?

Body:
If you give an id to <include/> tag it will override the id of parent included layout.

In your case most probably

android:id="@+id/ivRemoveData"

overrides the id of your imageView. And the id ivIcon could not be found.

You can change your xml like that:

<include
    android:id="@+id/ivIcon"
    layout="@layout/item_menu"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_margin="16dp"
    android:visibility="visible"/>


问:
SharePoint JQuery GetUserLoginFromEmail
Could someone provide an an example of how to call the SharePoint WebService, "GetUserLoginFromEmail"?

Thanks!

答:
I highly recommend getting the jQuery Library for SharePoint Web Services (SPServices) from CodePlex: http://spservices.codeplex.com

It will give you a wrapper for that call and every other SharePoint web service there is.

Title: SharePoint JQuery GetUserLoginFromEmail


问:
Running XQuery on the command line
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

```<code>Error: Could not find or load main class net.sf.saxon.Query
</code>```

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

答:
eXist offers XQuery 3.1 support and is packaged with scripts for executing queries and accessing the database from the command line:

```<code>$ bin/client.sh -s

Using locale: en_US.UTF-8
eXist version 3.3.0-SNAPSHOT (00c8bb256), Copyright (C) 2001-2017 The eXist-db Project
eXist-db comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions; for details read the license file.

Connecting to database...
Connected :-)

type help or ? for help.

exist:/db>help
--- general commands ---
ls                   list collection contents
cd [collection|..]   change current collection
put [file pattern]   upload file or directory to the database
putgz [file pattern] upload possibly gzip compressed file or directory to the database
putzip [file pattern] upload the contents of a ZIP archive to the database
edit [resource] open the resource for editing
mkcol collection     create new sub-collection in current collection
rm document          remove document from current collection
rmcol collection     remove collection
set [key=value]      set property. Calling set without
                     argument shows current settings.

--- search commands ---
find xpath-expr      execute the given XPath expression.
show [position]      display query result value at position.

--- user management (may require dba rights) ---
users                list existing users.
adduser username     create a new user.
passwd username      change password for user.
chown user group [resource]
                     change resource ownership. chown without
                     resource changes ownership of the current
                     collection.
chmod [resource] permissions
                     change resource permissions. Format:
                     [user|group|other]=[+|-][read|write|execute].
                     chmod without resource changes permissions for
                     the current collection.
lock resource        put a write lock on the specified resource.
unlock resource      remove a write lock from the specified resource.
svn                  subversion command-line client.
threads              threads debug information.
quit                 quit the program
</code>```

See also Using the Command-line Client and Executing Queries from the eXist documentation.

Title: Running XQuery on the command line

Body:
It sounds like I need some type of XML processor

It looks like theres a program called Saxon which I can use to run XQuery

When I try this websites example I get

Error: Could not find or load main class net.sf.saxon.Query

I don't know how to set up the java package from the saxon package I downloaded.

Id like to know if there is an easier option to be able to run XQuery from the command line other than this java package? All I want to do is process an xml file with commands like "Select  where type="something"".

Body:
eXist offers XQuery 3.1 support and is packaged with scripts for executing queries and accessing the database from the command line:

$ bin/client.sh -s

Using locale: en_US.UTF-8
eXist version 3.3.0-SNAPSHOT (00c8bb256), Copyright (C) 2001-2017 The eXist-db Project
eXist-db comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions; for details read the license file.

Connecting to database...
Connected :-)

type help or ? for help.

exist:/db>help
--- general commands ---
ls                   list collection contents
cd [collection|..]   change current collection
put [file pattern]   upload file or directory to the database
putgz [file pattern] upload possibly gzip compressed file or directory to the database
putzip [file pattern] upload the contents of a ZIP archive to the database
edit [resource] open the resource for editing
mkcol collection     create new sub-collection in current collection
rm document          remove document from current collection
rmcol collection     remove collection
set [key=value]      set property. Calling set without
                     argument shows current settings.

--- search commands ---
find xpath-expr      execute the given XPath expression.
show [position]      display query result value at position.

--- user management (may require dba rights) ---
users                list existing users.
adduser username     create a new user.
passwd username      change password for user.
chown user group [resource]
                     change resource ownership. chown without
                     resource changes ownership of the current
                     collection.
chmod [resource] permissions
                     change resource permissions. Format:
                     [user|group|other]=[+|-][read|write|execute].
                     chmod without resource changes permissions for
                     the current collection.
lock resource        put a write lock on the specified resource.
unlock resource      remove a write lock from the specified resource.
svn                  subversion command-line client.
threads              threads debug information.
quit                 quit the program

See also Using the Command-line Client and Executing Queries from the eXist documentation.