问:
C# Put Static Class Inside Dictionary
I was unclear in an earlier question I ask so I will try to be more explicit.

Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?

Here is how I would like to use it:

```<code>static class MyStatic : IInterface
{
    static void Do(){}
}

static class MyStatic2 : IInterface
{
    static void Do(){}
}

class StaticMap
{
    static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
    {
        {Type.1, MyStatic}
        {Type.2, MyStatic2}
    };
}

// Client Code

class ClientCode
{
    void Start()
    {
        StaticMap.dictionary[Type.1].Do();
    }
}
</code>```

答:
Instead of having the entire class as static, create a Singleton instance.

```<code>public class Foo
{
   public static Foo _Foo;
   public Foo()
   {
      _Foo = this;
   }
}
</code>```

Then you may add it to your list, and also inherit from Interfaces, etc.

Title: C# Put Static Class Inside Dictionary

Body:
I was unclear in an earlier question I ask so I will try to be more explicit.

Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?

Here is how I would like to use it:

static class MyStatic : IInterface
{
    static void Do(){}
}

static class MyStatic2 : IInterface
{
    static void Do(){}
}

class StaticMap
{
    static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
    {
        {Type.1, MyStatic}
        {Type.2, MyStatic2}
    };
}

// Client Code

class ClientCode
{
    void Start()
    {
        StaticMap.dictionary[Type.1].Do();
    }
}

Body:
Instead of having the entire class as static, create a Singleton instance.

public class Foo
{
   public static Foo _Foo;
   public Foo()
   {
      _Foo = this;
   }
}

Then you may add it to your list, and also inherit from Interfaces, etc.


来源: stackexchange

问:
Unable to import python requests library into AWS Lambda function
I have a lambda function that where I cannot the requests library to import.

So far I have tried the following imports:

```<code>import requests
from botocore.vendored import requests
</code>```

Neither of these has worked. Other libraries are importing fine such as import json.

What do I need to do to get the requests library to import to AWS Lambda

答:
requests library doesn't come by default in lambda. Comment out the first line and just go with the second line:</p>

```<code>from botocore.vendored import requests
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a lambda function that where I cannot the requests library to import.

So far I have tried the following imports:

import requests
from botocore.vendored import requests

Neither of these has worked. Other libraries are importing fine such as import json.

What do I need to do to get the requests library to import to AWS Lambda

Body:
requests library doesn't come by default in lambda. Comment out the first line and just go with the second line:

from botocore.vendored import requests


问:
javascript function working only once
I have been trying to use java script to validate a contact form.
The idea is to add a paragraph tag above each textbox and when the submit button is clicked a javascript function should be fired.
if the textbox is empty the "hidden" class will be removed from the class list of the paragraph so it will be visible
The problem is that function is fired only once, the first time i click the button. but if I fill on textbox and click again the function is not fired.
can any body help me about this?
Note: if I use getElementById the function is not fired and the compiler goes to the server side function btnSubmit_Click but when using getElementByName the function is fired only once as described above.

```<code>        <div id="contactForm" runat="server">
            <div class="control-group form-group">
                <div class="controls">
                    <p id="errname" class="hidden">You must insert your <b>name</b></p>
                    <input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" >
                </div>
            </div>
            <div class="control-group form-group">
                <div class="controls">
                    <p id="erremail" class="hidden">You must insert your <b>email</b></p>
                    <input type="email" runat="server" class="form-control" id="txtemail" name="txtemail" placeholder="*Email" >
                </div>
            </div>
            <div class="control-group form-group">
                <div class="controls">
                    <p id="errmessage" class="hidden">You must insert a <b>message</b></p>
                    <textarea runat="server" rows="10" cols="100" class="form-control" id="txtmessage" name="txtmessage" placeholder="*Message" maxlength="999" style="resize:none"></textarea>
                </div>
            </div>
            <asp:Button ID="btnSubmit" runat="server"  OnClientClick="return myfun();" OnClick="btnSubmit_Click"  Text="Send Message" class="btn btn-primary btn-block" />
        </div>
</code>```

and the javascript function is:

```<code>    function myfun() {
        document.getElementById("errname").classList.add('hidden');
        document.getElementById("erremail").classList.add('hidden');
        document.getElementById("errmessage").classList.add('hidden');

        var flag = true;
        if (!document.getElementsById("txtname").value) {
            document.getElementById("errname").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtemail").value) {
            document.getElementById("erremail").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtmessage").value) {
            document.getElementById("errmessage").classList.remove('hidden');
            flag = false;
        }
        if (flag == false) { return false;}

    }
