问:
Organizing retrieved JSON data from YQL
Hello fellow developers,

I recently had given up on a project involving AJAX request due to CORS but I finally found a work around in YQL. I have finally figured out how to retrieve my JSON data.  Now I am trying to figure out how I can access this data and organize it in the way that I want. Here is my code currently.

```<code>var errormsg = "There was an ERROR I am sorry";
var requestURL = "https://www.tip.it/runescape/json/hiscore_user?old_stats=1&rsn="

$(document).ready(function() {
    $('#retrievestats').click(function() {
        var RSname = document.getElementById('Userinputform').value.toLowerCase();
        getUserData(RSname)
    });
});

function getUserData(RSname, callback) {
    var yql = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + requestURL + RSname + '"') + '&format=json&diagnostics=false&callback=?';

    if (!RSname) {
        alert('Please enter a username');
        return false;
    }

    $.getJSON(yql, function(data){
        console.log(data);
    });
}
</code>```

As you can see, I can successfully view my data in the console of my browser but it looks as if it is all I can do. Is there any way for me to organize/separate the data? Currently the JSON gives me information in such a way

```<code>"orig_rsn":"zezima","rsn":"zezima","stats":{"overall":{"level":1280,"exp":12426850},"attack":{"level":71,"exp":815941},"defence":{"level":70,"exp":737635},"strength":{"level":70,"exp":737679},"constitution":{"level":69,"exp":697918},"range":{"level":43,"exp":53916},"prayer":{"level":46,"exp":68845},"magic":{"level":43,"exp":54901},"cooking":{"level":77,"exp":1560984},"woodcutting":{"level":73,"exp":1002436},"fletching":{"level":68,"exp":657325},
</code>```

I guess what I am asking is how can I take that JSON data, and use it to dynamically replace the values in the table below according to their names

```<code>                  <tr id=>
                    <td id=Fish>Fishing</td>
                    <td id=Fishlvl>1</td>
                    <td id=Fishexp>1</td>
                  </tr>
                  <tr id=>
                    <td id=FM>Firemaking</td>
                    <td id=FMlvl>1</td>
                    <td id=FMexp>1</td>
                  </tr>
                  <tr id=>
                    <td id=Craft>Crafting</td>
                    <td id=Craftlvl>1</td>
                    <td id=Craftexp>1</td>
                  </tr>
                  <tr id=>
                    <td id=Smith>Smithing</td>
                    <td id=Smithlvl>1</td>
                    <td id=Smithexp>1</td>
                  </tr>
</code>```

答:
A simple solution is using jQuery and creating your HTML using template function.

```<code> var data = {
   "orig_rsn":"zezima",
   "rsn":"zezima",
   "stats": {
     "overall": {"level":1280,"exp":12426850},
     "attack":{"level":71,"exp":815941},
     "defence":{"level":70,"exp":737635},
     "strength":{"level":70,"exp":737679},
     "constitution":{"level":69,"exp":697918},
     "range":{"level":43,"exp":53916},
     "prayer":{"level":46,"exp":68845},
     "magic":{"level":43,"exp":54901},
     "cooking":{"level":77,"exp":1560984},
     "woodcutting":{"level":73,"exp":1002436},
     "fletching":{"level":68,"exp":657325}
   }
 }

 $(document).ready(function() {

   var createRow = function(skill, level, exp){
     return   "<tr>" +
              "<td id=" + skill + ">" + skill +"</td>" +
              "<td id=" + skill + "lvl>" + level + "</td>" +
              "<td id=" + skill +"exp>"+exp+"</td></tr>";
   };

   var createTable = function(data){
       var html = "<table class='solid'><th>Skill</th><th>Level</th>               <th>experience</th>"
       for(var propt in data.stats){
         var skill = data.stats[propt];
         html+=createRow(propt,skill["level"],skill["exp"]);
       }
       html+="</table>";
       return html;
   };

    $("#container").html(createTable(data));
 });
</code>```

Of course, there are other ways using modern JS frameworks. But, if you want to use jQuery, that is it!

Pluker Example

Title: Organizing retrieved JSON data from YQL

Body:
Hello fellow developers,

I recently had given up on a project involving AJAX request due to CORS but I finally found a work around in YQL. I have finally figured out how to retrieve my JSON data.  Now I am trying to figure out how I can access this data and organize it in the way that I want. Here is my code currently.

var errormsg = "There was an ERROR I am sorry";
var requestURL = "https://www.tip.it/runescape/json/hiscore_user?old_stats=1&rsn="

$(document).ready(function() {
    $('#retrievestats').click(function() {
        var RSname = document.getElementById('Userinputform').value.toLowerCase();
        getUserData(RSname)
    });
});

function getUserData(RSname, callback) {
    var yql = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + requestURL + RSname + '"') + '&format=json&diagnostics=false&callback=?';

    if (!RSname) {
        alert('Please enter a username');
        return false;
    }

    $.getJSON(yql, function(data){
        console.log(data);
    });
}

As you can see, I can successfully view my data in the console of my browser but it looks as if it is all I can do. Is there any way for me to organize/separate the data? Currently the JSON gives me information in such a way

"orig_rsn":"zezima","rsn":"zezima","stats":{"overall":{"level":1280,"exp":12426850},"attack":{"level":71,"exp":815941},"defence":{"level":70,"exp":737635},"strength":{"level":70,"exp":737679},"constitution":{"level":69,"exp":697918},"range":{"level":43,"exp":53916},"prayer":{"level":46,"exp":68845},"magic":{"level":43,"exp":54901},"cooking":{"level":77,"exp":1560984},"woodcutting":{"level":73,"exp":1002436},"fletching":{"level":68,"exp":657325},

I guess what I am asking is how can I take that JSON data, and use it to dynamically replace the values in the table below according to their names

                    Fishing
                    1
                    1

                    Firemaking
                    1
                    1

                    Crafting
                    1
                    1

                    Smithing
                    1
                    1

Body:
A simple solution is using jQuery and creating your HTML using template function.

 var data = {
   "orig_rsn":"zezima",
   "rsn":"zezima",
   "stats": {
     "overall": {"level":1280,"exp":12426850},
     "attack":{"level":71,"exp":815941},
     "defence":{"level":70,"exp":737635},
     "strength":{"level":70,"exp":737679},
     "constitution":{"level":69,"exp":697918},
     "range":{"level":43,"exp":53916},
     "prayer":{"level":46,"exp":68845},
     "magic":{"level":43,"exp":54901},
     "cooking":{"level":77,"exp":1560984},
     "woodcutting":{"level":73,"exp":1002436},
     "fletching":{"level":68,"exp":657325}
   }
 }

 $(document).ready(function() {

   var createRow = function(skill, level, exp){
     return   "<tr>" +
              "<td id=" + skill + ">" + skill +"</td>" +
              "<td id=" + skill + "lvl>" + level + "</td>" +
              "<td id=" + skill +"exp>"+exp+"</td></tr>";
   };

   var createTable = function(data){
       var html = "<table class='solid'><th>Skill</th><th>Level</th>               <th>experience</th>"
       for(var propt in data.stats){
         var skill = data.stats[propt];
         html+=createRow(propt,skill["level"],skill["exp"]);
       }
       html+="</table>";
       return html;
   };

    $("#container").html(createTable(data));
 });

Of course, there are other ways using modern JS frameworks. But, if you want to use jQuery, that is it!

Pluker Example


来源: stackexchange

问:
JSON deserialization error on integer types - C#
I am implementing for the first time a POST in WebAPI from an Angular client that receives a JObject which I then deserialize to my objects of interest.
But when I check the resulting object I see that all fields are appropriately filled except those meant to be integers.

This is part of my POST method

```<code> // POST: api/PresupuestosApi
    [ResponseType(typeof(Presupuesto))]
    public async Task<IHttpActionResult> PostPresupuesto([FromBody]JObject presupuesto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        try
        {
            Presupuesto p = presupuesto.ToObject<Presupuesto>();
</code>```

My JSON looks like this:

```<code>{
"sTitulo": "Agentasa",
"cSolicitante":
{
    "eRol": "SOLICITANTE",
    "sEmail": "bla@sdlfkjsf.com",
    "iTelefono": "122299935",
    "sNombre": "Clau",
    "sApellido": "Clau"
},
"cTrabajo":
{
    "SNombreTrabajo": "Agenda"

},
"sMaterial": "sadsa",
"sDimAbierto": "12x22",
"sDimCerrado": "12x155",
"sImpresion": "Una cara",
"fGramaje": 12.5,
"iCantidad": 122,
 }
</code>```

And my Presupuesto class is this:

```<code>public class Presupuesto
{
    private int iIdPresupuesto;
    private string sTitulo;
    private Solicitante cSolicitante;
    private Trabajo cTrabajo;
    private string sMaterial;
    private string sDimAbierto;
    private string sDimCerrado;
    private float fGramaje;
    private string sImpresion;
    private int iCantidad;
  }
</code>```

So, when debugging I see this:

I am lost as to why it is correctly parsing every other type but int.
Any suggestions on this subject? I need to emphasize I have never worked with WebAPI before.

答: 0x0000007a in Hex = 122 in Dec.  Check your debugger settings. Debugger seems to be set to display integers in Hex.

ContentLicense: CC BY-SA 3.0

Body:
I am implementing for the first time a POST in WebAPI from an Angular client that receives a JObject which I then deserialize to my objects of interest.
But when I check the resulting object I see that all fields are appropriately filled except those meant to be integers.

This is part of my POST method

 // POST: api/PresupuestosApi
    [ResponseType(typeof(Presupuesto))]
    public async Task<IHttpActionResult> PostPresupuesto([FromBody]JObject presupuesto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        try
        {
            Presupuesto p = presupuesto.ToObject<Presupuesto>();

My JSON looks like this:

{
"sTitulo": "Agentasa",
"cSolicitante":
{
    "eRol": "SOLICITANTE",
    "sEmail": "bla@sdlfkjsf.com",
    "iTelefono": "122299935",
    "sNombre": "Clau",
    "sApellido": "Clau"
},
"cTrabajo":
{
    "SNombreTrabajo": "Agenda"

},
"sMaterial": "sadsa",
"sDimAbierto": "12x22",
"sDimCerrado": "12x155",
"sImpresion": "Una cara",
"fGramaje": 12.5,
"iCantidad": 122,
 }

And my Presupuesto class is this:

public class Presupuesto
{
    private int iIdPresupuesto;
    private string sTitulo;
    private Solicitante cSolicitante;
    private Trabajo cTrabajo;
    private string sMaterial;
    private string sDimAbierto;
    private string sDimCerrado;
    private float fGramaje;
    private string sImpresion;
    private int iCantidad;
  }

So, when debugging I see this:

I am lost as to why it is correctly parsing every other type but int.
Any suggestions on this subject? I need to emphasize I have never worked with WebAPI before.


问:
How to prevent content jumping up when resizing browser?
The image caption and content is held in place by the image. When window is resized or image is loading the page content jumps up and is then jumps back down again.

Is it possible to prevent the content from moving in this way?

```<code><div class="profile">
    <img src="http://lorempixel.com/g/720/720/nature" alt="" />
</div>
</code>```

See https://codepen.io/atoms/pen/bRdLVe

Built on Chris Ferdinandi's Kraken CSS framework.

This seems to do the trick:

```<code>.profile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
    float: left;
    height: 0;
    }
.profile img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    }
</code>```

and the result:
https://codepen.io/atoms/pen/jwbOYe

Now when you reload the page the text stays in place even when the image has not yet loaded. And you can resize the browser window to reflow the contents with the same result.

Not sure if the CSS is entirely correct but it seems to work.

答:
Firstly, you can add a class to your caption, like following:

```<code><p class="image-caption"><small>Image caption</small></p>
</code>```

And then add a "hidden" class in CSS:

```<code>.hidden {
  display: none;
}
</code>```

Then use jQuery to implement this feature:

```<code>$(document).ready( function() {
    $(".image-caption").addClass("hidden");
    $(".profile img").on('load', function() {
      $(".image-caption").removeClass("hidden");
    })
});
</code>```

Note: you need to include jQuery in your HTML code

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

Body:
The image caption and content is held in place by the image. When window is resized or image is loading the page content jumps up and is then jumps back down again.

Is it possible to prevent the content from moving in this way?

See https://codepen.io/atoms/pen/bRdLVe

Built on Chris Ferdinandi's Kraken CSS framework.

This seems to do the trick:

.profile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
    float: left;
    height: 0;
    }
.profile img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    }

and the result:
https://codepen.io/atoms/pen/jwbOYe

Now when you reload the page the text stays in place even when the image has not yet loaded. And you can resize the browser window to reflow the contents with the same result.

Not sure if the CSS is entirely correct but it seems to work.

Body:
Firstly, you can add a class to your caption, like following:

<p class="image-caption"><small>Image caption</small></p>

And then add a "hidden" class in CSS:

.hidden {
  display: none;
}

Then use jQuery to implement this feature:

$(document).ready( function() {
    $(".image-caption").addClass("hidden");
    $(".profile img").on('load', function() {
      $(".image-caption").removeClass("hidden");
    })
});

Note: you need to include jQuery in your HTML code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


问:
How to call an apollo client query from a redux action
If I'm using redux and the apollo client in my app, what's the best way to trigger a query from an action outside of a component.

For example, if I have a standard app, with redux and apollo client configured, how should I trigger a "refresh" list.  I can trigger a function on the component itself which has the gql, but how would I do it from an action which would be more in line with flux.

```<code>import React, { Component, PropTypes } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { connect } from 'react-redux';
import { refreshProfile } from './actions';

class Profile extends Component { ... }
Profile.propTypes = {
  data: PropTypes.shape({
    loading: PropTypes.bool.isRequired,
    user: PropTypes.object,
  }).isRequired,
};

const UserQuery = gql`
  query getUser {
    user {
      id
      name
    }
  }
`;

const ProfileWithData = graphql(UserQuery)(Profile);
const ProfileWithDataAndState = connect(
 (state) => ({ user: state.user })),
 )(ProfileWithData);
</code>```

And, say I want to trigger an action to refresh that user data?  Since the logic is in the component itself, I'm not sure how I would trigger that gql query from the action itself.

答:
I see your needs, as I was just in your place couple of days ago.

The sad news is: if you want to use actions with graphQL, then you shouldn't be using apollo, just use graphQL directly. This is a very good article to walk you through - getting started with Redux and GraphQL. Why? Because Apollo uses a function called qraphql(query) which calls its own action.

How both Redux and Apollo work in a very simplistic way.

Redux: (User dispatches an action) ActionCreator --> Action --> Middleware --> reducer --> store --> bind data to user props.  And we control each state manually.

Apollo: (User passes the query/mutation to graphql(query)) all hidden (action --> store) then binds data to user props.

You can say that Apollo replaces Redux if you are using graphql, because it has a better integration with react and graphQL.

In the meantime, as Apollo is still developing, you might need redux for redux-form and so on. If you are used to some redux libraries, which you might consider to continue using redux besides Apollo, you can still bind their stores and add costumed middleware that probably apply to both, but you probably won't be fetching data using Redux actions through Apollo.

I know it feels like you are loosing redux, but you are getting all advantages with more async requests and caching taking care of with Apollo.

and if you need a place to start react-redux-apollo.

Body:
If I'm using redux and the apollo client in my app, what's the best way to trigger a query from an action outside of a component.

For example, if I have a standard app, with redux and apollo client configured, how should I trigger a "refresh" list.  I can trigger a function on the component itself which has the gql, but how would I do it from an action which would be more in line with flux.

import React, { Component, PropTypes } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { connect } from 'react-redux';
import { refreshProfile } from './actions';

class Profile extends Component { ... }
Profile.propTypes = {
  data: PropTypes.shape({
    loading: PropTypes.bool.isRequired,
    user: PropTypes.object,
  }).isRequired,
};

const UserQuery = gql`
  query getUser {
    user {
      id
      name
    }
  }
`;

const ProfileWithData = graphql(UserQuery)(Profile);
const ProfileWithDataAndState = connect(
 (state) => ({ user: state.user })),
 )(ProfileWithData);

And, say I want to trigger an action to refresh that user data?  Since the logic is in the component itself, I'm not sure how I would trigger that gql query from the action itself.


答:
You need UNION ALL or UNION (removes duplicates).</p>

```<code>SELECT ... GROUP BY ...
    UNION ALL
SELECT ... GROUP BY ...;
</code>```

Title: Merge two tables while doing operations

Body:
I'm currently creating two tables using SQL but I need to Union them and it's not clear how to do this when group bys are involved

Select ...
group by email, column 1

Which creates two tables like this:

Table1
+--------------+----------+
| email        |  Column1 |
+--------------+----------+
| 1            |    x     |
+--------------+----------+
| 2            |    x     |
+--------------+----------+

table2
+--------------+----------+
| email        |  Column1 |
+--------------+----------+
| 1            |    x     |
+--------------+----------+
| 2            |    x     |
+--------------+----------+

I want to merge them using a union into this

TableTotal
+--------------+----------+----------+----------+
| email        |  Column1 |  Column2 |  Column3 |
+--------------+----------+----------+----------+
| 1            |    x     |    x     |    x     |
+--------------+----------+----------+----------+
| 2            |    x     |    x     |    x     |
+--------------+----------+----------+----------+
| 1            |    x     |    x     |    x     |
+--------------+----------+----------+----------+
| 2            |    x     |    x     |    x     |
+--------------+----------+----------+----------+

But I don't know how to use union when I'm also grouping the selections. When I try to do it, I get the error "column1 is ambiguous".

Body:
You need UNION ALL or UNION (removes duplicates).

SELECT ... GROUP BY ...
    UNION ALL
SELECT ... GROUP BY ...;


问:
Twitter Bootstrap modal pushes html content to the left
If I open a modal dialog, through Twitter Bootstrap, I've noticed that it pushes all the html content of the page (i.e., in the container) to the left a little bit, and then puts it back to normal after closing itself. However, this only happens if the browser width is large enough to not be on the "mobile" (i.e., smallest) media query. This occurs with the latest versions of FF and Chrome (haven't tested other browsers).

You can see the problem here: http://jsfiddle.net/jxX6A/2/

Note: You have to increase the width of the "Result" window so it switches to the "med" or "large" media query css.

I have setup the HTML of the page based upon the examples shown on Bootstrap's site:

```<code><div class='container'>
    <div class='page-header'>
        <h4>My Heading</h4>
    </div>
    <div id='content'>
        This is some content.
    </div>
    <div class='footer'>
        <p>© 2013, me</p>
    </div>
</div>
</code>```

I'm guessing this is not supposed to happen, but I'm not sure what I've done wrong.

EDIT: This is a known bug, for more (and up-to-date) information, please see: https://github.com/twbs/bootstrap/issues/9855

答:
I really didn't like any of the solutions provided, and used a combination of them (along with a fix I previously had for qTip modals) to come up with something that worked best for me with Bootstrap v3.3.7.

UPDATE:  Resolved issue with fixed navbar positioning on iOS.