</script>
</code>```

答:
Your JS can never return true. You have:

```<code>if(flag == false) {return false;}
</code>```

But you never tell it to return true. Instead of the line above, why not just:

```<code>return flag;
</code>```

Since you are changing the value from true to false if there's an error, it'll return whatever the value of flag is.

Title: javascript function working only once

Body:
I have been trying to use java script to validate a contact form.
The idea is to add a paragraph tag above each textbox and when the submit button is clicked a javascript function should be fired.
if the textbox is empty the "hidden" class will be removed from the class list of the paragraph so it will be visible
The problem is that function is fired only once, the first time i click the button. but if I fill on textbox and click again the function is not fired.
can any body help me about this?
Note: if I use getElementById the function is not fired and the compiler goes to the server side function btnSubmit_Click but when using getElementByName the function is fired only once as described above.

You must insert your name

                    <input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" >

You must insert your email

                    <input type="email" runat="server" class="form-control" id="txtemail" name="txtemail" placeholder="*Email" >

You must insert a message

                    <textarea runat="server" rows="10" cols="100" class="form-control" id="txtmessage" name="txtmessage" placeholder="*Message" maxlength="999" style="resize:none"></textarea>

            <asp:Button ID="btnSubmit" runat="server"  OnClientClick="return myfun();" OnClick="btnSubmit_Click"  Text="Send Message" class="btn btn-primary btn-block" />

and the javascript function is:

    function myfun() {
        document.getElementById("errname").classList.add('hidden');
        document.getElementById("erremail").classList.add('hidden');
        document.getElementById("errmessage").classList.add('hidden');

        var flag = true;
        if (!document.getElementsById("txtname").value) {
            document.getElementById("errname").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtemail").value) {
            document.getElementById("erremail").classList.remove('hidden');
            flag= false;
        }

        if (!document.getElementsById("txtmessage").value) {
            document.getElementById("errmessage").classList.remove('hidden');
            flag = false;
        }
        if (flag == false) { return false;}

    }
</script>

Body:
Your JS can never return true. You have:

if(flag == false) {return false;}

But you never tell it to return true. Instead of the line above, why not just:

return flag;

Since you are changing the value from true to false if there's an error, it'll return whatever the value of flag is.


问:
how can I verify content based on future date?
I have a content to verify in a webpage which will change after a month or so? how can I write code for this with java in selenium that if today's date is 25th dec then verify some content. I dont want to change todays date from calendar date picker. By default when current date reaches to certain time ( for exmp 25th dec) then it will verify those content or else verify current content.

Thanks in Advance.

答:
From what I understand, you want a specific line of code (or block/function etc), to run on a specific date. Although I do not recommend the following solution (it might add more complexity to your code and make it hard to understand etc), this should work for you:

```<code>DateTime desiredDate = new DateTime(2017, 12, 25, 00, 00, 00)
if(DateTime.Now.isAfter(desiredDate)
{
    //TODO stuff on 25th December 2017
}
</code>```

So every time your code runs, it will check if the moment running is after your desired date. If so, your code inside the if statement will run.

The code above is from JodaTime library, so you will have to include it in your project.

Body:
From what I understand, you want a specific line of code (or block/function etc), to run on a specific date. Although I do not recommend the following solution (it might add more complexity to your code and make it hard to understand etc), this should work for you:

DateTime desiredDate = new DateTime(2017, 12, 25, 00, 00, 00)
if(DateTime.Now.isAfter(desiredDate)
{
    //TODO stuff on 25th December 2017
}

So every time your code runs, it will check if the moment running is after your desired date. If so, your code inside the if statement will run.

The code above is from JodaTime library, so you will have to include it in your project.


问:
Preserve data file prefix when using dist_pkgdata_DATA?
Our test data is organized with two folders. We have TestData/ and TestVectors/, depending on the form of the data:

```<code>- TestData
  |
  + a.dat
  + b.dat
  + ...

- TestVector
  |
  + x.vec
  + y.vec
  + ...
</code>```

Our Makefile.am has:

```<code>dist_pkgdata_DATA = \
   $(testdata_FILES) \
   $(testvector_FILES)

testdata_FILES = \
   TestData/a.dat TestData/b.dat \
   ...

testvector_FILES = \
   TestVectors/x.vec TestVectors/y.vec \
   ...
</code>```

Automake installs them in @datadir@/@PACKAGE@/, but we lose the TestData and TestVectors prefix upon installation. That is, once installed, all the files are lumped together:

```<code>- @datadir@/@PACKAGE@/
  |
  + a.dat
  + b.dat
  + ...
  + x.vec
  + y.vec
  + ...
</code>```

There's a very similar question at Install arbitrary data files in arbitrary locations with Automake?, but I am not quite following what needs to be done to ensure make install works as expected.

My question is, how do we preserve the prefix of TestData or TestVectors during install?

答:
This is what the nobase prefix was invented for.  The name stands for "don't call basename" and would be used like:

```<code>nobase_dist_pkgdata_DATA = \
    $(testdata_FILES) \
    $(testvector_FILES)
</code>```

This should result in the listed files keeping their directory names in the install tree.

Body:
Our test data is organized with two folders. We have TestData/ and TestVectors/, depending on the form of the data:

- TestData
  |
  + a.dat
  + b.dat
  + ...

- TestVector
  |
  + x.vec
  + y.vec
  + ...

Our Makefile.am has:

dist_pkgdata_DATA = \
   $(testdata_FILES) \
   $(testvector_FILES)

testdata_FILES = \
   TestData/a.dat TestData/b.dat \
   ...

testvector_FILES = \
   TestVectors/x.vec TestVectors/y.vec \
   ...

Automake installs them in @datadir@/@PACKAGE@/, but we lose the TestData and TestVectors prefix upon installation. That is, once installed, all the files are lumped together:

- @datadir@/@PACKAGE@/
  |
  + a.dat
  + b.dat
  + ...
  + x.vec
  + y.vec
  + ...

There's a very similar question at Install arbitrary data files in arbitrary locations with Automake?, but I am not quite following what needs to be done to ensure make install works as expected.

My question is, how do we preserve the prefix of TestData or TestVectors during install?

Body:
This is what the nobase prefix was invented for.  The name stands for "don't call basename" and would be used like:

nobase_dist_pkgdata_DATA = \
    $(testdata_FILES) \
    $(testvector_FILES)

This should result in the listed files keeping their directory names in the install tree.


问:
To show only a part of the v-model data based on a condition
Here is my fiddle : DEMO

```<code>methods: {
  create() {
    console.log(JSON.stringify(this.modules, null, 4))
  }
}
</code>```

I have modules, their actions and its permissions.

```<code><div v-for="(module, moduleIndex) in modules"><b>{{ module.moduleName }}</b>
    <div v-for="(action, actionIndex) in module.actions">{{ action.actionName }}
      <div v-for="(permission, permIndex) in action.permissions">
        <input type="checkbox" v-model='modules[moduleIndex].actions[actionIndex].permissions[permIndex].value'> {{ permission.permissionName }} - {{modules[moduleIndex].actions[actionIndex].permissions[permIndex].value}}
      </div>
    </div>
</code>```

On choice of the checkboxes, the associated v-model gets updated. Is there a way I show only permissions for which the value in "true" in v-model or the displayed content.

Any help would be much appreciated. Thank you!

答:
Your updated_modules computed just needs to filter out the false permissions, then filter out actions with no permissions and objects with no actions:

```<code>updated_modules: function() {
  var updated = JSON.parse(JSON.stringify(this.modules));

  for (const obj of updated) {
    for (const action of obj.actions) {
      action.permissions = action.permissions.filter((p) => p.value);
    }
    obj.actions = obj.actions.filter((a) => a.permissions.length);
  }
  updated = updated.filter((o) => o.actions.length);

  return updated;
}
</code>```

then remember to print it rather than the unmodified modules

```<code><p> Result now </p>
```{{ JSON.stringify(this.updated_modules,null,4)}}```
</code>```

and you have this fiddle.

Body:
Here is my fiddle : DEMO

methods: {
  create() {
    console.log(JSON.stringify(this.modules, null, 4))
  }
}

I have modules, their actions and its permissions.

{{ module.moduleName }}

{{ action.actionName }}

        <input type="checkbox" v-model='modules[moduleIndex].actions[actionIndex].permissions[permIndex].value'> {{ permission.permissionName }} - {{modules[moduleIndex].actions[actionIndex].permissions[permIndex].value}}

On choice of the checkboxes, the associated v-model gets updated. Is there a way I show only permissions for which the value in "true" in v-model or the displayed content.

Any help would be much appreciated. Thank you!

Body:
Your updated_modules computed just needs to filter out the false permissions, then filter out actions with no permissions and objects with no actions:

updated_modules: function() {
  var updated = JSON.parse(JSON.stringify(this.modules));

  for (const obj of updated) {
    for (const action of obj.actions) {
      action.permissions = action.permissions.filter((p) => p.value);
    }
    obj.actions = obj.actions.filter((a) => a.permissions.length);
  }
  updated = updated.filter((o) => o.actions.length);

  return updated;
}

then remember to print it rather than the unmodified modules

<p> Result now </p>
<pre>{{ JSON.stringify(this.updated_modules,null,4)}}</pre>

and you have this fiddle.


问:
Is it possible to drag and drop external data into a jstree?
I'm working on a project which requires a hierarchical navigation menu to be built. jstree looks good for this.

The tree will be saved to a database - I am planning on using CakePHP's Tree Behaviour (the project has to work in Cake 2.x rather than 3.x due to the existing codebase).

One of the things I need to do is have the ability to add "Tags" to my tree from an external data source.

The way I have things configured is as follows:

The data to populate my jstree is coming from a database table (called navigations due to Cake's naming conventions). It uses the table structure given on the Tree Behaviour link above.

I'm loading this data into a jstree with the ajax method:

```<code>$.ajax({
    type : "GET",
    url : "/ajax_get_tree",
    dataType : "json",

    success : function(json) {
        createJSTrees(json);
    },

    error : function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});

function createJSTrees(jsonData) {
    $("#tree").jstree({
        'core': {
            "check_callback" : true,
            'data' : jsonData
        },
        "plugins" : ["dnd"]
    }).on('loaded.jstree', function() {
        $("#tree").jstree('open_all');
    });
}
</code>```

What I want to do is drag and drop "Tags" (by which I mean list items) from a separate div, #tagList into elements on the tree. The tag data is formatted as follows:

```<code><div id="tagList">
    <li data-tag="1">United Kingdom</li>
    <li data-tag="2">France</li>
    <li data-tag="3">Germany</li>
</div>
</code>```

I know it's possible to use things like jqueryui's draggable behaviour to move them from one div to another (from #tagList into #tree).

However, I don't know how I can "drop" the tag such that jstree lists it under the appropriate node.

For example I've tried this - which is just using jqueryui and has nothing to do with jstree other than referencing the div it's running on:

```<code>$('#tagList li').draggable({
        cursor: 'move',
        helper: 'clone',
        connectToSortable: "#tree",
    });
</code>```

My question really is whether what I'm trying to do is even possible? I've spent a long time looking into this and feel I'm getting nowhere with it.

Are there any other things out there that can do this type of task? I've had a look but was unable to find anything. Essentially the requirements are the ability to create a tree (name, edit, delete, drag/drop) but then to also bring Tags (
 elements from the #tagList) into it, and save it.

答:
Based on the articles I posted in the comments, you need to create an object that jsTree will be familiar with.

Reference:

How to drag a node from a div and drop it on to a JStree? (jstree version: 3.0.4)

Dragging a foreign object into JSTree problem

Working Example:

https://jsfiddle.net/Twisty/dLv7xk3t/

HTML

```<code><div class="ui-widget">
  <div class="ui-widget-header">
    Tags
  </div>
  <div id="tagList">
    <ul>
      <li data-tag="1" id="uk-1">United Kingdom</li>
      <li data-tag="2" id="france-1">France</li>
      <li data-tag="3" id="germany-1">Germany</li>
    </ul>
  </div>
</div>
<div class="ui-widget">
  <div class="ui-widget-header">
    Tree
  </div>
  <div id="tree">
  </div>
</div>
</code>```

JavaScript

```<code>var exData = [{
  id: "loc1",
  parent: "#",
  text: "Location 1"
}, {
  id: "loc2",
  parent: "#",
  text: "Location 2"
}, {
  id: "italy-1",
  parent: "loc2",
  text: "Italy",
  icon: "fa fa-flag"
}, {
  id: "poland-1",
  parent: "loc2",
  text: "Poland",
  icon: "fa fa-flag"
}];

function makeTreeItem(el) {
  return $("<a>", {
    id: $(el).attr("id") + "_anchor",
    class: "jstree-anchor",
    href: "#"
  });
}

$(function() {
  $('#tree').jstree({
    core: {
      check_callback: true,
      data: exData
    },
    types: {
      root: {
        icon: "fa fa-globe-o"
      }
    },
    plugins: ["dnd", "types"]
  });
  $('#tagList li').draggable({
    cursor: 'move',
    helper: 'clone',
    start: function(e, ui) {
      var item = $("<div>", {
        id: "jstree-dnd",
        class: "jstree-default"
      });
      $("<i>", {
        class: "jstree-icon jstree-er"
      }).appendTo(item);
      item.append($(this).text());
      var idRoot = $(this).attr("id").slice(0, -2);
      var newId = idRoot + "-" + ($("#tree [id|='" + idRoot + "'][class*='jstree-node']").length + 1);
      return $.vakata.dnd.start(e, {
        jstree: true,
        obj: makeTreeItem(this),
        nodes: [{
          id: newId,
          text: $(this).text(),
          icon: "fa fa-flag-o"
        }]
      }, item);
    }
  });
});
</code>```

The function makeTreeItem() is simply a wrapping function to make the item dragged in more like what jsTree already has.

The first thing to do is update the core preference to enable the creation of new nodes etc:

check_callback: true

The next key here is in the draggable start callback. This is where we create a Drag n Drop element that jsTree is already ready to handle, making use of the dnd plugin for jsTree.

```<code>  start: function(e, ui) {
      var item = $("<div>", {
        id: "jstree-dnd",
        class: "jstree-default"
      });
      $("<i>", {
        class: "jstree-icon jstree-er"
      }).appendTo(item);
      item.append($(this).text());
      var idRoot = $(this).attr("id").slice(0, -2);
      var newId = idRoot + "-" + ($("#tree [id|='" + idRoot + "'][class*='jstree-node']").length + 1);
      return $.vakata.dnd.start(e, {
        jstree: true,
        obj: makeTreeItem(this),
        nodes: [{
          id: newId,
          text: $(this).text(),
          icon: "fa fa-flag-o"
        }]
      }, item);
    }
</code>```

Basically, we have a div with an icon and the text of the item being dragged. This will represent our helper that will be seen while dragging. We then make and return an Event Object with specific attributes that jsTree will understand and our helper item.

Body:
I'm working on a project which requires a hierarchical navigation menu to be built. jstree looks good for this.

The tree will be saved to a database - I am planning on using CakePHP's Tree Behaviour (the project has to work in Cake 2.x rather than 3.x due to the existing codebase).

One of the things I need to do is have the ability to add "Tags" to my tree from an external data source.

The way I have things configured is as follows:

The data to populate my jstree is coming from a database table (called navigations due to Cake's naming conventions). It uses the table structure given on the Tree Behaviour link above.

I'm loading this data into a jstree with the ajax method:

$.ajax({
    type : "GET",
    url : "/ajax_get_tree",
    dataType : "json",

    success : function(json) {
        createJSTrees(json);
    },

    error : function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
    }
});

function createJSTrees(jsonData) {
    $("#tree").jstree({
        'core': {
            "check_callback" : true,
            'data' : jsonData
        },
        "plugins" : ["dnd"]
    }).on('loaded.jstree', function() {
        $("#tree").jstree('open_all');
    });
}

What I want to do is drag and drop "Tags" (by which I mean list items) from a separate div, #tagList into elements on the tree. The tag data is formatted as follows:

United Kingdom

France

Germany

I know it's possible to use things like jqueryui's draggable behaviour to move them from one div to another (from #tagList into #tree).

However, I don't know how I can "drop" the tag such that jstree lists it under the appropriate node.

For example I've tried this - which is just using jqueryui and has nothing to do with jstree other than referencing the div it's running on:

$('#tagList li').draggable({
        cursor: 'move',
        helper: 'clone',
        connectToSortable: "#tree",
    });

My question really is whether what I'm trying to do is even possible? I've spent a long time looking into this and feel I'm getting nowhere with it.

Are there any other things out there that can do this type of task? I've had a look but was unable to find anything. Essentially the requirements are the ability to create a tree (name, edit, delete, drag/drop) but then to also bring Tags (
 elements from the #tagList) into it, and save it.

Body:
Based on the articles I posted in the comments, you need to create an object that jsTree will be familiar with.

Reference:

How to drag a node from a div and drop it on to a JStree? (jstree version: 3.0.4)

Dragging a foreign object into JSTree problem

Working Example:

https://jsfiddle.net/Twisty/dLv7xk3t/

HTML

<div class="ui-widget">
  <div class="ui-widget-header">
    Tags
  </div>
  <div id="tagList">
    <ul>
      <li data-tag="1" id="uk-1">United Kingdom</li>
      <li data-tag="2" id="france-1">France</li>
      <li data-tag="3" id="germany-1">Germany</li>
    </ul>
  </div>
</div>
<div class="ui-widget">
  <div class="ui-widget-header">
    Tree
  </div>
  <div id="tree">
  </div>
</div>

JavaScript

var exData = [{
  id: "loc1",
  parent: "#",
  text: "Location 1"
}, {
  id: "loc2",
  parent: "#",
  text: "Location 2"
}, {
  id: "italy-1",
  parent: "loc2",
  text: "Italy",
  icon: "fa fa-flag"
}, {
  id: "poland-1",
  parent: "loc2",
  text: "Poland",
  icon: "fa fa-flag"
}];

function makeTreeItem(el) {
  return $("<a>", {
    id: $(el).attr("id") + "_anchor",
    class: "jstree-anchor",
    href: "#"
  });
}

$(function() {
  $('#tree').jstree({
    core: {
      check_callback: true,
      data: exData
    },
    types: {
      root: {
        icon: "fa fa-globe-o"
      }
    },
    plugins: ["dnd", "types"]
  });
  $('#tagList li').draggable({
    cursor: 'move',
    helper: 'clone',
    start: function(e, ui) {
      var item = $("<div>", {
        id: "jstree-dnd",
        class: "jstree-default"
      });
      $("<i>", {
        class: "jstree-icon jstree-er"
      }).appendTo(item);
      item.append($(this).text());
      var idRoot = $(this).attr("id").slice(0, -2);
      var newId = idRoot + "-" + ($("#tree [id|='" + idRoot + "'][class*='jstree-node']").length + 1);
      return $.vakata.dnd.start(e, {
        jstree: true,
        obj: makeTreeItem(this),
        nodes: [{
          id: newId,
          text: $(this).text(),
          icon: "fa fa-flag-o"
        }]
      }, item);
    }
  });
});

The function makeTreeItem() is simply a wrapping function to make the item dragged in more like what jsTree already has.

The first thing to do is update the core preference to enable the creation of new nodes etc:

check_callback: true

The next key here is in the draggable start callback. This is where we create a Drag n Drop element that jsTree is already ready to handle, making use of the dnd plugin for jsTree.

  start: function(e, ui) {
      var item = $("<div>", {
        id: "jstree-dnd",
        class: "jstree-default"
      });
      $("<i>", {
        class: "jstree-icon jstree-er"
      }).appendTo(item);
      item.append($(this).text());
      var idRoot = $(this).attr("id").slice(0, -2);
      var newId = idRoot + "-" + ($("#tree [id|='" + idRoot + "'][class*='jstree-node']").length + 1);
      return $.vakata.dnd.start(e, {
        jstree: true,
        obj: makeTreeItem(this),
        nodes: [{
          id: newId,
          text: $(this).text(),
          icon: "fa fa-flag-o"
        }]
      }, item);
    }

Basically, we have a div with an icon and the text of the item being dragged. This will represent our helper that will be seen while dragging. We then make and return an Event Object with specific attributes that jsTree will understand and our helper item.


问:
Access - how to derive a field upon entry of a record
I have an Access database for a media rental company which includes the following tables, among others;

LOAN:
customer_id (pk),
loan_datetimeLeant (pk),
loan_dateReturned (pk)

LOAN_ITEMS:
customer_id (pk),
loan_datetimeLeant (pk),
item_id (pk),
loanItem_cost

ITEM:
item_id (pk),
product_id,
item_availability

PRODUCT:
product_id (pk),
product_name,
product_type

MEDIA_COST:
product_type (pk),
product_cost

So basically the 'product type' (DVD, VHS etc) determines the cost. The 'product id' determines what movie, platform etc each item is.

My question is:
When creating a form for the Loan_Items table, how can I populate the loanItem_cost field (so it is stored) whenever a new Loan_Item record is added? I need to store it as the cost of the item (product_cost) may change over time and I'd like to record what the customer paid at the time the loan was made.

Thanks in advance

答:
Set the Default Value property of the loanItem_cost form control to reference the product_cost from another form or from the product table.

If you have a form with a button that opens another form, you can reference a control on the parent form in the Default Value property: Forms![ParentFormName]![product_cost].

Similarly, you can use a DLookup function:

```<code>DLookup("product_cost", "ProductTable", "product_id = " & Forms![ParentFormName]![product_id])
</code>```

The source of the product_id value in the "where" parameter of the DLookup function can come from several places, but would likely be found on another form.

ContentLicense: CC BY-SA 2.5

Body:
Set the Default Value property of the loanItem_cost form control to reference the product_cost from another form or from the product table.

If you have a form with a button that opens another form, you can reference a control on the parent form in the Default Value property: Forms![ParentFormName]![product_cost].

Similarly, you can use a DLookup function:

DLookup("product_cost", "ProductTable", "product_id = " & Forms![ParentFormName]![product_id])

The source of the product_id value in the "where" parameter of the DLookup function can come from several places, but would likely be found on another form.


问:
Mongodb load collection by ID
Probably something very simple here.
I have 2 mongoDb collections, one (users) with an objectId and the other (listings) which has the userId.

I want to get the documents in the listing collection by searching the objectId (currentUser._id).

How would i do this?

Component for page i want to display the listings on:

```<code>export class ManageComponent implements OnInit {
    listing : Listing;
    listings: Listing[] = [];
currentUser: User;

constructor(
    private listingService: ListingService,
    private userService: UserService) {
        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
     }

ngOnInit() {
    this.loadAllListings();
}

private loadAllListings() {
    this.listingService.getAll().subscribe(listings => { this.listings = listings; });
}

private loadById(userId: string) {
    this.listingService.getById(userId).subscribe(listings => { this.listings = listings});
    }
}
</code>```

I have a listing service that is used to for the CRUD operations (some omitted)

```<code>import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { Listing } from '../_models/index';

@Injectable()
export class ListingService {

constructor(private http: Http) { }

getAll() {
    return this.http.get('/listings').map((response: Response) => response.json());
}

getById(_id: string) {
    return this.http.get('/listings/' + _id).map((response: Response) => response.json());
}

getByUserId(userId: string) {
    return this.http.get('/listings/' + userId).map((response: Response) => response.json());
}

create(listing: Listing) {
    return this.http.post('/listings/add', listing);
}
</code>```

Server side listing controller which uses the server side service (see below):

```<code>function getRelevant(req, res) {
listingService.getByUserId(req.listing.sub)
    .then(function (listing) {
        if (listing) {
            res.send(listing);
        } else {
            res.sendStatus(404);
        }
    })
    .catch(function (err) {
        res.status(400).send(err);
    });
}
</code>```

Server side listing service:

```<code>function getByUserId(userId) {
var deferred = Q.defer();

db.listings.findById(userId, function (err, listing) {
    if (err) deferred.reject(err.name + ': ' + err.message);

    if (listing) {
        // return listing
        deferred.resolve(listing);
    } else {
        // listing not found
        deferred.resolve();
    }
});

return deferred.promise;
}
</code>```

答:
db.listings.aggregate([ $lookup:{
          from: "users",
          localField: "currentUser._id",
          foreignField: "_id",
          as: "result"
        }
   }
]).findOne({
user_id: id you want to search
})</p>

Title: Mongodb load collection by ID

Body:
Probably something very simple here.
I have 2 mongoDb collections, one (users) with an objectId and the other (listings) which has the userId.

I want to get the documents in the listing collection by searching the objectId (currentUser._id).

How would i do this?

Component for page i want to display the listings on:

export class ManageComponent implements OnInit {
    listing : Listing;
    listings: Listing[] = [];
currentUser: User;

constructor(
    private listingService: ListingService,
    private userService: UserService) {
        this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
     }

ngOnInit() {
    this.loadAllListings();
}

private loadAllListings() {
    this.listingService.getAll().subscribe(listings => { this.listings = listings; });
}

private loadById(userId: string) {
    this.listingService.getById(userId).subscribe(listings => { this.listings = listings});
    }
}

I have a listing service that is used to for the CRUD operations (some omitted)

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { Listing } from '../_models/index';

@Injectable()
export class ListingService {

constructor(private http: Http) { }

getAll() {
    return this.http.get('/listings').map((response: Response) => response.json());
}

getById(_id: string) {
    return this.http.get('/listings/' + _id).map((response: Response) => response.json());
}

getByUserId(userId: string) {
    return this.http.get('/listings/' + userId).map((response: Response) => response.json());
}

create(listing: Listing) {
    return this.http.post('/listings/add', listing);
}

Server side listing controller which uses the server side service (see below):

function getRelevant(req, res) {
listingService.getByUserId(req.listing.sub)
    .then(function (listing) {
        if (listing) {
            res.send(listing);
        } else {
            res.sendStatus(404);
        }
    })
    .catch(function (err) {
        res.status(400).send(err);
    });
}

Server side listing service:

function getByUserId(userId) {
var deferred = Q.defer();

db.listings.findById(userId, function (err, listing) {
    if (err) deferred.reject(err.name + ': ' + err.message);

    if (listing) {
        // return listing
        deferred.resolve(listing);
    } else {
        // listing not found
        deferred.resolve();
    }
});

return deferred.promise;
}


问:
How to have colors in the output of (emacs) shell-command?
When executing the command shell-command, the output shown in the associated buffer is not colorized.

This is particularly annoying when calling a testing framework (outputting yellow/green/red...) from within emacs.

How can I configure, or extend, emacs in order to have shell-command allowing colorized output in the shell and preserving the colors while representing that output?

Thanks!

ps. I'm using the Bash shell, on a UN*X system.

答:
You can implement your own shell-execute, something like</p>

```<code>(defun my-shell-execute(cmd)
   (interactive "sShell command: ")
   (shell (get-buffer-create "my-shell-buf"))
   (process-send-string (get-buffer-process "my-shell-buf") (concat cmd "\n")))
</code>```

Body:
You can implement your own shell-execute, something like

(defun my-shell-execute(cmd)
   (interactive "sShell command: ")
   (shell (get-buffer-create "my-shell-buf"))
   (process-send-string (get-buffer-process "my-shell-buf") (concat cmd "\n")))


问:
How to export a report expression in Cognos 10 as a data item and return the results when choosing Excel 2007 data
I have quick question about Cognos 10. I am trying to export a data item which I created that has a report expression as the value. The value is for example : IF(ParamValue('p_RPO') is NULL) THEN (' ') ELSE (ParamDisplayValue('p_RPO')). When I export the report out as a HTML it works as intended. However when I select excel 2007 data it seems to remove the data item column that has then report expression. Is there a way to fix this?</p>

答:
Instead of using a report expression add a data item to the query with this expression:

```<code>if (?p_RPO? is null) then ('whatever') else (?p_RPO?)
</code>```

Add this data item to the list.

To make the p_RPO parameter optional you have to use the prompt macro specifying a default value. In this case:

```<code>if(#prompt('p_RPO', 'string', 'default')# = 'default') then ('whatever') else (#prompt('p_RPO', 'string', 'default')#)
</code>```

Body:
Instead of using a report expression add a data item to the query with this expression:

if (?p_RPO? is null) then ('whatever') else (?p_RPO?)

Add this data item to the list.

To make the p_RPO parameter optional you have to use the prompt macro specifying a default value. In this case:

if(#prompt('p_RPO', 'string', 'default')# = 'default') then ('whatever') else (#prompt('p_RPO', 'string', 'default')#)


问:
Button flickers, hides in Safari
I have built a slider using SCSS, JavaScript, and HTML. The demo is here: https://jsfiddle.net/rr7g6a1b/

```<code>let mySlider = {
  initializeSlider: function (options) {
    let slider = options.container;
    let slides = slider.querySelectorAll('.slide');
    let initialSlide = slider.querySelector('.slide[data-index="0"]');
    let initialButton = slider.querySelector('.pagination-button[data-index="0"]');
    initialSlide.classList.add('active');
    initialButton.classList.add('active');
    let sliderControlButton = slider.querySelector('.control-slider-button');
    if (options.autoplay === true) {
      sliderControlButton.classList.add('stop');
    } else {
      sliderControlButton.classList.add('play');
    }
    sliderControlButton.addEventListener('click', function () {
      mySlider.switchAutoplay(options);
    });
    for (let i = 0; i < slides.length; i++) {
      let button = slider.querySelector('.pagination-button[data-index="' + i + '"]');
      button.addEventListener('click', function () {
        mySlider.goToSlide(options, i);
        mySlider.stopAutoplay(options);
      });
    }
    if (options.autoplay === true) {
      options.autoplayer = window.setTimeout(function () {
        mySlider.goToNext(options);
      }, options.duration);
    }
  },
  switchAutoplay: function (options) {
    let sliderControlButton = options.container.querySelector('.control-slider-button');
    if (options.autoplay === true) {
      mySlider.stopAutoplay(options);
        sliderControlButton.classList.add('play');
        sliderControlButton.classList.remove('stop');
    } else {
      mySlider.startAutoplay(options);
        sliderControlButton.classList.remove('play');
        sliderControlButton.classList.add('stop');
    }
  },
  goToSlide: function (options, target) {
    let slider = options.container;
    let targetSlide = slider.querySelector('.slide[data-index="' + target + '"]');
    if (!targetSlide.classList.contains('active')) {
      let activeSlide = slider.querySelector('.slide.active');
      let activeButton = slider.querySelector('.pagination-button.active');
      let activeNum = activeSlide.dataset.index;
      let targetNum = parseInt(target);
      let go = false;
      let direction = 'left';
      if (targetNum < activeNum) {
        direction = 'right';
      }

      let targetButton = slider.querySelector('.pagination-button[data-index="' + target + '"]');
      activeButton.classList.remove('active');
      targetButton.classList.add('active');

      let moveTarget = function (direction) {
        let correct = direction;
        let opposite = (direction === 'left') ? 'right' : 'left';
        correct = 'hide-' + direction;
        opposite = 'hide-' + opposite;
        targetSlide.classList.add('transitioning');
        window.setTimeout(function () {
          targetSlide.classList.remove(correct);
          targetSlide.classList.add(opposite);
        }, 100);
        window.setTimeout(function () {
          targetSlide.classList.remove('transitioning');
        }, 150);
      };
      let moveActive = function (direction) {
        activeSlide.classList.remove('active');
        direction = 'hide-' + direction;
        activeSlide.classList.add(direction);
      };

      moveTarget(direction);
      window.setTimeout(function () {
        moveActive(direction);
        targetSlide.classList.remove('hide-left');
        targetSlide.classList.remove('hide-right');
        targetSlide.classList.add('active');
      }, 200);
    }
  },
  goToNext: function (options) {
    if (options.autoplay === true) {
      let slider = options.container;
      let currentSlide = slider.querySelector('.slide.active');
      let currentSlideIndex = currentSlide.dataset.index;
      let lastSlide = slider.querySelectorAll('.slide').length - 1;
      let nextSlide = 0;
      if (currentSlideIndex != lastSlide) {
        nextSlide = parseInt(currentSlideIndex) + 1;
      }
      mySlider.goToSlide(options, nextSlide);
      options.autoplayer = window.setTimeout(function () {
        mySlider.goToNext(options);
      }, options.duration);
    }
  },
  stopAutoplay: function (options) {
    options.autoplay = false;
    window.clearTimeout(options.autoplayer);
  },
  startAutoplay: function (options) {
    options.autoplay = true;
    options.autoplayer = window.setTimeout(function () {
      mySlider.goToNext(options);
    }, options.duration);
  }
};

let mainSlider = document.getElementById('main-slider');
let mainSliderOptions = {
  container: mainSlider,
  autoplay: false,
  duration: 6000
}
mySlider.initializeSlider(mainSliderOptions);
</code>```

The pagination buttons work fine in Chrome but in Safari, they occasionally flicker or get cut off after you click on the buttons. Is there an error/workaround for this kind of flickering? I'm not sure what could be causing this issue.

答:
Css workaround for -webkit- browsers. Try adding the following to the flickering button's css.</p>

```<code>-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;
-webkit-transform: translate3d(0,0,0);
</code>```

Title: Button flickers, hides in Safari

Body:
I have built a slider using SCSS, JavaScript, and HTML. The demo is here: https://jsfiddle.net/rr7g6a1b/

let mySlider = {
  initializeSlider: function (options) {
    let slider = options.container;
    let slides = slider.querySelectorAll('.slide');
    let initialSlide = slider.querySelector('.slide[data-index="0"]');
    let initialButton = slider.querySelector('.pagination-button[data-index="0"]');
    initialSlide.classList.add('active');
    initialButton.classList.add('active');
    let sliderControlButton = slider.querySelector('.control-slider-button');
    if (options.autoplay === true) {
      sliderControlButton.classList.add('stop');
    } else {
      sliderControlButton.classList.add('play');
    }
    sliderControlButton.addEventListener('click', function () {
      mySlider.switchAutoplay(options);
    });
    for (let i = 0; i < slides.length; i++) {
      let button = slider.querySelector('.pagination-button[data-index="' + i + '"]');
      button.addEventListener('click', function () {
        mySlider.goToSlide(options, i);
        mySlider.stopAutoplay(options);
      });
    }
    if (options.autoplay === true) {
      options.autoplayer = window.setTimeout(function () {
        mySlider.goToNext(options);
      }, options.duration);
    }
  },
  switchAutoplay: function (options) {
    let sliderControlButton = options.container.querySelector('.control-slider-button');
    if (options.autoplay === true) {
      mySlider.stopAutoplay(options);
        sliderControlButton.classList.add('play');
        sliderControlButton.classList.remove('stop');
    } else {
      mySlider.startAutoplay(options);
        sliderControlButton.classList.remove('play');
        sliderControlButton.classList.add('stop');
    }
  },
  goToSlide: function (options, target) {
    let slider = options.container;
    let targetSlide = slider.querySelector('.slide[data-index="' + target + '"]');
    if (!targetSlide.classList.contains('active')) {
      let activeSlide = slider.querySelector('.slide.active');
      let activeButton = slider.querySelector('.pagination-button.active');
      let activeNum = activeSlide.dataset.index;
      let targetNum = parseInt(target);
      let go = false;
      let direction = 'left';
      if (targetNum < activeNum) {
        direction = 'right';
      }

      let targetButton = slider.querySelector('.pagination-button[data-index="' + target + '"]');
      activeButton.classList.remove('active');
      targetButton.classList.add('active');

      let moveTarget = function (direction) {
        let correct = direction;
        let opposite = (direction === 'left') ? 'right' : 'left';
        correct = 'hide-' + direction;
        opposite = 'hide-' + opposite;
        targetSlide.classList.add('transitioning');
        window.setTimeout(function () {
          targetSlide.classList.remove(correct);
          targetSlide.classList.add(opposite);
        }, 100);
        window.setTimeout(function () {
          targetSlide.classList.remove('transitioning');
        }, 150);
      };
      let moveActive = function (direction) {
        activeSlide.classList.remove('active');
        direction = 'hide-' + direction;
        activeSlide.classList.add(direction);
      };

      moveTarget(direction);
      window.setTimeout(function () {
        moveActive(direction);
        targetSlide.classList.remove('hide-left');
        targetSlide.classList.remove('hide-right');
        targetSlide.classList.add('active');
      }, 200);
    }
  },
  goToNext: function (options) {
    if (options.autoplay === true) {
      let slider = options.container;
      let currentSlide = slider.querySelector('.slide.active');
      let currentSlideIndex = currentSlide.dataset.index;
      let lastSlide = slider.querySelectorAll('.slide').length - 1;
      let nextSlide = 0;
      if (currentSlideIndex != lastSlide) {
        nextSlide = parseInt(currentSlideIndex) + 1;
      }
      mySlider.goToSlide(options, nextSlide);
      options.autoplayer = window.setTimeout(function () {
        mySlider.goToNext(options);
      }, options.duration);
    }
  },
  stopAutoplay: function (options) {
    options.autoplay = false;
    window.clearTimeout(options.autoplayer);
  },
  startAutoplay: function (options) {
    options.autoplay = true;
    options.autoplayer = window.setTimeout(function () {
      mySlider.goToNext(options);
    }, options.duration);
  }
};

let mainSlider = document.getElementById('main-slider');
let mainSliderOptions = {
  container: mainSlider,
  autoplay: false,
  duration: 6000
}
mySlider.initializeSlider(mainSliderOptions);

The pagination buttons work fine in Chrome but in Safari, they occasionally flicker or get cut off after you click on the buttons. Is there an error/workaround for this kind of flickering? I'm not sure what could be causing this issue.

Body:
Css workaround for -webkit- browsers. Try adding the following to the flickering button's css.

-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;
-webkit-transform: translate3d(0,0,0);


问:
If jQuery form is valid show hidden div
I've been messing with some form validation with two identical forms. So far I have the default HTML validation on the form, but for some reason when I submit the form, it reload the form it doesn't show my message that it's been successful.

Here's what I have for the form:

HTML

```<code><div class="place-form">
   <div class="success-msg" style="display:none;">
    <p>Thanks for your submission! We will contact you shortly.</p>
  </div>
  <div class="form-wrap">
    <form id="place-form-item">
    <div class="form-row">
      <input id="fname" type="text" name="fname" placeholder="Your First Name" required />
    </div>
    <div class="form-row">
      <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />
    </div>
    <div class="form-row">
      <input id="form-email" type="email" name="email" placeholder="Your Email" required />
    </div>
    <div class="btn-row">
      <button class="submit-btn">submit</button>
    </div>
      </form>
  </div>
</div>
</code>```

JS:

```<code>$(".submit-btn").click(function(e){
   var $this = $(this);
   if($this.find("#place-form-item").valid()) {
       $this.parents(".form-wrap").hide();
       $this.parents().next(".success-msg").show()
     e.preventDefault();
   }
});
</code>```

Not sure how to get it so that upon click, the form passed validation and then hides the one form and shows the success message. Unless I'm targeting something incorrectly.

答:
The problem is that .next() only targets the sibling that immediately follows the target. Given your structure, .success-msg precedes .form-wrap. As such, .next() cannot target it.

To resolve this, instead of $this.parents().next(".success-msg").show(), you can target the parent element .place-form and then make use of .find() to find the relevant .success-msg with $this.parents(".place-form").find(".success-msg").show().

You'll also want to move your e.preventDefault() to outside of your conditional.

This can be seen in the following example:

$(".submit-btn").click(function(e) {
  e.preventDefault();
  var $this = $(this);
  if ($('#place-form-item').valid()) {
    $this.parents(".form-wrap").hide();
    $this.parents(".place-form").find(".success-msg").show();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

<div class="place-form">
  <div class="success-msg" style="display:none;">
    <p>Thanks for your submission! We will contact you shortly.</p>
  </div>
  <div class="form-wrap">
    <form id="place-form-item">
      <div class="form-row">
        <input id="fname" type="text" name="fname" placeholder="Your First Name" required />
      </div>
      <div class="form-row">
        <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />
      </div>
      <div class="form-row">
        <input id="form-email" type="email" name="email" placeholder="Your Email" required />
      </div>
      <div class="btn-row">
        <button class="submit-btn">submit</button>
      </div>
    </form>
  </div>
</div></code>```

Hope this helps! :)

Title: If jQuery form is valid show hidden div

Body:
I've been messing with some form validation with two identical forms. So far I have the default HTML validation on the form, but for some reason when I submit the form, it reload the form it doesn't show my message that it's been successful.

Here's what I have for the form:

HTML

Thanks for your submission! We will contact you shortly.

    <form id="place-form-item">

      <input id="fname" type="text" name="fname" placeholder="Your First Name" required />

      <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />

      <input id="form-email" type="email" name="email" placeholder="Your Email" required />

      <button class="submit-btn">submit</button>

      </form>

JS:

$(".submit-btn").click(function(e){
   var $this = $(this);
   if($this.find("#place-form-item").valid()) {
       $this.parents(".form-wrap").hide();
       $this.parents().next(".success-msg").show()
     e.preventDefault();
   }
});

Not sure how to get it so that upon click, the form passed validation and then hides the one form and shows the success message. Unless I'm targeting something incorrectly.

Body:
The problem is that .next() only targets the sibling that immediately follows the target. Given your structure, .success-msg precedes .form-wrap. As such, .next() cannot target it.

To resolve this, instead of $this.parents().next(".success-msg").show(), you can target the parent element .place-form and then make use of .find() to find the relevant .success-msg with $this.parents(".place-form").find(".success-msg").show().

You'll also want to move your e.preventDefault() to outside of your conditional.

This can be seen in the following example:

$(".submit-btn").click(function(e) {
  e.preventDefault();
  var $this = $(this);
  if ($('#place-form-item').valid()) {
    $this.parents(".form-wrap").hide();
    $this.parents(".place-form").find(".success-msg").show();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

<div class="place-form">
  <div class="success-msg" style="display:none;">
    <p>Thanks for your submission! We will contact you shortly.</p>
  </div>
  <div class="form-wrap">
    <form id="place-form-item">
      <div class="form-row">
        <input id="fname" type="text" name="fname" placeholder="Your First Name" required />
      </div>
      <div class="form-row">
        <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />
      </div>
      <div class="form-row">
        <input id="form-email" type="email" name="email" placeholder="Your Email" required />
      </div>
      <div class="btn-row">
        <button class="submit-btn">submit</button>
      </div>
    </form>
  </div>
</div>

Hope this helps! :)


问:
Getting results even if row doesn't exist in JOIN table
I store 2 different backup types (Full or Log) and also have 2 different server types (Local or Azure) this query below brings back the correct results as 3 rows are returned, however when i delete a row which corresponds to this line in the SQL query:

```<code>AND (r4.Type = 'Full' AND r4.Server = 'Azure')
</code>```

Only 2 rows are then retrieved because their isn't a row which exists in the table for type 'Full' and server 'Azure'

This is the query i've done:

```<code>SELECT DISTINCT
   r1.Tenant,
   r1.Name,
   r1.DBName,
   r1.Server as Server1,
   r1.Type as Type1,
   r1.Date as Date1,
   r2.Type as Type2,
   r2.Date as Date2,
   r2.Server as Server2,
   r3.Type as Type3,
   r3.Date as Date3,
   r3.Server as Server3,
   r4.Type as Typ4,
   r4.Date as Date4,
   r4.Server as Server4
FROM #Results AS r1
JOIN #Results AS r2 ON r2.DBName = r1.DBName
JOIN #Results AS r3 ON r3.DBName = r1.DBName
JOIN #Results AS r4 ON r4.DBName = r1.DBName
WHERE
(r1.TYPE = 'Full' AND r1.Server = 'Local') AND
(r2.TYPE = 'Log' AND r2.Server = 'Local') AND
(r3.Type = 'Full' AND r3.Server = 'Azure') AND
(r4.Type = 'Log' AND r4.Server = 'Azure')
ORDER BY r1.Tenant
</code>```

As you can see from the screenshot above, this is the data retrieved. I expect another row containing the following:

Log, Local

Full, Local

Log, Azure

NULL, NULL (as a Full Azure backup doesn't exist)

Here is the data within the Result table:

答:
```<code> SELECT Tenant,  Name, DBName,
        MAX( CASE WHEN Server = 'local' and Type = 'full'
                  THEN Date END) as FullLocalDate,
        MAX( CASE WHEN Server = 'local' and Type = 'log'
                  THEN Date END) as LogLocalDate,
        MAX( CASE WHEN Server = 'azure' and Type = 'full'
                  THEN Date END) as FullAzureDate,
        MAX( CASE WHEN Server = 'azure' and Type = 'log'
                  THEN Date END) as LogAzureDate
 FROM #Results r
 GROUP BY Tenant,  Name, DBName
</code>```

I remove the columns Server1 Server2 ... because is already part of the date information. But can be add it if need it.

Body:
I store 2 different backup types (Full or Log) and also have 2 different server types (Local or Azure) this query below brings back the correct results as 3 rows are returned, however when i delete a row which corresponds to this line in the SQL query:

AND (r4.Type = 'Full' AND r4.Server = 'Azure')

Only 2 rows are then retrieved because their isn't a row which exists in the table for type 'Full' and server 'Azure'

This is the query i've done:

SELECT DISTINCT
   r1.Tenant,
   r1.Name,
   r1.DBName,
   r1.Server as Server1,
   r1.Type as Type1,
   r1.Date as Date1,
   r2.Type as Type2,
   r2.Date as Date2,
   r2.Server as Server2,
   r3.Type as Type3,
   r3.Date as Date3,
   r3.Server as Server3,
   r4.Type as Typ4,
   r4.Date as Date4,
   r4.Server as Server4
FROM #Results AS r1
JOIN #Results AS r2 ON r2.DBName = r1.DBName
JOIN #Results AS r3 ON r3.DBName = r1.DBName
JOIN #Results AS r4 ON r4.DBName = r1.DBName
WHERE
(r1.TYPE = 'Full' AND r1.Server = 'Local') AND
(r2.TYPE = 'Log' AND r2.Server = 'Local') AND
(r3.Type = 'Full' AND r3.Server = 'Azure') AND
(r4.Type = 'Log' AND r4.Server = 'Azure')
ORDER BY r1.Tenant

As you can see from the screenshot above, this is the data retrieved. I expect another row containing the following:

Log, Local

Full, Local

Log, Azure

NULL, NULL (as a Full Azure backup doesn't exist)

Here is the data within the Result table:

Body:
 SELECT Tenant,  Name, DBName,
        MAX( CASE WHEN Server = 'local' and Type = 'full'
                  THEN Date END) as FullLocalDate,
        MAX( CASE WHEN Server = 'local' and Type = 'log'
                  THEN Date END) as LogLocalDate,
        MAX( CASE WHEN Server = 'azure' and Type = 'full'
                  THEN Date END) as FullAzureDate,
        MAX( CASE WHEN Server = 'azure' and Type = 'log'
                  THEN Date END) as LogAzureDate
 FROM #Results r
 GROUP BY Tenant,  Name, DBName

I remove the columns Server1 Server2 ... because is already part of the date information. But can be add it if need it.


问:
How to use SQL Joins and Selects to get results from a third table that matches the first two?
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

```<code>Select * from 3rdTable where City='' AND State='';
</code>```

Result from Join is like

```<code> - City | State
 - A    | B
 - C    | D
 - E    | F
</code>```

Example Result if only 1 row of the 3rd table matches

```<code> - C    |  D
</code>```

How can this be done?

答:
I think this could help you:

```<code>SELECT T3.*
FROM
table_1_2_join T12 /* replace this placeholder table with the select statement that joins your 2 tables */
JOIN table_3 T3 ON T3.City = T12.city AND T3.state = T12.state
</code>```

Let me know if you need more details.

Body:
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

Select * from 3rdTable where City='' AND State='';

Result from Join is like

 - City | State
 - A    | B
 - C    | D
 - E    | F

Example Result if only 1 row of the 3rd table matches

 - C    |  D

How can this be done?

Body:
I think this could help you:

SELECT T3.*
FROM
table_1_2_join T12 /* replace this placeholder table with the select statement that joins your 2 tables */
JOIN table_3 T3 ON T3.City = T12.city AND T3.state = T12.state

Let me know if you need more details.


答:
My question is, how do we preserve the prefix of TestData or TestVectors during install?

Ordinarily, Automake computes the basename of each target and uses that at install time to record the file directly in the designated directory.  If the target names contain directory prefixes that you want to propagate into the installed image then you can tell Automake about it by using the nobase_ prefix on the relevant target variable.  This can be combined with other prefixes such as dist_.  For example,

```<code>nobase_dist_pkgdata_DATA = \
   $(testdata_FILES) \
   $(testvector_FILES)
</code>```

Prefixes in general are described in section 3.3 of the Automake manual, and nobase_ in particular is detailed in section 12.1 of the Automake manual.

Title: Preserve data file prefix when using dist_pkgdata_DATA?

Body:
Our test data is organized with two folders. We have TestData/ and TestVectors/, depending on the form of the data:

- TestData
  |
  + a.dat
  + b.dat
  + ...

- TestVector
  |
  + x.vec
  + y.vec
  + ...

Our Makefile.am has:

dist_pkgdata_DATA = \
   $(testdata_FILES) \
   $(testvector_FILES)

testdata_FILES = \
   TestData/a.dat TestData/b.dat \
   ...

testvector_FILES = \
   TestVectors/x.vec TestVectors/y.vec \
   ...

Automake installs them in @datadir@/@PACKAGE@/, but we lose the TestData and TestVectors prefix upon installation. That is, once installed, all the files are lumped together:

- @datadir@/@PACKAGE@/
  |
  + a.dat
  + b.dat
  + ...
  + x.vec
  + y.vec
  + ...

There's a very similar question at Install arbitrary data files in arbitrary locations with Automake?, but I am not quite following what needs to be done to ensure make install works as expected.

My question is, how do we preserve the prefix of TestData or TestVectors during install?

Body:
My question is, how do we preserve the prefix of TestData or TestVectors during install?

Ordinarily, Automake computes the basename of each target and uses that at install time to record the file directly in the designated directory.  If the target names contain directory prefixes that you want to propagate into the installed image then you can tell Automake about it by using the nobase_ prefix on the relevant target variable.  This can be combined with other prefixes such as dist_.  For example,

nobase_dist_pkgdata_DATA = \
   $(testdata_FILES) \
   $(testvector_FILES)

Prefixes in general are described in section 3.3 of the Automake manual, and nobase_ in particular is detailed in section 12.1 of the Automake manual.


问:
Tomcat memory leak warnings when gracefully shutting down - Codahale
I'm having an issue when attempting to when gracefully shutting down tomcat. This severe warning is issued and the application will hang until terminated. Seems to be related to codahale in this case unlike another few similar questions. Any suggestions on a fix. Thanks in advance.

(Using Tomcat 7.0.78 through Intellij)

```<code>created a ThreadLocal with key of type
[com.codahale.metrics.ThreadLocalRandom$1] (value
[com.codahale.metrics.ThreadLocalRandom$1@7008afaf]) and a value of
type [com.codahale.metrics.ThreadLocalRandom] (value
[com.codahale.metrics.ThreadLocalRandom@cb6fe27]) but failed to remove
it when the web application was stopped. Threads are going to be
renewed over time to try and avoid a probable memory leak.
</code>```

答:
This is an open issue: https://github.com/dropwizard/metrics/issues/742

com.codahale.metrics.ThreadLocalRandom is a class loaded by the same classloader that loads Codahale so that class has a reference to it's classloader which prevents all other classes to be garbage collected. If codahale is part of your application then all your classes will not be garbage collected.
Try to put codahale in common/lib instead of your app and see what happens. I think that that would allow your application to be gc-ed.

Body:
I'm having an issue when attempting to when gracefully shutting down tomcat. This severe warning is issued and the application will hang until terminated. Seems to be related to codahale in this case unlike another few similar questions. Any suggestions on a fix. Thanks in advance.

(Using Tomcat 7.0.78 through Intellij)

created a ThreadLocal with key of type
[com.codahale.metrics.ThreadLocalRandom$1] (value
[com.codahale.metrics.ThreadLocalRandom$1@7008afaf]) and a value of
type [com.codahale.metrics.ThreadLocalRandom] (value
[com.codahale.metrics.ThreadLocalRandom@cb6fe27]) but failed to remove
it when the web application was stopped. Threads are going to be
renewed over time to try and avoid a probable memory leak.


问:
How does Postgresql's '%' affect a LIKE comparison
When comparing the results of a function which returns TEXT, LIKE '%word', or LIKE 'word%' will produce a match, but not LIKE 'word'.

```<code>SELECT extract_json_text(lst_logs.data) AS machine
   FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra';
</code>```

Gives me no results, but

```<code>SELECT extract_json_text(lst_logs.data) AS machine
       FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE '%Cupra';
</code>```

or even

```<code>SELECT extract_json_text(lst_logs.data) AS machine
       FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra%';
</code>```

Gives me what I want, yet my results say that the text is Cupra.

How is % able to effect the match from either side of the string?

EDIT Here is the function which extracts the text.  There are escaped quotes inside the JSON which is which I use TRIM.

```<code>CREATE OR REPLACE FUNCTION cupra.lst_machine(jsonb)
  RETURNS text
IMMUTABLE
LANGUAGE plpgsql
AS $$
BEGIN
  RETURN (TRIM(BOTH '\"' FROM $1->>5));
END;
$$;
</code>```

答:
Because of how LIKE works.

The % is a wildcard match.

Stating LIKE 'word' is the equivalent to stating = 'word'; that is to state, "look for 'word' and exactly 'word' as the entire contents of the field." However, LIKE is slower than = in that instance.

Adding % to the mix causes LIKE to find 'word' anywhere in the string. It doesn't care which side the % is placed.

To find out what's in front, you can get the code point by doing:

```<code>SELECT ascii(extract_json_text(lst_logs.data)) AS first_char_code_point
  FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra%' LIMIT 1;
</code>```

ascii() will only return the code point for the first character. If it isn't 67, then you've found your culprit.

For the last character, the following should do the trick:

```<code>SELECT ascii(substr(extract_json_text(lst_logs.data),
       length(extract_json_text(lst_logs.data))) AS last_char_code_point
  FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra%' LIMIT 1;
</code>```

If it isn't 97, then you've found your culprit.

Body:
When comparing the results of a function which returns TEXT, LIKE '%word', or LIKE 'word%' will produce a match, but not LIKE 'word'.

SELECT extract_json_text(lst_logs.data) AS machine
   FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra';

Gives me no results, but

SELECT extract_json_text(lst_logs.data) AS machine
       FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE '%Cupra';

or even

SELECT extract_json_text(lst_logs.data) AS machine
       FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra%';

Gives me what I want, yet my results say that the text is Cupra.

How is % able to effect the match from either side of the string?

EDIT Here is the function which extracts the text.  There are escaped quotes inside the JSON which is which I use TRIM.

CREATE OR REPLACE FUNCTION cupra.lst_machine(jsonb)
  RETURNS text
IMMUTABLE
LANGUAGE plpgsql
AS $$
BEGIN
  RETURN (TRIM(BOTH '\"' FROM $1->>5));
END;
$$;

Body:
Because of how LIKE works.

The % is a wildcard match.

Stating LIKE 'word' is the equivalent to stating = 'word'; that is to state, "look for 'word' and exactly 'word' as the entire contents of the field." However, LIKE is slower than = in that instance.

Adding % to the mix causes LIKE to find 'word' anywhere in the string. It doesn't care which side the % is placed.

To find out what's in front, you can get the code point by doing:

SELECT ascii(extract_json_text(lst_logs.data)) AS first_char_code_point
  FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra%' LIMIT 1;

ascii() will only return the code point for the first character. If it isn't 67, then you've found your culprit.

For the last character, the following should do the trick:

SELECT ascii(substr(extract_json_text(lst_logs.data),
       length(extract_json_text(lst_logs.data))) AS last_char_code_point
  FROM lst_logs WHERE extract_json_text(lst_logs.data) LIKE 'Cupra%' LIMIT 1;

If it isn't 97, then you've found your culprit.


问:
Service Fabric App Deployment Not Creating Service
When I deploy my service fabric app to my local cluster via Visual Studio 2017, my service is not getting created.  I have to manually go into the Service Fabric Explorer and click create.  Why?

Background: I did some project re-naming and moving folders around.  I think that broke this as it used to work.

Output Window of Service Fabric Tools

```<code>Started executing script 'Publish-NewServiceFabricApplication'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; Publish-NewServiceFabricApplication -ApplicationPackagePath 'C:\Users\mdepouw\source\repos\The Repo\TheProject.IdentityDomain\TheProject.Identity.App\pkg\Debug' -ApplicationParameterFilePath 'C:\Users\mdepouw\source\repos\The Repo\TheProject.IdentityDomain\TheProject.Identity.App\PublishProfiles\..\ApplicationParameters\Local.5Node.xml' -ApplicationParameter @{_WFDebugParams_='[{"""CodePackageName""":"""Code""","""CodePackageLinkFolder""":null,"""ConfigPackageName""":null,"""ConfigPackageLinkFolder""":null,"""DataPackageName""":null,"""DataPackageLinkFolder""":null,"""LockFile""":null,"""WorkingFolder""":null,"""ServiceManifestName""":"""IdentityServicePkg""","""EntryPointType""":"""Main""","""DebugExePath""":"""C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\Packages\\Debugger\\VsDebugLaunchNotify.exe""","""DebugArguments""":""" {83288f71-0cb5-49bc-b56b-f212d6fc8486} -p [ProcessId] -tid [ThreadId]""","""DebugParametersFile""":null}]'} -Action Create -SkipPackageValidation:$true -ErrorAction Stop
Creating application...

ApplicationName        : fabric:/IdentityApp
ApplicationTypeName    : IdentityAppType
ApplicationTypeVersion : 1.0.0
ApplicationParameters  : { "_WFDebugParams_" = "[{"CodePackageName":"Code","CodePackageLinkFolder":null,"ConfigPackageN
                         ame":null,"ConfigPackageLinkFolder":null,"DataPackageName":null,"DataPackageLinkFolder":null,"
                         LockFile":null,"WorkingFolder":null,"ServiceManifestName":"IdentityServicePkg","EntryPointType
                         ":"Main","DebugExePath":"C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\C
                         ommon7\\Packages\\Debugger\\VsDebugLaunchNotify.exe","DebugArguments":"
                         {83288f71-0cb5-49bc-b56b-f212d6fc8486} -p [ProcessId] -tid
                         [ThreadId]","DebugParametersFile":null}]" }

Create application succeeded.

Finished executing script 'Publish-NewServiceFabricApplication'.
Time elapsed: 00:00:07.2779519
Started executing script 'Get-ServiceFabricApplicationStatus'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; Get-ServiceFabricApplicationStatus -ApplicationName 'fabric:/IdentityApp' -ErrorAction Stop
The application has started.
Service Status:

The application is ready.
Finished executing script 'Get-ServiceFabricApplicationStatus'.
Time elapsed: 00:00:04.7490158
Launching the browser with URL https://localhost:44300/ to open the application.Started executing script 'Unpublish-ServiceFabricApplication'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; Unpublish-ServiceFabricApplication -ApplicationName 'fabric:/IdentityApp' -ErrorAction Stop
Removing application...
Remove application instance succeeded
Finished executing script 'Unpublish-ServiceFabricApplication'.
Time elapsed: 00:00:08.9813491
Started executing script 'UnregisterApplicationType'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; if (Get-ServiceFabricApplicationType -ApplicationTypeName 'IdentityAppType' | Where-Object { $_.ApplicationTypeVersion -eq '1.0.0' }) { Unregister-ServiceFabricApplicationType -ApplicationTypeName 'IdentityAppType' -ApplicationTypeVersion '1.0.0' -ErrorAction Stop -Force }
Unregister application type succeeded.
Finished executing script 'UnregisterApplicationType'.
Time elapsed: 00:00:07.9996788
Launching the browser with URL https://localhost:44300/ to open the application.
</code>```

答:
In ApplicationManifest.xml I had to define the <DefaultServices> I wanted:

<DefaultServices>

    <Service Name="Identity">
      <StatelessService ServiceTypeName="IdentityService" InstanceCount="[Identity_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
</DefaultServices>
```

Body:
When I deploy my service fabric app to my local cluster via Visual Studio 2017, my service is not getting created.  I have to manually go into the Service Fabric Explorer and click create.  Why?

Background: I did some project re-naming and moving folders around.  I think that broke this as it used to work.

Output Window of Service Fabric Tools

Started executing script 'Publish-NewServiceFabricApplication'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; Publish-NewServiceFabricApplication -ApplicationPackagePath 'C:\Users\mdepouw\source\repos\The Repo\TheProject.IdentityDomain\TheProject.Identity.App\pkg\Debug' -ApplicationParameterFilePath 'C:\Users\mdepouw\source\repos\The Repo\TheProject.IdentityDomain\TheProject.Identity.App\PublishProfiles\..\ApplicationParameters\Local.5Node.xml' -ApplicationParameter @{_WFDebugParams_='[{"""CodePackageName""":"""Code""","""CodePackageLinkFolder""":null,"""ConfigPackageName""":null,"""ConfigPackageLinkFolder""":null,"""DataPackageName""":null,"""DataPackageLinkFolder""":null,"""LockFile""":null,"""WorkingFolder""":null,"""ServiceManifestName""":"""IdentityServicePkg""","""EntryPointType""":"""Main""","""DebugExePath""":"""C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\Packages\\Debugger\\VsDebugLaunchNotify.exe""","""DebugArguments""":""" {83288f71-0cb5-49bc-b56b-f212d6fc8486} -p [ProcessId] -tid [ThreadId]""","""DebugParametersFile""":null}]'} -Action Create -SkipPackageValidation:$true -ErrorAction Stop
Creating application...

ApplicationName        : fabric:/IdentityApp
ApplicationTypeName    : IdentityAppType
ApplicationTypeVersion : 1.0.0
ApplicationParameters  : { "_WFDebugParams_" = "[{"CodePackageName":"Code","CodePackageLinkFolder":null,"ConfigPackageN
                         ame":null,"ConfigPackageLinkFolder":null,"DataPackageName":null,"DataPackageLinkFolder":null,"
                         LockFile":null,"WorkingFolder":null,"ServiceManifestName":"IdentityServicePkg","EntryPointType
                         ":"Main","DebugExePath":"C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\C
                         ommon7\\Packages\\Debugger\\VsDebugLaunchNotify.exe","DebugArguments":"
                         {83288f71-0cb5-49bc-b56b-f212d6fc8486} -p [ProcessId] -tid
                         [ThreadId]","DebugParametersFile":null}]" }

Create application succeeded.

Finished executing script 'Publish-NewServiceFabricApplication'.
Time elapsed: 00:00:07.2779519
Started executing script 'Get-ServiceFabricApplicationStatus'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; Get-ServiceFabricApplicationStatus -ApplicationName 'fabric:/IdentityApp' -ErrorAction Stop
The application has started.
Service Status:

The application is ready.
Finished executing script 'Get-ServiceFabricApplicationStatus'.
Time elapsed: 00:00:04.7490158
Launching the browser with URL https://localhost:44300/ to open the application.Started executing script 'Unpublish-ServiceFabricApplication'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; Unpublish-ServiceFabricApplication -ApplicationName 'fabric:/IdentityApp' -ErrorAction Stop
Removing application...
Remove application instance succeeded
Finished executing script 'Unpublish-ServiceFabricApplication'.
Time elapsed: 00:00:08.9813491
Started executing script 'UnregisterApplicationType'.
[void](Connect-ServiceFabricCluster); Import-Module 'C:\Program Files\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1'; if (Get-ServiceFabricApplicationType -ApplicationTypeName 'IdentityAppType' | Where-Object { $_.ApplicationTypeVersion -eq '1.0.0' }) { Unregister-ServiceFabricApplicationType -ApplicationTypeName 'IdentityAppType' -ApplicationTypeVersion '1.0.0' -ErrorAction Stop -Force }
Unregister application type succeeded.
Finished executing script 'UnregisterApplicationType'.
Time elapsed: 00:00:07.9996788
Launching the browser with URL https://localhost:44300/ to open the application.

Body:
In ApplicationManifest.xml I had to define the <DefaultServices> I wanted:

<DefaultServices>
    <!-- The section below creates instances of service types, when an instance of this
         application type is created. You can also create one or more instances of service type using the
         ServiceFabric PowerShell module.

         The attribute ServiceTypeName below must match the name defined in the imported ServiceManifest.xml file. -->
    <Service Name="Identity">
      <StatelessService ServiceTypeName="IdentityService" InstanceCount="[Identity_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
</DefaultServices>


问:
SQL to count turnover and group by month (please check)
I have three tables and I need to calculte turnover for John Smith in year 2015 divided by months.

```<code>                   OrderItems
                   ------------       Orders
Products           OrderItem_ID       ------
----------         Order_ID   <--->   Order_ID
Product_ID  <--->  Product_ID         Type
Name               Quantity           Date
Category           UnitPrice          Customer
</code>```

The tables are connected by Order_ID & Order_ID (tabs OrderItems and Orders) and then by Product_IDs (tabs Products and OrderItems). I guess I don't need tab Products anyway.

```<code>Orders (Order_ID INT, Type INT, Date DATETIME, Customer VARCHAR)
OrderItems (OrderItem_ID INT, Order_ID INT, Product_ID INT, Quantity INT, UnitPrice MONEY)
Products (Product_ID INT, Name VARCHAR, Category VARCHAR)
</code>```

I have been dozens and dozens minutes googling and knowledge refreshing because it is a long while since I have used SQL for the last time.

I wrote this query but totally I am not sure. Can you check it please?

```<code>SELECT
    SUM(a.quantity * a.price) AS 'turnover',
    DATEPART(month, a.date) AS 'month'
FROM
(
    SELECT
        Quantity.OrderItems AS 'quantity',
        UnitPrice.OrderItems AS 'price',
        Date.Orders AS 'date',
        Customer.Orders AS 'customer'
    FROM Orders
    JOIN Orders
        ON OrderItems.Order_ID = Orders.Order_ID
    WHERE
        date BETWEEN 2015-01-01 and 2015-12-31
        AND customer = 'John Smith'
) a
GROUP BY month
ORDER BY month
</code>```

Thank you very much

//corrected one minor typo in code

答:
You need to join Orders to OrderItems

```<code>SELECT
    SUM(a.quantity * a.price) AS 'turnover',
    DATEPART(month, a.date) AS 'month'
FROM
(
    SELECT
        OI.Quantity AS 'quantity',
        OI.UnitPrice AS 'price',
        O.Date AS 'date',
        O.Customer AS 'customer'
    FROM Orders O
    INNER JOIN OrderItems OI
        ON O.Order_ID = OI.Order_ID
    WHERE
        O.date BETWEEN 2015-01-01 and 2015-12-31
        AND O.customer = 'John Smith'
) a
GROUP BY DATEPART(month, a.date)
ORDER BY DATEPART(month, a.date)
</code>```

Body:
I have three tables and I need to calculte turnover for John Smith in year 2015 divided by months.

                   OrderItems
                   ------------       Orders
Products           OrderItem_ID       ------
----------         Order_ID   <--->   Order_ID
Product_ID  <--->  Product_ID         Type
Name               Quantity           Date
Category           UnitPrice          Customer

The tables are connected by Order_ID & Order_ID (tabs OrderItems and Orders) and then by Product_IDs (tabs Products and OrderItems). I guess I don't need tab Products anyway.

Orders (Order_ID INT, Type INT, Date DATETIME, Customer VARCHAR)
OrderItems (OrderItem_ID INT, Order_ID INT, Product_ID INT, Quantity INT, UnitPrice MONEY)
Products (Product_ID INT, Name VARCHAR, Category VARCHAR)

I have been dozens and dozens minutes googling and knowledge refreshing because it is a long while since I have used SQL for the last time.

I wrote this query but totally I am not sure. Can you check it please?

SELECT
    SUM(a.quantity * a.price) AS 'turnover',
    DATEPART(month, a.date) AS 'month'
FROM
(
    SELECT
        Quantity.OrderItems AS 'quantity',
        UnitPrice.OrderItems AS 'price',
        Date.Orders AS 'date',
        Customer.Orders AS 'customer'
    FROM Orders
    JOIN Orders
        ON OrderItems.Order_ID = Orders.Order_ID
    WHERE
        date BETWEEN 2015-01-01 and 2015-12-31
        AND customer = 'John Smith'
) a
GROUP BY month
ORDER BY month

Thank you very much

//corrected one minor typo in code

Body:
You need to join Orders to OrderItems

SELECT
    SUM(a.quantity * a.price) AS 'turnover',
    DATEPART(month, a.date) AS 'month'
FROM
(
    SELECT
        OI.Quantity AS 'quantity',
        OI.UnitPrice AS 'price',
        O.Date AS 'date',
        O.Customer AS 'customer'
    FROM Orders O
    INNER JOIN OrderItems OI
        ON O.Order_ID = OI.Order_ID
    WHERE
        O.date BETWEEN 2015-01-01 and 2015-12-31
        AND O.customer = 'John Smith'
) a
GROUP BY DATEPART(month, a.date)
ORDER BY DATEPART(month, a.date)