CSS:

```<code>/* fix issue with scrollbars and navbar fixed movement issue with bootstrap modals */
html {
    overflow-y: scroll !important;
}

html.noscroll {
    position: fixed;
    width: 100%;
    top:0;
    left: 0;
    height: 100%;
    overflow-y: scroll !important;
}

.modal-open .modal {
    padding-right: 0 !important;
}

.modal-open[style] {
    padding-right: 0px !important;
}

.modal::-webkit-scrollbar {
    width: 0 !important; /*removes the scrollbar but still scrollable*/
}
/* end modal fix */
</code>```

JavaScript:

```<code>/* fix for modal overlay scrollbar issue */
$(document).ready(function() {
    var curScrollTop;
    var prevScrollTop;
    $('.modal').on('show.bs.modal', function() {
        curScrollTop = $(window).scrollTop();
        $('html').addClass('noscroll').css('top', '-' + curScrollTop + 'px');
        $('.navbar-fixed-top').css({'position':'absolute','top':curScrollTop});
        $(window).on("resize", function() {
            var bodyH = $("body").height();
            var winH = $(window).height();
            if (winH > bodyH) {
                prevScrollTop = curScrollTop;
                curScrollTop = 0;
                $('.navbar-fixed-top').css({'position':'absolute','top':'0'});
            }
            else {
                $('html').removeClass("noscroll");
                if (curScrollTop == 0) window.scrollTo(0, prevScrollTop);
                else window.scrollTo(0, curScrollTop);
                curScrollTop = $(window).scrollTop();
                $('.navbar-fixed-top').css({'position':'absolute','top':curScrollTop});
                $('html').addClass("noscroll");
            }
            $('html').css('top', '-' + curScrollTop + 'px');
        })
    })
    $('.modal').on('hide.bs.modal', function() {
        $('html').removeClass("noscroll");
         $('.navbar-fixed-top').css({'position':'fixed','top':'0'});
        window.scrollTo(0, curScrollTop);
        $(window).off("resize");
    })
})
</code>```

This allows the background to be "fixed" yet still allows the modals to be scrollable, resolves the issue of double scrollbar and the repositioning of the fixed navbar.

Note that there is additional code there as well to remember the 'scroll' position (and return to it) when the modal is closed.

Hope this helps anyone else looking to achieve what I was going after.

Body:
If I open a modal dialog, through Twitter Bootstrap, I've noticed that it pushes all the html content of the page (i.e., in the container) to the left a little bit, and then puts it back to normal after closing itself. However, this only happens if the browser width is large enough to not be on the "mobile" (i.e., smallest) media query. This occurs with the latest versions of FF and Chrome (haven't tested other browsers).

You can see the problem here: http://jsfiddle.net/jxX6A/2/

Note: You have to increase the width of the "Result" window so it switches to the "med" or "large" media query css.

I have setup the HTML of the page based upon the examples shown on Bootstrap's site:

My Heading

        This is some content.

© 2013, me

I'm guessing this is not supposed to happen, but I'm not sure what I've done wrong.

EDIT: This is a known bug, for more (and up-to-date) information, please see: https://github.com/twbs/bootstrap/issues/9855

Body:
I really didn't like any of the solutions provided, and used a combination of them (along with a fix I previously had for qTip modals) to come up with something that worked best for me with Bootstrap v3.3.7.

UPDATE:  Resolved issue with fixed navbar positioning on iOS.

CSS:

/* fix issue with scrollbars and navbar fixed movement issue with bootstrap modals */
html {
    overflow-y: scroll !important;
}

html.noscroll {
    position: fixed;
    width: 100%;
    top:0;
    left: 0;
    height: 100%;
    overflow-y: scroll !important;
}

.modal-open .modal {
    padding-right: 0 !important;
}

.modal-open[style] {
    padding-right: 0px !important;
}

.modal::-webkit-scrollbar {
    width: 0 !important; /*removes the scrollbar but still scrollable*/
}
/* end modal fix */

JavaScript:

/* fix for modal overlay scrollbar issue */
$(document).ready(function() {
    var curScrollTop;
    var prevScrollTop;
    $('.modal').on('show.bs.modal', function() {
        curScrollTop = $(window).scrollTop();
        $('html').addClass('noscroll').css('top', '-' + curScrollTop + 'px');
        $('.navbar-fixed-top').css({'position':'absolute','top':curScrollTop});
        $(window).on("resize", function() {
            var bodyH = $("body").height();
            var winH = $(window).height();
            if (winH > bodyH) {
                prevScrollTop = curScrollTop;
                curScrollTop = 0;
                $('.navbar-fixed-top').css({'position':'absolute','top':'0'});
            }
            else {
                $('html').removeClass("noscroll");
                if (curScrollTop == 0) window.scrollTo(0, prevScrollTop);
                else window.scrollTo(0, curScrollTop);
                curScrollTop = $(window).scrollTop();
                $('.navbar-fixed-top').css({'position':'absolute','top':curScrollTop});
                $('html').addClass("noscroll");
            }
            $('html').css('top', '-' + curScrollTop + 'px');
        })
    })
    $('.modal').on('hide.bs.modal', function() {
        $('html').removeClass("noscroll");
         $('.navbar-fixed-top').css({'position':'fixed','top':'0'});
        window.scrollTo(0, curScrollTop);
        $(window).off("resize");
    })
})

This allows the background to be "fixed" yet still allows the modals to be scrollable, resolves the issue of double scrollbar and the repositioning of the fixed navbar.

Note that there is additional code there as well to remember the 'scroll' position (and return to it) when the modal is closed.

Hope this helps anyone else looking to achieve what I was going after.


问:
when a JRadioButton is clicked it will not print out correct
i am trying to make a code that when pressed by he user it will print out correct but instead of printing out correct it just does nothing. i have researched this topic very clearly but i cannot seem to find the right answer if any body can help me it will be greatly appreciated</p>

```<code>import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JOptionPane;

public class JRadioButtonTest
{

  public static void main(String[] args)
  {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JRadioButton Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JRadioButton button1 = new JRadioButton("0.4");
    JRadioButton button2 = new JRadioButton("12");
    JRadioButton button3 = new JRadioButton("37");

    ButtonGroup colorButtonGroup = new ButtonGroup();
    colorButtonGroup.add(button1);
    colorButtonGroup.add(button2);
    colorButtonGroup.add(button3);

    frame.add(new JLabel("what is the density of a piece of rock that is 40 grams and 25cm3"));
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.pack();
    frame.setVisible(true);

    if(button2.isSelected()){
      JOptionPane.showMessageDialog(null,"correct");
      }
    }
  }
</code>```

答:
In your code you check immediately the state of the radio buttons after you created them. Because of this, you have to press the radio button between the setVisible(true) call and the check, which is practically impossible.

What you are looking for are Listeners, these will be executed if specific events happen.
As example the ItemListener, which is most applicable to your example as it will be executed every time the value of the radio buttons change.

```<code>button2.addItemListener(new ItemListener()
{
 @Override
 public void itemStateChanged(ItemEvent e) {
   if (e.getStateChange() == ItemEvent.SELECTED) {
    // Your selected code here.
   }
   else if (e.getStateChange() == ItemEvent.DESELECTED) {
    // Your deselected code here.
   }
 }
}
</code>```

Happy coding!

Body:
i am trying to make a code that when pressed by he user it will print out correct but instead of printing out correct it just does nothing. i have researched this topic very clearly but i cannot seem to find the right answer if any body can help me it will be greatly appreciated

import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JOptionPane;

public class JRadioButtonTest
{

  public static void main(String[] args)
  {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JRadioButton Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JRadioButton button1 = new JRadioButton("0.4");
    JRadioButton button2 = new JRadioButton("12");
    JRadioButton button3 = new JRadioButton("37");

    ButtonGroup colorButtonGroup = new ButtonGroup();
    colorButtonGroup.add(button1);
    colorButtonGroup.add(button2);
    colorButtonGroup.add(button3);

    frame.add(new JLabel("what is the density of a piece of rock that is 40 grams and 25cm3"));
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);
    frame.pack();
    frame.setVisible(true);

    if(button2.isSelected()){
      JOptionPane.showMessageDialog(null,"correct");
      }
    }
  }

Body:
In your code you check immediately the state of the radio buttons after you created them. Because of this, you have to press the radio button between the setVisible(true) call and the check, which is practically impossible.

What you are looking for are Listeners, these will be executed if specific events happen.
As example the ItemListener, which is most applicable to your example as it will be executed every time the value of the radio buttons change.

button2.addItemListener(new ItemListener()
{
 @Override
 public void itemStateChanged(ItemEvent e) {
   if (e.getStateChange() == ItemEvent.SELECTED) {
    // Your selected code here.
   }
   else if (e.getStateChange() == ItemEvent.DESELECTED) {
    // Your deselected code here.
   }
 }
}

Happy coding!


问:
Trying to use filter function on strings
i have the following function and I am trying to make a list containing the 'tweet numbers' of tweets done by DanClark . I am splitting the strings and trying to use the filter function to produce it. I am trying to avoid explicit recursion. i keep getting the following error " 'str' object is not callable" when i try to run "search_tweets(tweets, "DanClark")"</p>

```<code>tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

def separator(tweets, item1, item2, tweeter):

part1 = (tweets[item1].split('::'))
part2 = part1[item2]
part3 = part2[1:]

  if part3 == tweeter:
      return (part1[0])[1:]
  else:
      return []

def search_tweets(tweets, tweeter):
  return list(filter((separator(tweets, 0, 1, tweeter)), tweets))
</code>```

答:
```<code>tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets = [tweet1, tweet19, tweet50, tweet14, tweet15]

def numbers_of_tweets_done_by(who):
    r_list = []
    for tweet in tweets:
        t_info = tweet.split('::')
        if t_info[1] == who:
           r_list.append(int(t_info[0][1:]))
    return r_list

if __name__ == '__main__':
    print(numbers_of_tweets_done_by('@DanClark'))

#Prints [1,14]
</code>```

Body:
i have the following function and I am trying to make a list containing the 'tweet numbers' of tweets done by DanClark . I am splitting the strings and trying to use the filter function to produce it. I am trying to avoid explicit recursion. i keep getting the following error " 'str' object is not callable" when i try to run "search_tweets(tweets, "DanClark")"

tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

def separator(tweets, item1, item2, tweeter):

part1 = (tweets[item1].split('::'))
part2 = part1[item2]
part3 = part2[1:]

  if part3 == tweeter:
      return (part1[0])[1:]
  else:
      return []

def search_tweets(tweets, tweeter):
  return list(filter((separator(tweets, 0, 1, tweeter)), tweets))


问:
Processing - How to make 2 moving images collide?
I want to have the panda (which the user moves with left and right arrow keys) collide with a candy image which is falling from the top left of the screen. When the 2 images collide, it would say "YOU TOUCHED THE CANDY" on the screen and the console. But when the panda and candy touch, nothing happens.

Here is the code:

```<code>PImage candy, panda;

int pandaX = 800;
 int pandaY = 790;
 int candySpeed = 20;
 int yDirCandy = 1;
 int yPosCandy = 10;
 int xPosCandy = 20;

 void setup() {
 candy = loadImage("goodCandy1.png");
 panda = loadImage("panda.png");
 }
 void loadStuff() {
   image(panda, pandaX, pandaY, 80, 112);
   text("Lives: " + lives, 1400, 70);
   image(candy, xPosCandy, yPosCandy, 187, 121);
   yPosCandy = yPosCandy + (candySpeed * yDirCandy);
   touchCandy(pandaX, pandaY, yPosCandy, xPosCandy);
 }
 void keyPressed() {
   if (key==CODED) {
     if (keyCode==LEFT) {
       pandaX = pandaX-20;
     }
     if (keyCode==RIGHT) {
       pandaX = pandaX+20;
     }
    if (pandaX<=10) {
      pandaX=10;
      lives = lives -1;
    }
    if (pandaX>=1500) {
      pandaX=1500;
    }
   }

 }

 void touchCandy(int xPosCandy, int yPosCandy, int pandaX, int pandaY) {
   if (pandaX==xPosCandy && pandaY==yPosCandy ) {
     text("YOU TOUCHED THE CANDY!", width/2, height/2);
     print("YOU TOUCHED THE CANDY!");
   }

 }
</code>```

I tried doing  if (pandaX==xPosCandy && pandaY==yPosCandy) But it didn't work. I also tried doing if (pandaX>xPosCandy && pandaY<yPosCandy) but it says YOU TOUCHED THE CANDY too soon.

Any help would be appreciated, and let me know if you need more code. Thanks!

答:
Look at this line:

```<code>if (pandaX==xPosCandy && pandaY==yPosCandy)
</code>```

This will only be true if the panda and the candy are in exactly the same position. This is pretty unlikely.

Similarly, look at this line:

```<code>if (pandaX>xPosCandy && pandaY<yPosCandy)
</code>```

This will only be true if the panda is to the right and above the candy, which is not what you want.

Instead, you need to check whether they're overlapping. You'd do this by checking each side, like this:

```<code>if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
   //collision
}
</code>```

Shameless self-promotion: I've written a tutorial on collision detection in Processing (including rectangle-rectangle collision) available here.

Body:
I want to have the panda (which the user moves with left and right arrow keys) collide with a candy image which is falling from the top left of the screen. When the 2 images collide, it would say "YOU TOUCHED THE CANDY" on the screen and the console. But when the panda and candy touch, nothing happens.

Here is the code:

PImage candy, panda;

int pandaX = 800;
 int pandaY = 790;
 int candySpeed = 20;
 int yDirCandy = 1;
 int yPosCandy = 10;
 int xPosCandy = 20;

 void setup() {
 candy = loadImage("goodCandy1.png");
 panda = loadImage("panda.png");
 }
 void loadStuff() {
   image(panda, pandaX, pandaY, 80, 112);
   text("Lives: " + lives, 1400, 70);
   image(candy, xPosCandy, yPosCandy, 187, 121);
   yPosCandy = yPosCandy + (candySpeed * yDirCandy);
   touchCandy(pandaX, pandaY, yPosCandy, xPosCandy);
 }
 void keyPressed() {
   if (key==CODED) {
     if (keyCode==LEFT) {
       pandaX = pandaX-20;
     }
     if (keyCode==RIGHT) {
       pandaX = pandaX+20;
     }
    if (pandaX<=10) {
      pandaX=10;
      lives = lives -1;
    }
    if (pandaX>=1500) {
      pandaX=1500;
    }
   }

 }

 void touchCandy(int xPosCandy, int yPosCandy, int pandaX, int pandaY) {
   if (pandaX==xPosCandy && pandaY==yPosCandy ) {
     text("YOU TOUCHED THE CANDY!", width/2, height/2);
     print("YOU TOUCHED THE CANDY!");
   }

 }

I tried doing  if (pandaX==xPosCandy && pandaY==yPosCandy) But it didn't work. I also tried doing if (pandaX>xPosCandy && pandaY<yPosCandy) but it says YOU TOUCHED THE CANDY too soon.

Any help would be appreciated, and let me know if you need more code. Thanks!

Body:
Look at this line:

if (pandaX==xPosCandy && pandaY==yPosCandy)

This will only be true if the panda and the candy are in exactly the same position. This is pretty unlikely.

Similarly, look at this line:

if (pandaX>xPosCandy && pandaY<yPosCandy)

This will only be true if the panda is to the right and above the candy, which is not what you want.

Instead, you need to check whether they're overlapping. You'd do this by checking each side, like this:

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
   //collision
}

Shameless self-promotion: I've written a tutorial on collision detection in Processing (including rectangle-rectangle collision) available here.


问:
Add TapRecognizer and different color to word inside a string in Xcode
I am pulling a text from a plist and draw it into a UIView.
The text contains terms that I want to be highlighted and user interaction enabled so I could pop a dictionary view with the teem explanation.

I know how to find their location on the string and that works fine.
But I did not find how to make them a appear in different color.
And even more important to me - how to add a tap recognizer to them.

I would appreciate any help.

Thanks
Shani

答: Add a transparent button with the same font and text in front of where the word appears in the UIView. I have a class that will do this with a UILabel if you'd like it? It creates the same effect as with the Facebook application.</p>

ContentLicense: CC BY-SA 2.5


问:
Arraylist user selector
Okay, so I am trying to make a simple secret Santa program, they type in their name, it then removes them from the arraylist, and randomizes the arraylist and outputs the text to a text box, or should I say, I need it to.

```<code>private void button1_Click(object sender, EventArgs e)
{
    ArrayList NameSel = new ArrayList();
    NameSel.Add("name1");
    NameSel.Add("name2");
    NameSel.Add("name3");;
    if (textBox1.Text == "name1")
    {
        NameSel.Remove("name1");
        Random rand = new Random();
        int randoms = rand.Next(NameSel.Count);
        string textbox = NameSel[randoms];
        textBox2.Text = textbox;
    }
</code>```

The problem lies at textbox, specifically "NameSel[randoms];".

Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

I don't work with arraylists at all, for this I usually a string, for example

```<code>string[] names = new string[]
{
     "name1",
     "name2",
     "name3",
};
</code>```

And I tested, and that works, but as far as I am aware, I cant use stringname.remove("name1") or any equivalent, so I am out of my comfort zone, Any help that doesn't massively edit the original code is appreciated!

答:
Don't use ArrayList!

An ArrayList could have anything in it. You want a generic List<string> instead. It works almost exactly the same, but will only let you put strings in it and therefore won't make you do casting.

Additionally, a much better and simpler method for assigning secret santa names is to shuffle the list once (and only once, so don't this as part of your existing method), and then assign everyone to the person who comes after them in the list (or before, if you prefer). Also assign the person at the end of the list to the person at the beginning. This ensures that everyone has exactly one person assigned to them, and everyone is assigned to someone.

Title: Arraylist user selector

Body:
Okay, so I am trying to make a simple secret Santa program, they type in their name, it then removes them from the arraylist, and randomizes the arraylist and outputs the text to a text box, or should I say, I need it to.

private void button1_Click(object sender, EventArgs e)
{
    ArrayList NameSel = new ArrayList();
    NameSel.Add("name1");
    NameSel.Add("name2");
    NameSel.Add("name3");;
    if (textBox1.Text == "name1")
    {
        NameSel.Remove("name1");
        Random rand = new Random();
        int randoms = rand.Next(NameSel.Count);
        string textbox = NameSel[randoms];
        textBox2.Text = textbox;
    }

The problem lies at textbox, specifically "NameSel[randoms];".

Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

I don't work with arraylists at all, for this I usually a string, for example

string[] names = new string[]
{
     "name1",
     "name2",
     "name3",
};

And I tested, and that works, but as far as I am aware, I cant use stringname.remove("name1") or any equivalent, so I am out of my comfort zone, Any help that doesn't massively edit the original code is appreciated!


问:
How to Delete data in Both Tables in SQL Server?
I have a table TableA, its PK is AId. I have another table TableB, its only column is BId. BId is actually is a subset of AId. Now, we can not use FK (because of this and that reason).

How can I Delete the TOP 1000 rows in TableB and its related rows (if the same id exists in table A) in table A?

A solution is to SELECT TOP 100) from tableB and save to temp table, then use it to delete the data in table A, then delete rows in tableB.

But it should have a more efficient way to do this.

I also tried:

```<code>DELETE TOP (1000) FROM tableA WHERE AId IN (SELECT BId FROM TableB)
</code>```

But how can I make sure the top 1000 BId got deleted?

Thanks

答:
In general, one DELETE statement can change data only in one table.
So, in general, you need two separate DELETE statements to delete rows from two tables.

Technically, you don't have to write BId to a temp table, just read them twice from TableB.

```<code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

BEGIN TRANSACTION;

DELETE FROM TableA
WHERE TableA.AId IN
(
    SELECT TOP(1000) TableB.BId
    FROM TableB
    ORDER BY TableB.BId
)
;

DELETE FROM TableB
WHERE TableB.BId IN
(
    SELECT TOP(1000) TableB.BId
    FROM TableB
    ORDER BY TableB.BId
)
;

COMMIT TRANSACTION;
</code>```

You need to make sure that the set of 1000 BId are the same in both queries, which means that you have to use ORDER BY with TOP. Also, you should do something to prevent changes to TableB by another process between two DELETE statements.

In the end, taking care of concurrency issues (for example, by setting the transaction isolation level to serializable) may incur more overhead than writing these 1000 Ids into a temp table.

On the other hand, you said "BId is actually is a subset of AId". So, TableA is master, TableB is detail.

Technically, you can define a Foreign Key with ON DELETE CASCADE option. It is not clear to me from the question why you can't use foreign key constraint.

```<code>ALTER TABLE TableB WITH CHECK ADD CONSTRAINT [FK_TableB_TableA] FOREIGN KEY(BId)
REFERENCES TableA(AId) ON DELETE CASCADE
GO

ALTER TABLE TableB CHECK CONSTRAINT [FK_TableB_TableA]
GO
</code>```

Then you will delete only from TableA and child rows from TableB would be deleted by the foreign key constraint. Whether that would be more efficient than two explicit DELETEs is hard to tell - you need to test yourself on your hardware.

In this case one explicit DELETE is enough:

```<code>DELETE FROM TableA
WHERE TableA.AId IN
(
    SELECT TOP(1000) TableB.BId
    FROM TableB
    ORDER BY TableB.BId
)
;
</code>```

This will take care of concurrency issues as well.

Body:
I have a table TableA, its PK is AId. I have another table TableB, its only column is BId. BId is actually is a subset of AId. Now, we can not use FK (because of this and that reason).

How can I Delete the TOP 1000 rows in TableB and its related rows (if the same id exists in table A) in table A?

A solution is to SELECT TOP 100) from tableB and save to temp table, then use it to delete the data in table A, then delete rows in tableB.

But it should have a more efficient way to do this.

I also tried:

DELETE TOP (1000) FROM tableA WHERE AId IN (SELECT BId FROM TableB)

But how can I make sure the top 1000 BId got deleted?

Thanks

Body:
In general, one DELETE statement can change data only in one table.
So, in general, you need two separate DELETE statements to delete rows from two tables.

Technically, you don't have to write BId to a temp table, just read them twice from TableB.

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

BEGIN TRANSACTION;

DELETE FROM TableA
WHERE TableA.AId IN
(
    SELECT TOP(1000) TableB.BId
    FROM TableB
    ORDER BY TableB.BId
)
;

DELETE FROM TableB
WHERE TableB.BId IN
(
    SELECT TOP(1000) TableB.BId
    FROM TableB
    ORDER BY TableB.BId
)
;

COMMIT TRANSACTION;

You need to make sure that the set of 1000 BId are the same in both queries, which means that you have to use ORDER BY with TOP. Also, you should do something to prevent changes to TableB by another process between two DELETE statements.

In the end, taking care of concurrency issues (for example, by setting the transaction isolation level to serializable) may incur more overhead than writing these 1000 Ids into a temp table.

On the other hand, you said "BId is actually is a subset of AId". So, TableA is master, TableB is detail.

Technically, you can define a Foreign Key with ON DELETE CASCADE option. It is not clear to me from the question why you can't use foreign key constraint.

ALTER TABLE TableB WITH CHECK ADD CONSTRAINT [FK_TableB_TableA] FOREIGN KEY(BId)
REFERENCES TableA(AId) ON DELETE CASCADE
GO

ALTER TABLE TableB CHECK CONSTRAINT [FK_TableB_TableA]
GO

Then you will delete only from TableA and child rows from TableB would be deleted by the foreign key constraint. Whether that would be more efficient than two explicit DELETEs is hard to tell - you need to test yourself on your hardware.

In this case one explicit DELETE is enough:

DELETE FROM TableA
WHERE TableA.AId IN
(
    SELECT TOP(1000) TableB.BId
    FROM TableB
    ORDER BY TableB.BId
)
;

This will take care of concurrency issues as well.


问:
SSIS- seq num genearion based on key in result set
Suppose in the OLEDB source query result, I have a result set like this:

```<code>Account Num   field1 field2 field3

1
1
2
3
4
</code>```

I want the output to be:

```<code>Account Num  SEQ NUM   field1 field2 field3
1              1
1              2
2              1
3              1
4              1
</code>```

By which transformation in SSIS can I get this output?

答:
You can alter your oledb source query and use ROW_NUMBER function to achieve this:

```<code>Select [Account Num],
    ROW_NUMBER() OVER(PARTITION BY  [Account Num] ORDER BY  [Account Num]) AS  [SEQ Num],
    Field1, Field2, Field3
  From SourceTable
</code>```

Body:
Suppose in the OLEDB source query result, I have a result set like this:

Account Num   field1 field2 field3

1
1
2
3
4

I want the output to be:

Account Num  SEQ NUM   field1 field2 field3
1              1
1              2
2              1
3              1
4              1

By which transformation in SSIS can I get this output?

Body:
You can alter your oledb source query and use ROW_NUMBER function to achieve this:

Select [Account Num],
    ROW_NUMBER() OVER(PARTITION BY  [Account Num] ORDER BY  [Account Num]) AS  [SEQ Num],
    Field1, Field2, Field3
  From SourceTable


问:
Get the value in the intermediate model in a Through Relationship
As I loop through a Prize.objects.all() set, I am trying to get the quantity value from PrizeItem, but it seems to reference only the GameItem model, not giving access to the intermediate PrizeItem attributes.

How do I get access to the Through model's attributes?

MODELS:

```<code>class GameItem(models.Model):
    '...'

class Prize(models.Model):
    '...'

    item            = models.ManyToManyField(GameItem, through='PrizeItem')

class PrizeItem(models.Model):
    #relations
    game_item        = models.ForeignKey(GameItem, on_delete=models.CASCADE)
    prize            = models.ForeignKey(Prize, on_delete=models.CASCADE)
    #Item details
    quantity         = models.IntegerField(null=True, blank=True, default=1)
</code>```

VIEWS:

```<code>def gameprizes(request):
    prizes=Prize.objects.all()
    context={'prizes':prizes}
    return render(request, "the-app/game-prizes.html", context)
</code>```

TEMPLATE:

```<code>{% if prize.item.all %}
<table class="table table-condensed">
    <tbody>
    {% for prize_item in prize.item.all %}
        <tr>
           <td>{{ prize_item.type }}</td><td>{{ prize_item.name }} {{ prize_item.quantity }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
{% endif %}
</code>```

答:
It gets a little ugly when it comes to intermediate models in querysets. One way you can address this would be:

```<code>class Prize(models.Model):
    '...'

    item            = models.ManyToManyField(GameItem, through='PrizeItem')

    def quantity(self):
        return self.item.quantity
</code>```

Note that this does lead to additional queries, and you can use prefetch_related in your query to optimize

Another option would be to use the template

For game item, you would be doing something like:

```<code>class GameItem(models.Model):
    '...'

    def quantity(self):
        return self.prizeitem_set.first()
</code>```

Body:
As I loop through a Prize.objects.all() set, I am trying to get the quantity value from PrizeItem, but it seems to reference only the GameItem model, not giving access to the intermediate PrizeItem attributes.

How do I get access to the Through model's attributes?

MODELS:

class GameItem(models.Model):
    '...'

class Prize(models.Model):
    '...'

    item            = models.ManyToManyField(GameItem, through='PrizeItem')

class PrizeItem(models.Model):
    #relations
    game_item        = models.ForeignKey(GameItem, on_delete=models.CASCADE)
    prize            = models.ForeignKey(Prize, on_delete=models.CASCADE)
    #Item details
    quantity         = models.IntegerField(null=True, blank=True, default=1)

VIEWS:

def gameprizes(request):
    prizes=Prize.objects.all()
    context={'prizes':prizes}
    return render(request, "the-app/game-prizes.html", context)

TEMPLATE:

{% if prize.item.all %}

    {% for prize_item in prize.item.all %}

           {{ prize_item.type }}	{{ prize_item.name }} {{ prize_item.quantity }}

    {% endfor %}

{% endif %}

Body:
It gets a little ugly when it comes to intermediate models in querysets. One way you can address this would be:

class Prize(models.Model):
    '...'

    item            = models.ManyToManyField(GameItem, through='PrizeItem')

    def quantity(self):
        return self.item.quantity

Note that this does lead to additional queries, and you can use prefetch_related in your query to optimize

Another option would be to use the template

For game item, you would be doing something like:

class GameItem(models.Model):
    '...'

    def quantity(self):
        return self.prizeitem_set.first()


问:
Is it possible to import data from csv files into Teradata table?
Looking for importing data from csv/json files to Teradata, can we do it with Python code?</p>

答:
Judging from some of the resources I found online it does see possible. Just use the csv and json libraries built into python to parse your input:

https://docs.python.org/3.5/library/csv.html and https://docs.python.org/3.5/library/json.html

Then use this python module I found under Teradata's site to insert your data via session.executes:
https://developer.teradata.com/tools/reference/teradata-python-module

Looking at some of their examples, this seems really similar to standard Database statements. You may also be able add data using pyodbc but I am unsure.
https://github.com/mkleehammer/pyodbc/wiki

pyodbc can be installed via pip.


问:
AWS cannot signed CloudFront urls
Excepted: I want to get signed urls with my AWS CloudFront url.

What I have done: I have created a AWS CloudFront instence and enabled Restrict Viewer Access function, Trusted Signers is Self.

Below is the php code I want to sign the url

```<code>function getSignedURL()
{
    $resource = 'http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp';
    $timeout = 300;

    //This comes from key pair you generated for cloudfront
    $keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

    $expires = time() + $timeout; //Time out in seconds
    $json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

    //Read Cloudfront Private Key Pair
    $fp=fopen("private_key.pem","r");
    $priv_key=fread($fp,8192);
    fclose($fp);

    //Create the private key
    $key = openssl_get_privatekey($priv_key);
    if(!$key)
    {
            echo "<p>Failed to load private key!</p>";
            return;
    }

    //Sign the policy with the private key
    if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
    {
            echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
            return;
    }

    //Create url safe signed policy
    $base64_signed_policy = base64_encode($signed_policy);
    $signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

    //Construct the URL
    $url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

    return $url;
}
</code>```

For $keyPairId and private_key.pem, I logged in my root account and generated this two variables in Security Credentials->CloudFront Key Pairs section.

If I access http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp on browser directly. It will response like

```<code><Error>
  <Code>MissingKey</Code>
  <Message>
    Missing Key-Pair-Id query parameter or cookie value
  </Message>
</Error>
</code>```

After I run the function, I got a long signed url, parse the url on chrome browser, it will response like

```<code><Error>
  <Code>InvalidKey</Code>
  <Message>Unknown Key</Message>
</Error>
</code>```

Question: I have search AWS document and google much time about this, Could anyone tell me why this happened or if I miss something? Thanks in advance!

答:
$priv_key=fread($fp,8192);

If I understand, you generated the key.  If so, it looks like you are setting a key size that is not supported.

The key pair must be an SSH-2 RSA key pair.

The key pair must be in base64 encoded PEM format.

The supported key lengths are 1024, 2048, and 4096 bit

Docs: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html#private-content-creating-cloudfront-key-pairs

Title: AWS cannot signed CloudFront urls

Body:
Excepted: I want to get signed urls with my AWS CloudFront url.

What I have done: I have created a AWS CloudFront instence and enabled Restrict Viewer Access function, Trusted Signers is Self.

Below is the php code I want to sign the url

function getSignedURL()
{
    $resource = 'http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp';
    $timeout = 300;

    //This comes from key pair you generated for cloudfront
    $keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

    $expires = time() + $timeout; //Time out in seconds
    $json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

    //Read Cloudfront Private Key Pair
    $fp=fopen("private_key.pem","r");
    $priv_key=fread($fp,8192);
    fclose($fp);

    //Create the private key
    $key = openssl_get_privatekey($priv_key);
    if(!$key)
    {
            echo "
Failed to load private key!
";
            return;
    }

    //Sign the policy with the private key
    if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
    {
            echo '
Failed to sign policy: '.openssl_error_string().'
';
            return;
    }

    //Create url safe signed policy
    $base64_signed_policy = base64_encode($signed_policy);
    $signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

    //Construct the URL
    $url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

    return $url;
}

For $keyPairId and private_key.pem, I logged in my root account and generated this two variables in Security Credentials->CloudFront Key Pairs section.

If I access http://d2qui8qg6d31zk.cloudfront.net/richardcuicks3sample/140-140.bmp on browser directly. It will response like

<Error>
  MissingKey
  <Message>
    Missing Key-Pair-Id query parameter or cookie value
  </Message>
</Error>

After I run the function, I got a long signed url, parse the url on chrome browser, it will response like

<Error>
  InvalidKey
  <Message>Unknown Key</Message>
</Error>

Question: I have search AWS document and google much time about this, Could anyone tell me why this happened or if I miss something? Thanks in advance!


问:
Determining if a squence is true
How would I determine if a sequence is true?
Lets say I have this code

```<code>int a = random.nextInt(10);
int b = random.nextInt(10);
int c = random.nextInt(10);
</code>```

How would I use an if statement or a loop to determine if/when a = 1, b = 2, and c = 3 (or any combination of a,b, and c being only one number apart. Like 4,5,6 or 7,8,9) is in a sequence such as stated?

答:
I think it should be like,</p>

```<code>public static boolean checker() {
    // you can do this without worrying about overflow
    // because nextInt method generates a number btw 0(inclusive) and 10(exclusive)
    return (b-a == 1 && c-b == 1) || (b-a == -1 && c-b == -1);
    //            1, 2, 3         or          3, 2, 1
}
</code>```

Title: Determining if a squence is true

Body:
How would I determine if a sequence is true?
Lets say I have this code

int a = random.nextInt(10);
int b = random.nextInt(10);
int c = random.nextInt(10);

How would I use an if statement or a loop to determine if/when a = 1, b = 2, and c = 3 (or any combination of a,b, and c being only one number apart. Like 4,5,6 or 7,8,9) is in a sequence such as stated?

Body:
I think it should be like,

public static boolean checker() {
    // you can do this without worrying about overflow
    // because nextInt method generates a number btw 0(inclusive) and 10(exclusive)
    return (b-a == 1 && c-b == 1) || (b-a == -1 && c-b == -1);
    //            1, 2, 3         or          3, 2, 1
}


问:
using ESI slower than EAX?
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

```<code>jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1
</code>```

```<code>jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1
</code>```

答: A small effect is also that in some cases instructions using AX/EAX may be shorter.  Not as big a deal as it was WAAAY back in the 8088 day when (due to the 8-bit data bus and slow memory access) the processor wasted a LOT of time just trying to fill the pipeline to run the next instruction.</p>

Title: using ESI slower than EAX?

Body:
This piece of asm is much slower than the corresponding piece using the eax register. Why is that?

jmp .l2
.l1:

   dec ESI
.l2:
   cmp ESI, 0
   jne .l1

jmp .l2
.l1:

   dec EAX
.l2:
   cmp EAX, 0
   jne .l1


问:
Reference list object by a variable is different than for (some) other objects?
In defining variable of a list object, for example:

```<code>x = [1,2,0.2,3,4]
y = x
x.sort()
</code>```

I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

On the other hand, another example :

```<code>x = 5
y = x
x = 4
</code>```

from this the value of y is still 5, it does not change as x change.

My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

答:
Every variable is just a pointer to an Python object, if you have two variables pointing to the same object then you'll see the changes in each of them (and .sort works in-place, if you want a new list you should use x = sorted(x)). However if you re-assign a variable then it will point to a different object.

I included some images to better visualize what's happening (not high-quality but I hope it conveys the message).

```<code>x = [1,2,0.2,3,4]
y = x
</code>```

If you copy (it's a shallow copy so the list-contents still refer to the same items!):

```<code>x = [1,2,0.2,3,4]
y = x.copy()
</code>```

Your second case is just the same:

```<code>x = 5
y = x
</code>```

But then you re-assign the variable x (so it points to another object thereafter):

```<code>x = 4
</code>```

Body:
In defining variable of a list object, for example:

x = [1,2,0.2,3,4]
y = x
x.sort()

I would expect that y is still equal to [1, 2, 0.2, 3, 4], but it does not. The value of y changed as x changed. To counter this, I found that using y = x.copy() can preserve the value in the first line.

On the other hand, another example :

x = 5
y = x
x = 4

from this the value of y is still 5, it does not change as x change.

My question : is this due to the design in list's class, or there is another explanation? I found the dynamic change also happen when using x.append(value). Any insight is appreciated. Regards, Arief

Body:
Every variable is just a pointer to an Python object, if you have two variables pointing to the same object then you'll see the changes in each of them (and .sort works in-place, if you want a new list you should use x = sorted(x)). However if you re-assign a variable then it will point to a different object.

I included some images to better visualize what's happening (not high-quality but I hope it conveys the message).

x = [1,2,0.2,3,4]
y = x

If you copy (it's a shallow copy so the list-contents still refer to the same items!):

x = [1,2,0.2,3,4]
y = x.copy()

Your second case is just the same:

x = 5
y = x

But then you re-assign the variable x (so it points to another object thereafter):

x = 4


问:
Change ng-bootstrap buttons activeClass?
In out AngularJs app, we changed the activeClass of buttons (as in toggle groups) to btn-default (from the default btn-primary), so all our CSS expects that.

I notice that ng-bootstrap also defaults to btn-primary but I don't see how (or if) that can be changed.

Is it possible for me to change the activeClass so my CSS is correct with the new components?

答:
First of all, which version of angular are you using?
there's quite difference between ng versions

ng-1 angularjs.org - docs

```<code><button ng-class="{'class1 class2 class3' : true}">
    it's a button
</button>
</code>```

ng-2/4 angular.io - docs

```<code><button [ngClass]="{'class1 class2 class3' : true}">
    it's a button
</button>
</code>```

Body:
First of all, which version of angular are you using?
there's quite difference between ng versions

ng-1 angularjs.org - docs

<button ng-class="{'class1 class2 class3' : true}">
    it's a button
</button>

ng-2/4 angular.io - docs

<button [ngClass]="{'class1 class2 class3' : true}">
    it's a button
</button>


问:
Why do we always prefer using parameters in SQL statements?
I am very new to working with databases. Now I can write SELECT, UPDATE, DELETE, and INSERT commands. But I have seen many forums where we prefer to write:

```<code>SELECT empSalary from employee where salary = @salary
</code>```

...instead of:

```<code>SELECT empSalary from employee where salary = txtSalary.Text
</code>```

Why do we always prefer to use parameters and how would I use them?

I wanted to know the use and benefits of the first method. I have even heard of SQL injection but I don't fully understand it. I don't even know if SQL injection is related to my question.

答:
Old post but wanted to ensure newcomers are aware of Stored procedures.

My 10¢ worth here is that if you are able to write your SQL statement as a stored procedure, that in my view is the optimum approach.  I ALWAYS use stored procs and never loop through records in my main code.  For Example: SQL Table > SQL Stored Procedures > IIS/Dot.NET > Class.

When you use stored procedures, you can restrict the user to EXECUTE permission only, thus reducing security risks.

Your stored procedure is inherently paramerised, and you can specify input and output parameters.

The stored procedure (if it returns data via SELECT statement) can be accessed and read in the exact same way as you would a regular SELECT statement in your code.

It also runs faster as it is compiled on the SQL Server.

Did I also mention you can do multiple steps, e.g. update a table, check values on another DB server, and then once finally finished, return data to the client, all on the same server, and no interaction with the client.  So this is MUCH faster than coding this logic in your code.

Body:
I am very new to working with databases. Now I can write SELECT, UPDATE, DELETE, and INSERT commands. But I have seen many forums where we prefer to write:

SELECT empSalary from employee where salary = @salary

...instead of:

SELECT empSalary from employee where salary = txtSalary.Text

Why do we always prefer to use parameters and how would I use them?

I wanted to know the use and benefits of the first method. I have even heard of SQL injection but I don't fully understand it. I don't even know if SQL injection is related to my question.

ContentLicense: CC BY-SA 4.0


问:
Slicing pandas dtype object from end not working
I have a dataframe:

where series_id is a dtype object. When I run:

```<code>df['dataType'] = df['series_id'].apply(lambda x: x[-1:])
</code>```

Nothing happens, but when I run:

```<code> df['dataType'] = df['series_id'].apply(lambda x: x[19:20])
</code>```

It creates the correct dataType column.

Any ideas why I can't slice from the end of the object, but from the beginning it works?

答:
If you just need the last char of series_id, you can just convert it to str and take the last char from the string. Adding strip to make sure the trailing spaces are removed.</p>

```<code>df['dataType'] = df.series_id.str.strip().str[-1]
</code>```

Body:
I have a dataframe:

where series_id is a dtype object. When I run:

df['dataType'] = df['series_id'].apply(lambda x: x[-1:])

Nothing happens, but when I run:

 df['dataType'] = df['series_id'].apply(lambda x: x[19:20])

It creates the correct dataType column.

Any ideas why I can't slice from the end of the object, but from the beginning it works?

Body:
If you just need the last char of series_id, you can just convert it to str and take the last char from the string. Adding strip to make sure the trailing spaces are removed.

df['dataType'] = df.series_id.str.strip().str[-1]


问:
Why don't Django admin "Today" and "Now" buttons show up in Safari?
I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:

alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png

This is as expected. However, when I deploy to my webserver and use the application from there, I get this:

alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png

The application on the server is exactly the same as my local copy, except that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?

Update

The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).

I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget:

RelatedObjectLookup.js

DateTimeShortcuts.js

icon_calendar.gif

icon_clock.gif

答:
It seems like you have admin media missing (hence js and images aren't loading). I generally do following.

in settings.py

```<code>ADMIN_MEDIA_PREFIX = '/media/admin/'
</code>```

Then I symlink path of django.contrib.admin.media within my media dir. Say:

```<code>ln -s /var/lib/python-support/python2.5/django/contrib/admin/media/ /var/www/media/admin
</code>```

Development server serves admin media automatically. But on production servers one generally prefers to server static stuff directly from apache (or whatever server).

OwnerDisplayName: mipadi

LastEditorDisplayName: mipadi

Body:
It seems like you have admin media missing (hence js and images aren't loading). I generally do following.

in settings.py

ADMIN_MEDIA_PREFIX = '/media/admin/'

Then I symlink path of django.contrib.admin.media within my media dir. Say:

ln -s /var/lib/python-support/python2.5/django/contrib/admin/media/ /var/www/media/admin

Development server serves admin media automatically. But on production servers one generally prefers to server static stuff directly from apache (or whatever server).

OwnerDisplayName: muhuk


问:
Pure Redux VS ngrx with Angular
What are the pro and cons of using either pure Redux or ngrx with Angular2/4?

I have been using both in differenet projects but am still wondering which one is the most efficient and fastest.

答:
ngrx/store was created specifically for Angular2.
The detailed reasons can be found here:

https://github.com/ngrx/store/issues/16

Title: Pure Redux VS ngrx with Angular


问:
Why a timezone aware datetime's tzinfo does not equal the timezone?
```<code>>>> import pytz
>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False
</code>```

What's the reason for these to differ?

```<code>>>> dt_aware.tzinfo
<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>
>>> tz
<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>
</code>```

答:
The first one has been adjusted to the date and time provided, 2016-06-06T00:00:00.  Central Daylight Time (CDT) is in effect at this time.  It is 5 hours behind UTC (24:00 - 05:00 = 19:00).

The second one has not been localized, so it is giving you the first offset in the available time zone data, which happens to be the Local Mean Time (LMT) entry.  You can see this in the tzdata sources here.  The LMT is 5 hours, 50 minutes, and 36 seconds behind UTC.  The seconds of the LMT offset are rounded off somewhere in pytz, so 18:09 is reflecting this correctly (24:00 - 05:51 = 18:09)

Body:
>>> import pytz
>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False

What's the reason for these to differ?

>>> dt_aware.tzinfo
<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>
>>> tz
<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>


问:
Permanently storing key-value pairs efficiently
I'm working on an application which requires read/write access to key-value pairs (strings) currently saved in a CSV file. At the moment I'm creating hash maps from the file and overwriting when adding new entries but this is leading to a plethora of problems down the line. What's the best way to store and update this data?

Only need to store string pairs

Relatively few entries (<100)

Must be able to update data

答: Use a java.util.Properties file.

Body: Use a java.util.Properties file.


问:
Using jq parse a json output to get specific properties as a new json output
I am very new to jq, I am trying to parse an output json I get from  command -

```<code>aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE
</code>```

to get a new output where values of the key matches to certain pattern.

for example this is my json output from previous command -

```<code>{
  "StackSummaries": [
    {
      "StackId": "arn:aws:213dqwqwdqwdqwdq",
      "StackName": "monkeyman",
      "CreationTime": "2017-06-06T20:52:59.728Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "Liaison API ELB cloud formation script"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "monkeyman2",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "yoohooo instance"
    },
    {
      "StackId": "arn:aws:sdffgds444fsdfsdfgdfgfdg",
      "StackName": "starfish2",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "helloworld instance"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "bulldog4",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "night night instance"
    },
    {
      "StackId": "arn:aws:yhyhyhyhyhysdfgdfgfdg",
      "StackName": "carrotman",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "surprise mo instance"
    }

  ]

}
</code>```

Here I need to create a new output json by piping the first output to jq where StackName startsWith monkeyman and bulldog and which should look like -

```<code>{
  "StackSummaries": [
    {
      "StackId": "arn:aws:213dqwqwdqwdqwdq",
      "StackName": "monkeyman",
      "CreationTime": "2017-06-06T20:52:59.728Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "Liaison API ELB cloud formation script"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "monkeyman2",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "yoohooo instance"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "bulldog4",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "night night instance"
    }

  ]

}
</code>```

I have tried a lot, I was able to do it somehow using basic unix split and regex commands but something tells me it would be easier and less cumbersome to do directly with jq.

答:
It is easy with jq

```<code>jq '.[] |= map(select(.StackName | startswith("monkeyman"), startswith("bulldog")))'
</code>```

In a nutshell, map(x) applies x to every object that is fed to it. select(y) selects the objects that meet the condition y. In this case, condition y is that there is a key called StackName whose value starts with either "monkeyman" or "bulldog".

Body:
I am very new to jq, I am trying to parse an output json I get from  command -

aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE

to get a new output where values of the key matches to certain pattern.

for example this is my json output from previous command -

{
  "StackSummaries": [
    {
      "StackId": "arn:aws:213dqwqwdqwdqwdq",
      "StackName": "monkeyman",
      "CreationTime": "2017-06-06T20:52:59.728Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "Liaison API ELB cloud formation script"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "monkeyman2",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "yoohooo instance"
    },
    {
      "StackId": "arn:aws:sdffgds444fsdfsdfgdfgfdg",
      "StackName": "starfish2",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "helloworld instance"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "bulldog4",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "night night instance"
    },
    {
      "StackId": "arn:aws:yhyhyhyhyhysdfgdfgfdg",
      "StackName": "carrotman",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "surprise mo instance"
    }

  ]

}

Here I need to create a new output json by piping the first output to jq where StackName startsWith monkeyman and bulldog and which should look like -

{
  "StackSummaries": [
    {
      "StackId": "arn:aws:213dqwqwdqwdqwdq",
      "StackName": "monkeyman",
      "CreationTime": "2017-06-06T20:52:59.728Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "Liaison API ELB cloud formation script"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "monkeyman2",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "yoohooo instance"
    },
    {
      "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg",
      "StackName": "bulldog4",
      "CreationTime": "2017-06-06T20:51:55.191Z",
      "StackStatus": "CREATE_COMPLETE",
      "TemplateDescription": "night night instance"
    }

  ]

}

I have tried a lot, I was able to do it somehow using basic unix split and regex commands but something tells me it would be easier and less cumbersome to do directly with jq.

Body:
It is easy with jq

jq '.[] |= map(select(.StackName | startswith("monkeyman"), startswith("bulldog")))'

In a nutshell, map(x) applies x to every object that is fed to it. select(y) selects the objects that meet the condition y. In this case, condition y is that there is a key called StackName whose value starts with either "monkeyman" or "bulldog".


问:
ElasticSearch & Nest - Wrong convertion
I have this pure call to Elastic that works. It returns 29 docs:

```<code>GET /idxsearch-test/movies/_search
{
  "size": 20,
  "query": {
    "bool": {
            "must": {
                "bool" : {
                  "should": [
                                {"term": {"tag.name": "Paris"}},
                                {"multi_match" : {
                                  "operator":   "and",
                                    "query" : "Paris",
                                    "fields": ["movie_title.default^10",
                                    "movie_title.snowball^2",
                                    "movie_title.shingles^2",
                                    "movie_title.ngrams"]}}
                            ]
                }
            },
            "filter": {
              "term": { "is_adult": false }
            }
        }
  },
  "_source": ["id_content", "movie_title", "vote_average", "tag.name", "is_adult"]
}
</code>```

I need to use Nest, so I converted to this. It returns 0:

```<code>        var vod = client.Search<dynamic>(s => s
                            .Size(10)
                            .From(1)
                            .Index(defaultIndex)
                            .Type("movies")
                            .Query(qry1 => qry1
                                            .FunctionScore(fs =>
                                                    fs.Query(qry2 =>
                                                                qry2.Bool(bool1 =>
                                                                            bool1.Must(must1 =>
                                                                                must1.Bool(bool2 =>
                                                                                bool2.Should(should1 =>
                                                                                {
                                                                                QueryContainer qc = null;
                                                                                qc &= should1.Term(tt => tt.Field("tag.name").Value(keywords));
                                                                                qc &= should1.MultiMatch(mm1 => mm1.Fields(ff => ff
                                                                                .Field("movie_title.default^10")
                                                                                .Field("movie_title.snowball^2")
                                                                                .Field("movie_title.shingles^2")
                                                                                .Field("movie_title.ngrams"))
                                                                                .Operator(Operator.And)
                                                                                .Query(keywords));

                                                                                return qc;
                                                                                })
                                                                                )
                                                                                )
                                                                            .Filter(fil =>
                                                                            {
                                                                                QueryContainer query = null;
                                                                                if (!includeAdult)
                                                                                query &= fil.Terms(fil2 => fil2.Field("is_adult").Terms(false));

                                                                                return query;
                                                                            })
                                                                        )
                                                           )
                                            .BoostMode(FunctionBoostMode.Sum)
                                            .Functions(ff => ff.FieldValueFactor(fv => fv.Field("vote_average")
                                                                                .Factor(0.5)
                                                                                .Modifier(FieldValueFactorModifier.Log1P)))
                            ))
                );
</code>```

But the results are different... What am I missing?

Is there a way to make the same call in a cleaner and correct way?

cheers

答:
The first query can be written as </p>

```<code>//Fluent
            client.Search<dynamic>(
                s => s.
                Index("idxsearch-test").
                Type("movies").
                Take(20).
                Query(q => q.Bool(
                              b => b.Must(m => m.Term(t => t.Field("tag.name").Value("Paris")) ||
                                              m.MultiMatch(mm => mm.Fields(f => f.
                                                                              Field("movie_title.default", 10).
                                                                              Field("movie_title.snowball", 2).
                                                                              Field("movie_title.shingles", 2).
                                                                              Field("movie_title.ngrams")))).
                                      Filter(f => includeAdult ? f.Term(t => t.Field("is_adult").Value("")) : null))).
                 Source(sc => sc.Includes(i => i.Field("id_content").Field("movie_title").Field("vote_average").Field("tag.name").Field("is_adult"))));

            //Object
            client.Search<dynamic>(new SearchRequest<dynamic>("idxsearch-test", "movies")
            {
                Size = 20,
                Query = new BoolQuery
                {
                    Must = new QueryContainer[]
                    {
                        new BoolQuery
                        {
                            Should = new QueryContainer[]
                            {
                                new TermQuery() { Field = "tag.name", Value = "Paris" },
                                new MultiMatchQuery
                                {
                                    Fields = new [] { "movie_title.default^10", "movie_title.snowball^2", "movie_title.shingles^2", "movie_title.ngrams" }
                                }
                            }
                        }
                    },
                    Filter = includeAdult ? new QueryContainer[]
                    {
                        new TermQuery { Field = "is_adult", Value = false }
                    } : null
                },
                Source = new Union<bool, ISourceFilter>(new SourceFilter { Includes = new[] { "id_content", "movie_title", "vote_average", "tag.name", "is_adult" } })
            });
</code>```

Title: ElasticSearch & Nest - Wrong convertion

Body:
I have this pure call to Elastic that works. It returns 29 docs:

GET /idxsearch-test/movies/_search
{
  "size": 20,
  "query": {
    "bool": {
            "must": {
                "bool" : {
                  "should": [
                                {"term": {"tag.name": "Paris"}},
                                {"multi_match" : {
                                  "operator":   "and",
                                    "query" : "Paris",
                                    "fields": ["movie_title.default^10",
                                    "movie_title.snowball^2",
                                    "movie_title.shingles^2",
                                    "movie_title.ngrams"]}}
                            ]
                }
            },
            "filter": {
              "term": { "is_adult": false }
            }
        }
  },
  "_source": ["id_content", "movie_title", "vote_average", "tag.name", "is_adult"]
}

I need to use Nest, so I converted to this. It returns 0:

        var vod = client.Search<dynamic>(s => s
                            .Size(10)
                            .From(1)
                            .Index(defaultIndex)
                            .Type("movies")
                            .Query(qry1 => qry1
                                            .FunctionScore(fs =>
                                                    fs.Query(qry2 =>
                                                                qry2.Bool(bool1 =>
                                                                            bool1.Must(must1 =>
                                                                                must1.Bool(bool2 =>
                                                                                bool2.Should(should1 =>
                                                                                {
                                                                                QueryContainer qc = null;
                                                                                qc &= should1.Term(tt => tt.Field("tag.name").Value(keywords));
                                                                                qc &= should1.MultiMatch(mm1 => mm1.Fields(ff => ff
                                                                                .Field("movie_title.default^10")
                                                                                .Field("movie_title.snowball^2")
                                                                                .Field("movie_title.shingles^2")
                                                                                .Field("movie_title.ngrams"))
                                                                                .Operator(Operator.And)
                                                                                .Query(keywords));

                                                                                return qc;
                                                                                })
                                                                                )
                                                                                )
                                                                            .Filter(fil =>
                                                                            {
                                                                                QueryContainer query = null;
                                                                                if (!includeAdult)
                                                                                query &= fil.Terms(fil2 => fil2.Field("is_adult").Terms(false));

                                                                                return query;
                                                                            })
                                                                        )
                                                           )
                                            .BoostMode(FunctionBoostMode.Sum)
                                            .Functions(ff => ff.FieldValueFactor(fv => fv.Field("vote_average")
                                                                                .Factor(0.5)
                                                                                .Modifier(FieldValueFactorModifier.Log1P)))
                            ))
                );

But the results are different... What am I missing?

Is there a way to make the same call in a cleaner and correct way?

cheers

Body:
The first query can be written as

//Fluent
            client.Search<dynamic>(
                s => s.
                Index("idxsearch-test").
                Type("movies").
                Take(20).
                Query(q => q.Bool(
                              b => b.Must(m => m.Term(t => t.Field("tag.name").Value("Paris")) ||
                                              m.MultiMatch(mm => mm.Fields(f => f.
                                                                              Field("movie_title.default", 10).
                                                                              Field("movie_title.snowball", 2).
                                                                              Field("movie_title.shingles", 2).
                                                                              Field("movie_title.ngrams")))).
                                      Filter(f => includeAdult ? f.Term(t => t.Field("is_adult").Value("")) : null))).
                 Source(sc => sc.Includes(i => i.Field("id_content").Field("movie_title").Field("vote_average").Field("tag.name").Field("is_adult"))));

            //Object
            client.Search<dynamic>(new SearchRequest<dynamic>("idxsearch-test", "movies")
            {
                Size = 20,
                Query = new BoolQuery
                {
                    Must = new QueryContainer[]
                    {
                        new BoolQuery
                        {
                            Should = new QueryContainer[]
                            {
                                new TermQuery() { Field = "tag.name", Value = "Paris" },
                                new MultiMatchQuery
                                {
                                    Fields = new [] { "movie_title.default^10", "movie_title.snowball^2", "movie_title.shingles^2", "movie_title.ngrams" }
                                }
                            }
                        }
                    },
                    Filter = includeAdult ? new QueryContainer[]
                    {
                        new TermQuery { Field = "is_adult", Value = false }
                    } : null
                },
                Source = new Union<bool, ISourceFilter>(new SourceFilter { Includes = new[] { "id_content", "movie_title", "vote_average", "tag.name", "is_adult" } })
            });