答:
You can extract the keys by getting the unique key names from objects in the input array that aren't sno, then use a reducer to change the data form.

var obj = [
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]

const getSeries = obj => {
    const emptyResult = getSeriesNames(obj).map(seriesName => ({
      seriesName,
      data: []
    }));

    return obj.reduce((result, item) => {
        const series = result.filter(series => series.seriesName in item)[0]
        series.data.push({ value: item[series.seriesName] });
        return result;
    }, emptyResult);
}

const getSeriesNames = obj => obj.reduce((names, item) => {
    Object.keys(item)
    .filter(key => key !== 'sno')
    .forEach(key => {
        if (!names.includes(key)) {
            names.push(key);
        }
    });
    return names;
}, []);

console.log(getSeries(obj));```

Title: Forming new object with array of objects

Body:
From the object 1, I am trying to form another object 2. I have written this below piece of code but I dono is this the right approach to achieve object 2.

var arr = [];
    object1.filter(function(value) {
                                return value.hasOwnProperty("This Year"); // Get only elements, which have such a key
                                    }).map(function(value) {
                                arr.push({value:value["This Year"]}); // Extract the values only
                                    });

Object 1

var obj=[
  {
    "sno": 1,
    "Last Year": 10000
  },
  {
    "sno": 2,
    "Last Year": 11500
  },
  {
    "sno": 3,
    "Last Year": 12500
  },
  {
    "sno": 4,
    "This Year": 25400
  },
  {
    "sno": 5,
    "Last Year": 15000
  },
  {
    "sno": 6,
    "This Year": 29800
  }
]

Object 2 - Desired Result

var dataset = [
        {
            "seriesname": "Last Year",
            "data": [
                {
                    "value": "10000"
                },
                {
                    "value": "11500"
                },
                {
                    "value": "12500"
                },
                {
                    "value": "15000"
                }
            ]
        },
        {
            "seriesname": "This Year",
            "data": [
                {
                    "value": "25400"
                },
                {
                    "value": "29800"
                }
            ]
        }
    ]

If anyone can help me with better approach. In my code I am hard coding the key name of object 1. Is it possible in any other way?


来源: stackexchange

问:
Google maps new version battery drain in offline mode
Since > 9 version of google maps services battery start draining hard in offline(or airplane) mode.

Gsm logs:

```<code>02-16 03:16:00.172 5795-13092/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1792900917#, com.google.android.gms(10007):UserLocationProducer, vrsn=10298000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1792900917#
02-16 03:16:00.184 5795-13092/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1253298855#, com.google.android.gms(10007):UserLocationProducer, vrsn=10298000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1253298855#
02-16 03:20:32.082 5795-25747/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1792900917#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-179290000#
02-16 03:20:32.084 5795-25747/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1253298855#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1253298855#
02-16 03:27:56.240 5795-25125/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1792900917#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1792900917#
02-16 03:27:56.247 5795-25125/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1253298855#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1253298855#
</code>```

Is it possible to suspend gsm services while there is no connection?

What is the class - AclManager?

Thanks

答:
Check this out:

Blockquote
  Since I hate spam and hate to be tracked for advertising by Google, I always opt out for all those things. In the last version of Google Maps for Android, there is a Location History option, that was off. Since Google Maps has the devilish behavior of trying to track you by launching itself when you don't open it yourself, it opens in the background and tries to save your location in their servers. That trigged a crazy loop because of my Location History off setting.

The only solution I found, at least if I want to keep using Google Maps, was to enable Location History. No more batery drains.

Google is copying the worst practices of Microsoft at the speed of light.

ContentLicense: CC BY-SA 3.0

Body:
Since > 9 version of google maps services battery start draining hard in offline(or airplane) mode.

Gsm logs:

02-16 03:16:00.172 5795-13092/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1792900917#, com.google.android.gms(10007):UserLocationProducer, vrsn=10298000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1792900917#
02-16 03:16:00.184 5795-13092/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1253298855#, com.google.android.gms(10007):UserLocationProducer, vrsn=10298000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1253298855#
02-16 03:20:32.082 5795-25747/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1792900917#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-179290000#
02-16 03:20:32.084 5795-25747/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1253298855#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1253298855#
02-16 03:27:56.240 5795-25125/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1792900917#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1792900917#
02-16 03:27:56.247 5795-25125/? W/ctxmgr: [AclManager]No 2 for (accnt=account#-1253298855#, com.google.android.gms(10007):UserLocationProducer, vrsn=10290000, 0, 3pPkg = null ,  3pMdlId = null). Was: 2 for 1, account#-1253298855#

Is it possible to suspend gsm services while there is no connection?

What is the class - AclManager?

Thanks


答:
My best guess:</p>

```<code>select Masterr.OrderId,
       sum(Masterr.Amount)
  from Masterr
 where Masterr.ItemQty = 3
   and exists(select *
                from Detail
                join TempMaster on TempMaster.ItemQty = Masterr.ItemQty
                join TempDetail on TempDetail.OrderId = TempMaster.OrderId
               where Detail.OrderId = Masterr.OrderId
                 and TempDetail.ItemId  = Detail.ItemId
                 and TempDetail.Qty     = Detail.Qty
                 and TempDetail.Price   = Detail.Price)
 group by Masterr.OrderId;
</code>```

Title: SQL Server - Master / Detail - get extract exact detail item match

Body:
I need help to extract the exact item match from two table. I want from Detail Table  all the order that exists in Temp Detail and Master and Temp Master itemQty are the same.

example: in this case I need the sum of master.Amount for all the order which ItemQty is 3 and the detail table has the exact same value of temp Detail.

Master

OrderId|      Amount   | ItemQty |Status
------------------------------------------
125    |       36.75   |    3    |  A    |
------------------------------------------
128    |       11.95   |    5    |  A    |
------------------------------------------

Detail contain lot of order detail

------------------------------------------
OrderId|  ItemId    |  Qty  | Price      |
------------------------------------------
125    |     12345 |  1   |  11.00      |
------------------------------------------
125    |     23456 |  1   |  12.75      |
------------------------------------------
125    |     34567 |  1   |  13.00      |
------------------------------------------

Temp Master

------------------------------------------
|OrderId|      Amount   | ItemQty |Status
------------------------------------------
|9999   |       36.75   |    3    |  A   |
------------------------------------------

Temp Detail

------------------------------------------
|OrderId |  ItemId  |  Qty | Price       |
------------------------------------------
| 9999   |   12345 |    1 |   11.00      |
------------------------------------------
| 9999   |   23456 |    1 |   12.75      |
------------------------------------------
| 9999   |   34567 |    1 |   13.00      |
------------------------------------------

thank you in advance

Body:
My best guess:

select Masterr.OrderId,
       sum(Masterr.Amount)
  from Masterr
 where Masterr.ItemQty = 3
   and exists(select *
                from Detail
                join TempMaster on TempMaster.ItemQty = Masterr.ItemQty
                join TempDetail on TempDetail.OrderId = TempMaster.OrderId
               where Detail.OrderId = Masterr.OrderId
                 and TempDetail.ItemId  = Detail.ItemId
                 and TempDetail.Qty     = Detail.Qty
                 and TempDetail.Price   = Detail.Price)
 group by Masterr.OrderId;


问:
Using list comprehension to store the maximum seen value
Is it possible to do the below with list comprehension? Trying to store the maximum value that has been seen at any given point through the loop.</p>

```<code>def test(input):
    a = input[0]
    b = []
    for i in input:
        a = max(i,a)
        b.append(a)
    return b

print test([-5,6,19,4,5,20,1,30])

# returns [-5, 6, 19, 19, 19, 20, 20, 30]
</code>```

答:
What you present here is a typical form of what is known in functional programming as scan.

A way to do this with list comprehension that is inefficient is:

```<code>[max(input[:i]) for i in range(1,n+1)]
</code>```

But this will run in O(n2).

You can do this with list comprehension given you use a function with side effects: like the following:

```<code>def update_and_store(f,initial=None):
    cache = [initial]
    def g(x):
       cache[0] = f(cache[0],x)
       return cache[0]
    return g
</code>```

You can then use:

```<code>h = update_and_store(max,a[0])
[h(x) for x in a]
</code>```

Or you can use a dictonaries setdefault() like:

```<code>def update_and_store(f):
    c = {}
    def g(x):
        return c.setdefault(0,f(c.pop(0,x),x))
    return g
</code>```

and call it with:

```<code>h = update_and_store(max)
[h(x) for x in a]
</code>```

like @AChampion says.

But functions with side-effects are rather unpythonic and not declarative.

But you better use a scanl or accumulate approach like the one offered by itertools:

```<code><b>from itertools import accumulate</b>

accumulate(input,max)</code>```

Body:
Is it possible to do the below with list comprehension? Trying to store the maximum value that has been seen at any given point through the loop.

def test(input):
    a = input[0]
    b = []
    for i in input:
        a = max(i,a)
        b.append(a)
    return b

print test([-5,6,19,4,5,20,1,30])

# returns [-5, 6, 19, 19, 19, 20, 20, 30]

Body:
What you present here is a typical form of what is known in functional programming as scan.

A way to do this with list comprehension that is inefficient is:

[max(input[:i]) for i in range(1,n+1)]

But this will run in O(n2).

You can do this with list comprehension given you use a function with side effects: like the following:

def update_and_store(f,initial=None):
    cache = [initial]
    def g(x):
       cache[0] = f(cache[0],x)
       return cache[0]
    return g

You can then use:

h = update_and_store(max,a[0])
[h(x) for x in a]

Or you can use a dictonaries setdefault() like:

def update_and_store(f):
    c = {}
    def g(x):
        return c.setdefault(0,f(c.pop(0,x),x))
    return g

and call it with:

h = update_and_store(max)
[h(x) for x in a]

like @AChampion says.

But functions with side-effects are rather unpythonic and not declarative.

But you better use a scanl or accumulate approach like the one offered by itertools:

from itertools import accumulate

accumulate(input,max)


问:
Htaccess and url for multilingual site
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

```<code>- Same filename
site.com/fr/login
site.com/en/login
</code>```

OR

```<code>- Different filename
site.com/fr/connexion
site.com/en/login
</code>```

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)

答:
Should you translate paths?

If possible, by all means - as this will help users of that language to feel like "first class citizens". Login routes probably won't have much impact on SEO, but translating URLs on content pages may well help them to be more discoverable.

You can read Google's recommendations on multi-regional and multilingual sites, which state that it's "fine to translate words in the URL".

Should you redirect based on IP?

This can help first time users, but there are a few things to bear in mind:

How accurate will this be? E.g. if I speak English but I visit France and then view your site - I will get French. If your target market is mobile-toting globe-trotters, then it may not be the best choice. Is looking at Accept-Language, for example, any better?

Will geolocating the IP address on every request introduce any performance problems for your servers? Or make too many calls to an external geocoding service? Make sure to carry out capacity planning, and reduce calls where you already know the locale (e.g. from a cookie, or user explicitly stating their preference.

Even if you guess a preferred locale, always allow an explicit user preference to override that. There's nothing more frustrating than moving between pages, and having the site decide that it knows better what language you understand :-)

As long as you make it easy to switch between sites, you shouldn't need a specific landing page. It doesn't hurt to pop up a banner if you're unsure whether you should redirect a user (for example, amazon.com will show a banner to a UK user, giving them the option of switching sites - but not deciding for them)

How should you structure your URLs?

Having the language somewhere in the URL (either as a subdomain or a folder) is probably best for SEO. Don't forget to update your sitemap as well, to indicate to crawlers that there are alternate content pages in different languages.

Title: Htaccess and url for multilingual site

Body:
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

- Same filename
site.com/fr/login
site.com/en/login

OR

- Different filename
site.com/fr/connexion
site.com/en/login

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)


问:
Google Places API Web Service Server Side Solution
I've been struggling through this for a few days now - I've got it working how I want but then I keep running into roadblocks which I will describe below. It's got to the point where I just need to ask for some advice from someone who has the necessary experience.

So this is what I ultimately want to achieve:

Web page loads and the user sees their local area on a Google Map

There are a list of brands next to the map, such as "Tesco" and
"Walmart" for example

When the user clicks on Walmart, they would
see all Walmart stores in their local area on the map - when the map
markers are clicked, the popup will contain the store name, address
etc.

Pretty simple in terms of functionality really.

I originally was using the Google Maps JavaScript API together with the Google Places API JavaScript Library.

I got the basic functionality working, but ran into the OVER_QUERY_LIMIT problem.

I discovered this happens because of the simultaneous requests being made (nothing to do with the daily usage limits); for example when the user clicks "Walmart", trying to show ~10+ stores on the map at the same time is blocked by Google.

From my research, it looked like I'd have to use the Google Maps API Web Services instead.

If too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code. The per-session rate limit prevents the use of client-side services for batch requests. For batch requests, use the Maps API web services.

So I also got it all working for a 2nd time using the Google Places API Web Service which I was pretty pleased about. I'm using AJAX to request the JSON from Google, but now I get the following console error:

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=53.000403,-1.129625&radius=10000&name=Sainsbury's|Debenhams&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I know I'm getting this error because I'm requesting from a different server/domain. Here's my code, which I'm just running locally at the moment:

accessURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+userCords.latitude+","+userCords.longitude+"&radius=10000&name=Sainsbury's|Debenhams&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg";

$.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  url: accessURL,
  dataType: 'json',
  success: function (data) {

    $.each(data.results, function (i, val) {
      storeId.push(val.place_id);
      storeName.push(val.name);
    });

    //Now, use the id to get detailed info
    $.each(storeId, function (k, v){
      $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "https://maps.googleapis.com/maps/api/place/details/json?placeid="+v+"&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg",
        dataType: 'json',
        success: function (data) {

          var latitude = data.result.geometry.location.lat;
          var longitude = data.result.geometry.location.lng;

          //set the markers.
          myLatlng = new google.maps.LatLng(latitude,longitude);

          allMarkers = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: data.result.name,
            html: '
' +
                '
'+data.result.name+'
' +
                  '
'+data.result.formatted_address+'
' +
                '
'
          });

          //put all lat long in array
          allLatlng.push(myLatlng);

          //Put the markers in an array
          tempMarkerHolder.push(allMarkers);

          google.maps.event.addListener(allMarkers, 'click', function () {
            infowindow.setContent(this.html);
            infowindow.open(map, this);
          });

          //  Make an array of the LatLng's of the markers you want to show
          //  Create a new viewpoint bound
          var bounds = new google.maps.LatLngBounds ();
          //  Go through each...
          for (var i = 0, LtLgLen = allLatlng.length; i < LtLgLen; i++) {
            //  And increase the bounds to take this point
            bounds.extend (allLatlng[i]);
          }
          //  Fit these bounds to the map
          map.fitBounds (bounds);

        }
      });
    }); //end .each
  }
});```

For testing, I've used this https://crossorigin.me prepended onto the API access urls to temporarily get around this issue, but now I actually need to solve the problem properly.

After some research, I saw a lot of people advising to change the dataType to jsonp. But when I do that, I get the following console error:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=53.041981899999996,-1.1898794&radius=10000&name=Sainsbury%27s|Debenhams&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg&callback=jQuery111309486707670378429_1491079656734&_=1491079656735:2
  Uncaught SyntaxError: Unexpected token :

After even more research into that latest error, I'm seeing things like "looks like the places api doesn't support ajax or jsonp", which is extremely annoying after I got it all working already!

Then I saw this:

The Google Places API Web Service is for use in server applications. If you're building a client-side application, take a look at the Google Places API for Android and the Places Library in the Google Maps JavaScript API.

Which means I've now gone full circle!

I'm at the point where I guess I have to work out a server-side solution instead of a client-side one. But honestly, I have no idea where to go from here and can't find anything online to point me in the right direction.

Can anyone please advise what to do next? What would a "server-side solution" look like? I've come this far, I really don't want to quit now! Any help would be hugely appreciated!

答:
To solve the issue you should build your own intermediate server that will send requests to Google (server side requests) and pass the JSON responses back to your client side application. In other words you should build a proxy to avoid the CORS issue.

How you build the proxy server, it's completely up to you. Choose the technology you are familiar with (Java, Python, NodeJs, etc.) and implement a server side code.

The client side code will send requests to intermediate server, intermediate server will send HTTPS request to Google and pass the response back to client side.

There are several useful libraries on GitHub that you can use server side with NodeJs, Java, Python or Go:

https://github.com/googlemaps/google-maps-services-js

https://github.com/googlemaps/google-maps-services-java

https://github.com/googlemaps/google-maps-services-python

https://github.com/googlemaps/google-maps-services-go

Hope it helps!

Body:
I've been struggling through this for a few days now - I've got it working how I want but then I keep running into roadblocks which I will describe below. It's got to the point where I just need to ask for some advice from someone who has the necessary experience.

So this is what I ultimately want to achieve:

Web page loads and the user sees their local area on a Google Map

There are a list of brands next to the map, such as "Tesco" and
"Walmart" for example

When the user clicks on Walmart, they would
see all Walmart stores in their local area on the map - when the map
markers are clicked, the popup will contain the store name, address
etc.

Pretty simple in terms of functionality really.

I originally was using the Google Maps JavaScript API together with the Google Places API JavaScript Library.

I got the basic functionality working, but ran into the OVER_QUERY_LIMIT problem.

I discovered this happens because of the simultaneous requests being made (nothing to do with the daily usage limits); for example when the user clicks "Walmart", trying to show ~10+ stores on the map at the same time is blocked by Google.

From my research, it looked like I'd have to use the Google Maps API Web Services instead.

If too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code. The per-session rate limit prevents the use of client-side services for batch requests. For batch requests, use the Maps API web services.

So I also got it all working for a 2nd time using the Google Places API Web Service which I was pretty pleased about. I'm using AJAX to request the JSON from Google, but now I get the following console error:

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=53.000403,-1.129625&radius=10000&name=Sainsbury's|Debenhams&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I know I'm getting this error because I'm requesting from a different server/domain. Here's my code, which I'm just running locally at the moment:

accessURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+userCords.latitude+","+userCords.longitude+"&radius=10000&name=Sainsbury's|Debenhams&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg";

$.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  url: accessURL,
  dataType: 'json',
  success: function (data) {

    $.each(data.results, function (i, val) {
      storeId.push(val.place_id);
      storeName.push(val.name);
    });

    //Now, use the id to get detailed info
    $.each(storeId, function (k, v){
      $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "https://maps.googleapis.com/maps/api/place/details/json?placeid="+v+"&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg",
        dataType: 'json',
        success: function (data) {

          var latitude = data.result.geometry.location.lat;
          var longitude = data.result.geometry.location.lng;

          //set the markers.
          myLatlng = new google.maps.LatLng(latitude,longitude);

          allMarkers = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: data.result.name,
            html: '
' +
                '
'+data.result.name+'
' +
                  '
'+data.result.formatted_address+'
' +
                '
'
          });

          //put all lat long in array
          allLatlng.push(myLatlng);

          //Put the markers in an array
          tempMarkerHolder.push(allMarkers);

          google.maps.event.addListener(allMarkers, 'click', function () {
            infowindow.setContent(this.html);
            infowindow.open(map, this);
          });

          //  Make an array of the LatLng's of the markers you want to show
          //  Create a new viewpoint bound
          var bounds = new google.maps.LatLngBounds ();
          //  Go through each...
          for (var i = 0, LtLgLen = allLatlng.length; i < LtLgLen; i++) {
            //  And increase the bounds to take this point
            bounds.extend (allLatlng[i]);
          }
          //  Fit these bounds to the map
          map.fitBounds (bounds);

        }
      });
    }); //end .each
  }
});

For testing, I've used this https://crossorigin.me prepended onto the API access urls to temporarily get around this issue, but now I actually need to solve the problem properly.

After some research, I saw a lot of people advising to change the dataType to jsonp. But when I do that, I get the following console error:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=53.041981899999996,-1.1898794&radius=10000&name=Sainsbury%27s|Debenhams&key=AIzaSyBJPuiaP0Xptia5x3aKgizYLkzqMTAdMMg&callback=jQuery111309486707670378429_1491079656734&_=1491079656735:2
  Uncaught SyntaxError: Unexpected token :

After even more research into that latest error, I'm seeing things like "looks like the places api doesn't support ajax or jsonp", which is extremely annoying after I got it all working already!

Then I saw this:

The Google Places API Web Service is for use in server applications. If you're building a client-side application, take a look at the Google Places API for Android and the Places Library in the Google Maps JavaScript API.

Which means I've now gone full circle!

I'm at the point where I guess I have to work out a server-side solution instead of a client-side one. But honestly, I have no idea where to go from here and can't find anything online to point me in the right direction.

Can anyone please advise what to do next? What would a "server-side solution" look like? I've come this far, I really don't want to quit now! Any help would be hugely appreciated!


问:
How to match and copy time-data from one matrix to another?
In MATLAB (R2015a), I have two large matrices that can be simplified as:

```<code>A = [ 24 10 830; 24 15 830; 150 17 945; 231 40 1130; 231 45 1130]
</code>```

(note that in A, column 3 is the time for the event cataloged in column 1) and

```<code>B = [24 13; 150 29; 231 43]
</code>```

How can I match and copy the time-data from column 3 in matrix A, to a matching and filtered event column in matrix B?

For example, I want the value 24 from first column in B to be matched with value 24 from first column in A, and then copy the corresponding time-data in A's third column (for 24 it's 830, for 150 it's 945 etc.) into B. This should result into our new B with the time-data from A:

```<code>B = [24 13 830; 150 29 945; 231 43 1130]
</code>```

I relatively new to MATLAB so any help is much appreciated!

答:
First find the location of the elements in the first row of B in the first row of A using the ismember function. And then use those locations to construct the new matrix.

```<code>[~,Locb] = ismember(B(:,1),A(:,1));
Bnew = [B A(Locb,3)]

Bnew =

          24          13         830
         150          29         945
         231          43        1130
</code>```

This is a fast way that comes to my mind. There might be some singularities that needed to be checked more thoroughly.

Body:
In MATLAB (R2015a), I have two large matrices that can be simplified as:

A = [ 24 10 830; 24 15 830; 150 17 945; 231 40 1130; 231 45 1130]

(note that in A, column 3 is the time for the event cataloged in column 1) and

B = [24 13; 150 29; 231 43]

How can I match and copy the time-data from column 3 in matrix A, to a matching and filtered event column in matrix B?

For example, I want the value 24 from first column in B to be matched with value 24 from first column in A, and then copy the corresponding time-data in A's third column (for 24 it's 830, for 150 it's 945 etc.) into B. This should result into our new B with the time-data from A:

B = [24 13 830; 150 29 945; 231 43 1130]

I relatively new to MATLAB so any help is much appreciated!

Body:
First find the location of the elements in the first row of B in the first row of A using the ismember function. And then use those locations to construct the new matrix.

[~,Locb] = ismember(B(:,1),A(:,1));
Bnew = [B A(Locb,3)]

Bnew =

          24          13         830
         150          29         945
         231          43        1130

This is a fast way that comes to my mind. There might be some singularities that needed to be checked more thoroughly.


问:
How can I use Scanner on switch case for String of array so that case takes in value from String b
How can I use Scanner class in "switch case" to determine the result;

Goal is to be able to use Scanner to determine the case. When user will input value in the scanner the select case will be able to use that String value (e.g if user type Mocking Bird in the Scanner it will be recognized in the switch case and out the code

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

    Scanner input = new Scanner(System.in);
    String b = input.next();

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {

      switch (Books[t]) {

        case "Harry Potter":
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;

        case "To Kill a Mocking Bird"
         System.out.println("Getting from switch case " + t + " " + Books[t]);
              break;

        default:
            break;
        }
     }
</code>```

答:
you just need to change

String b = input.next();

to

String b = input.nextLine();

and change the switch to

for (int t = 0; t < Books.length; t++) {
     switch (Books[t].equals(b)) {
        case true:
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;
         default:
            break;
        }
     }

or use if statement, it's better in this case

Body:
How can I use Scanner class in "switch case" to determine the result;

Goal is to be able to use Scanner to determine the case. When user will input value in the scanner the select case will be able to use that String value (e.g if user type Mocking Bird in the Scanner it will be recognized in the switch case and out the code

    import java.util.Scanner;

    Scanner input = new Scanner(System.in);
    String b = input.next();

    String Books[] = { "Harry Potter", "To Kill a Mocking Bird", "Hunger Games" };

    for (int t = 0; t < Books.length; t++) {

      switch (Books[t]) {

        case "Harry Potter":
         System.out.println("Getting from switch case " + t + " " + Books[t]);
             break;

        case "To Kill a Mocking Bird"
         System.out.println("Getting from switch case " + t + " " + Books[t]);
              break;

        default:
            break;
        }
     }


问:
Swift3 Fade in/Fade out or Smooth transition UIImageView animationImages
I am trying to do an images slideshow

What is the best way do add a smooth transition for animationImages in a UIImageView (Swift3)

here my code for the slideshow :

```<code>        DispatchQueue.main.async {
                imageView.animationImages = activeImages
                imageView.clipsToBounds = true
                imageView.animationDuration = (1.0 * Double(activeImages.count))
                imageView.animationRepeatCount = Int.max
                imageView.startAnimating()
         }
</code>```

答:
Use UIVIew.animate blocks and two UIImageViews for transitions, they are commonly used and produce very clean code.

```<code>UIView.animate(withDuration: 0.3,
               delay: 0,
               options: .curveEaseInOut, //just an example, check UIViewAnimationOptions
               animations: {
      self.image1.alpha = 0
      self.image2.alpha = 1
})
</code>```

Body:
I am trying to do an images slideshow

What is the best way do add a smooth transition for animationImages in a UIImageView (Swift3)

here my code for the slideshow :

        DispatchQueue.main.async {
                imageView.animationImages = activeImages
                imageView.clipsToBounds = true
                imageView.animationDuration = (1.0 * Double(activeImages.count))
                imageView.animationRepeatCount = Int.max
                imageView.startAnimating()
         }

Body:
Use UIVIew.animate blocks and two UIImageViews for transitions, they are commonly used and produce very clean code.

UIView.animate(withDuration: 0.3,
               delay: 0,
               options: .curveEaseInOut, //just an example, check UIViewAnimationOptions
               animations: {
      self.image1.alpha = 0
      self.image2.alpha = 1
})


问:
Django Rest Framework - Limiting fields of nesting serializer
I have User and Item models, and am having an issue with nested Items in a Item.objects.all() view.  Specifically, I'm getting the following in the ItemListView resource:

```<code>[  {
"id": 3,
"description": "Some test item description",
"user": {
  "id": 10,
  "username": "jason",
  "email": "test@test.com",
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0aW1lIjoiRnJpIE1hciAyNCAyMDo1NDo1OSAyMDE3IiwidXNlcm5hbWUiOiJqYXNvbiJ9.x4qdTF5eVKGLnrkcunm63n4d_X8xEzEYM0z48E5HKh4",
  "items": [
    {
      "id": 3,
      "description": "Some item description",
      "timestamp": "2017-03-25T15:50:08.265780Z",
      "user": 10
    },
    {
      "id": 2,
      "description": "test item description",
      "timestamp": "2017-03-24T22:28:49.904198Z",
      "user": 10
    }
  ]
},
"timestamp": "2017-03-25T15:50:08.265780Z"
</code>```

},

What I want is the User.items excluded from the output.  How can I do that with the serializers and models below:

```<code>class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only = True, required = False)
    confirm_password = serializers.CharField(required = False)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password', 'confirm_password', 'token', 'posts')
        read_only_fields = ('confirm_password', )
        depth = 1

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)

    def validate(self, data):
        if data['password'] != data['confirm_password']:
        raise ValidationError('Passwords do not match')

        return data

class ItemSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only = True)

    def create(self, validated_data):
        return Item.objects.create(**validated_data)

    class Meta:
        fields = ('id', 'content', 'user', 'timestamp')
        read_only_fields = ('timestamp', )
        model = Item
        depth = 1
</code>```

Models:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length = 50,
                                unique = True)
    email = models.EmailField(unique = True, blank = False, null = False)
    token = models.CharField(max_length = 255,
                             default = '')

    objects = UserManager()

    USERNAME_FIELD = 'username'

    def generate_token(self):
        self.token = User.objects.generate_token(user = self)
        self.save()

    @python_2_unicode_compatible
    def __str__(self):
        return '{} [Username: {}] [Email: {}]'.format(self.pk,
                                                      self.username,
                                                      self.email)

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

class Item(models.Model):
    description = models.CharField(db_index = True, max_length = 1000)
    timestamp = models.DateTimeField(auto_now_add = True,  db_index = True)
    user = models.ForeignKey(User,
                             on_delete = models.CASCADE,
                             related_name = 'items')

    def __str__(self):
        return '{} [User: {}] [Timestamp: {}] [Slug {}]'.format(self.pk, self.user.pk, self.timestamp, self.description[:20])

    class Meta:
        verbose_name = 'item'
        verbose_name_plural = 'items'
        ordering = ['-timestamp']
</code>```

答:
There is no out of the box solution to dynamically set which fields you want to serialize on related models.

You either need to define a stripped copy of UserSerializer and use it inside ItemSerializer (can define it right inside ItemSerializer class to not pollute the namespace), or extend the ModelSerializer and manually implement some support for dynamic field serialization, see here for some ideas (this could get tricky if you want to go a few layers deep I would imagine).

Body:
I have User and Item models, and am having an issue with nested Items in a Item.objects.all() view.  Specifically, I'm getting the following in the ItemListView resource:

[  {
"id": 3,
"description": "Some test item description",
"user": {
  "id": 10,
  "username": "jason",
  "email": "test@test.com",
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0aW1lIjoiRnJpIE1hciAyNCAyMDo1NDo1OSAyMDE3IiwidXNlcm5hbWUiOiJqYXNvbiJ9.x4qdTF5eVKGLnrkcunm63n4d_X8xEzEYM0z48E5HKh4",
  "items": [
    {
      "id": 3,
      "description": "Some item description",
      "timestamp": "2017-03-25T15:50:08.265780Z",
      "user": 10
    },
    {
      "id": 2,
      "description": "test item description",
      "timestamp": "2017-03-24T22:28:49.904198Z",
      "user": 10
    }
  ]
},
"timestamp": "2017-03-25T15:50:08.265780Z"

},

What I want is the User.items excluded from the output.  How can I do that with the serializers and models below:

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only = True, required = False)
    confirm_password = serializers.CharField(required = False)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password', 'confirm_password', 'token', 'posts')
        read_only_fields = ('confirm_password', )
        depth = 1

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)

    def validate(self, data):
        if data['password'] != data['confirm_password']:
        raise ValidationError('Passwords do not match')

        return data

class ItemSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only = True)

    def create(self, validated_data):
        return Item.objects.create(**validated_data)

    class Meta:
        fields = ('id', 'content', 'user', 'timestamp')
        read_only_fields = ('timestamp', )
        model = Item
        depth = 1

Models:

class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length = 50,
                                unique = True)
    email = models.EmailField(unique = True, blank = False, null = False)
    token = models.CharField(max_length = 255,
                             default = '')

    objects = UserManager()

    USERNAME_FIELD = 'username'

    def generate_token(self):
        self.token = User.objects.generate_token(user = self)
        self.save()

    @python_2_unicode_compatible
    def __str__(self):
        return '{} [Username: {}] [Email: {}]'.format(self.pk,
                                                      self.username,
                                                      self.email)

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

class Item(models.Model):
    description = models.CharField(db_index = True, max_length = 1000)
    timestamp = models.DateTimeField(auto_now_add = True,  db_index = True)
    user = models.ForeignKey(User,
                             on_delete = models.CASCADE,
                             related_name = 'items')

    def __str__(self):
        return '{} [User: {}] [Timestamp: {}] [Slug {}]'.format(self.pk, self.user.pk, self.timestamp, self.description[:20])

    class Meta:
        verbose_name = 'item'
        verbose_name_plural = 'items'
        ordering = ['-timestamp']


问:
How do I enlarge an image imported onto a Tkinter canvas?
I am working on making a background for my video game but I can't figure out or find out how to make the image larger.
My code is:

```<code>from tkinter import *
Master = Tk()
Can = Canvas(Master, width=1325, height=400)
img = PhotoImage(file="G.E.N.E.S\Textures\Ppm's\G.E.N.E.S.-1.ppm")
Background = Can.create_image(0,160,anchor=NW,image=img)
Blob = Can.create_oval(650,385,675,360,fil="black")
Can.config(bg="white")
Can.pack()
</code>```

How can I make the image larger on the Canvas?
I'd really appreciate anyone's help.
Note: I cant install any modules because I'm working at school.
P.S. I'm sorry but I can't figure out how to put a screen shot in.

答:
You can use the .zoom method.

```<code>img = PhotoImage(file="G.E.N.E.S\Textures\Ppm's\G.E.N.E.S.-1.ppm")
img.zoom(2,2) # x, y
</code>```

This will make the image larger by 2x both height and width. If x or y is not specified, x or y will stay the same.

Body:
I am working on making a background for my video game but I can't figure out or find out how to make the image larger.
My code is:

from tkinter import *
Master = Tk()
Can = Canvas(Master, width=1325, height=400)
img = PhotoImage(file="G.E.N.E.S\Textures\Ppm's\G.E.N.E.S.-1.ppm")
Background = Can.create_image(0,160,anchor=NW,image=img)
Blob = Can.create_oval(650,385,675,360,fil="black")
Can.config(bg="white")
Can.pack()

How can I make the image larger on the Canvas?
I'd really appreciate anyone's help.
Note: I cant install any modules because I'm working at school.
P.S. I'm sorry but I can't figure out how to put a screen shot in.

Body:
You can use the .zoom method.

img = PhotoImage(file="G.E.N.E.S\Textures\Ppm's\G.E.N.E.S.-1.ppm")
img.zoom(2,2) # x, y

This will make the image larger by 2x both height and width. If x or y is not specified, x or y will stay the same.


问:
How do I get the Back Button to work with an AngularJS ui-router state machine?
I have implemented an angularjs single page application using ui-router.

Originally I identified each state using a distinct url however this made for unfriendly, GUID packed urls.

So I have now defined my site as a much simpler state-machine. The states are not identified by urls but are simply transitioned to as required, like this:

Define Nested States

```<code>angular
.module 'app', ['ui.router']
.config ($stateProvider) ->
    $stateProvider
    .state 'main',
        templateUrl: 'main.html'
        controller: 'mainCtrl'
        params: ['locationId']

    .state 'folder',
        templateUrl: 'folder.html'
        parent: 'main'
        controller: 'folderCtrl'
        resolve:
            folder:(apiService) -> apiService.get '#base/folder/#locationId'
</code>```

Transition to a Defined State

```<code>#The ui-sref attrib transitions to the 'folder' state

a(ui-sref="folder({locationId:'{{folder.Id}}'})")
    | {{ folder.Name }}
</code>```

This system works very well and I love its clean syntax. However, as I am not using urls the back button does not work.

How do I keep my neat ui-router state-machine but enable the back button functionality?

答:
Can be solved using a simple directive "go-back-history", this one is also closing window in case of no previous history.

Directive usage

```<code><a data-go-back-history>Previous State</a>
</code>```

Angular directive declaration

```<code>.directive('goBackHistory', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            elm.on('click', function ($event) {
                $event.stopPropagation();
                if ($window.history.length) {
                    $window.history.back();
                } else {
                    $window.close();
                }
            });
        }
    };
}])
</code>```

Note: Working using ui-router or not.

Body:
I have implemented an angularjs single page application using ui-router.

Originally I identified each state using a distinct url however this made for unfriendly, GUID packed urls.

So I have now defined my site as a much simpler state-machine. The states are not identified by urls but are simply transitioned to as required, like this:

Define Nested States

angular
.module 'app', ['ui.router']
.config ($stateProvider) ->
    $stateProvider
    .state 'main',
        templateUrl: 'main.html'
        controller: 'mainCtrl'
        params: ['locationId']

    .state 'folder',
        templateUrl: 'folder.html'
        parent: 'main'
        controller: 'folderCtrl'
        resolve:
            folder:(apiService) -> apiService.get '#base/folder/#locationId'

Transition to a Defined State

#The ui-sref attrib transitions to the 'folder' state

a(ui-sref="folder({locationId:'{{folder.Id}}'})")
    | {{ folder.Name }}

This system works very well and I love its clean syntax. However, as I am not using urls the back button does not work.

How do I keep my neat ui-router state-machine but enable the back button functionality?

Body:
Can be solved using a simple directive "go-back-history", this one is also closing window in case of no previous history.

Directive usage

<a data-go-back-history>Previous State</a>

Angular directive declaration

.directive('goBackHistory', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            elm.on('click', function ($event) {
                $event.stopPropagation();
                if ($window.history.length) {
                    $window.history.back();
                } else {
                    $window.close();
                }
            });
        }
    };
}])

Note: Working using ui-router or not.


问:
What context name should be passed to Glide method?
In order to load image when using viewholder and fragment, I don't know context object name I should pass. Below is my glide code:

```<code>Glide.with(activity).load(cheeses.getImageView()).fitCenter().into(mImageView);
</code>```

Error:

```<code>at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1555)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
at com.bumptech.glide.manager.RequestManagerRetriever.getSupportRequestManagerFragment(RequestManagerRetriever.java:187)
at com.bumptech.glide.manager.RequestManagerRetriever.supportFragmentGet(RequestManagerRetriever.java:195)
at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:104)
at com.bumptech.glide.Glide.with(Glide.java:644)
at com.support.android.designlibdemo.ViewHolderClass.ViewHolder.bindToCheese(ViewHolder.java:42)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:112)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:93)
</code>```

答:
The issue is here:

```<code> Glide.with(activity)
</code>```

You are creating a new Activity, rather than getting the current activity, which is why you get that error. You should do:

```<code> Glide.with(getActivity())...
</code>```

Ideally, you would pass the Fragment context into your RecyclerView, and use that context in the call. The documents say:

public static RequestManager with(Context context)

Begin a load with
  Glide by passing in a context. Any requests started using a context
  will only have the application level options applied and will not be
  started or stopped based on lifecycle events. In general, loads should
  be started at the level the result will be used in. If the resource
  will be used in a view in a child fragment, the load should be started
  with with(android.app.Fragment)} using that child fragment. Similarly,
  if the resource will be used in a view in the parent fragment, the
  load should be started with with(android.app.Fragment) using the
  parent fragment. In the same vein, if the resource will be used in a
  view in an activity, the load should be started with
  with(android.app.Activity)}.

This method is appropriate for resources that will be used outside of
  the normal fragment or activity lifecycle (For example in services, or
  for notification thumbnails).

Parameters: context - Any context, will not be retained. Returns: A
  RequestManager for the top level application that can be used to start
  a load.

Source

You could do:

```<code>public ViewHolder(View view, Context context) {
    super(view);
    mView = view;
    mImageView = (ImageView) view.findViewById(R.id.avatar);
    mTextView = (TextView) view.findViewById(android.R.id.text1);
    activity = context;
}
</code>```

Then you could use activity.

Body:
In order to load image when using viewholder and fragment, I don't know context object name I should pass. Below is my glide code:

Glide.with(activity).load(cheeses.getImageView()).fitCenter().into(mImageView);

Error:

at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1555)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
at com.bumptech.glide.manager.RequestManagerRetriever.getSupportRequestManagerFragment(RequestManagerRetriever.java:187)
at com.bumptech.glide.manager.RequestManagerRetriever.supportFragmentGet(RequestManagerRetriever.java:195)
at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:104)
at com.bumptech.glide.Glide.with(Glide.java:644)
at com.support.android.designlibdemo.ViewHolderClass.ViewHolder.bindToCheese(ViewHolder.java:42)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:112)
at com.support.android.designlibdemo.CheeseListFragment$1.populateViewHolder(CheeseListFragment.java:93)

Body:
The issue is here:

 Glide.with(activity)

You are creating a new Activity, rather than getting the current activity, which is why you get that error. You should do:

 Glide.with(getActivity())...

Ideally, you would pass the Fragment context into your RecyclerView, and use that context in the call. The documents say:

public static RequestManager with(Context context)

Begin a load with
  Glide by passing in a context. Any requests started using a context
  will only have the application level options applied and will not be
  started or stopped based on lifecycle events. In general, loads should
  be started at the level the result will be used in. If the resource
  will be used in a view in a child fragment, the load should be started
  with with(android.app.Fragment)} using that child fragment. Similarly,
  if the resource will be used in a view in the parent fragment, the
  load should be started with with(android.app.Fragment) using the
  parent fragment. In the same vein, if the resource will be used in a
  view in an activity, the load should be started with
  with(android.app.Activity)}.

This method is appropriate for resources that will be used outside of
  the normal fragment or activity lifecycle (For example in services, or
  for notification thumbnails).

Parameters: context - Any context, will not be retained. Returns: A
  RequestManager for the top level application that can be used to start
  a load.

Source

You could do:

public ViewHolder(View view, Context context) {
    super(view);
    mView = view;
    mImageView = (ImageView) view.findViewById(R.id.avatar);
    mTextView = (TextView) view.findViewById(android.R.id.text1);
    activity = context;
}

Then you could use activity.


问:
Ruby on Rails - rspec Validation failed: Class must exist
I'm currently writing tests for my web application and I came across something out of my intelligence scope.

The context:
I am testing the "show" method of the UserController. However, User has a 1 to 1 relation with the class Face.

Here is the code testing the show method.

```<code>it "assigns the requested user as @user" do
   face = Face.create(:id => 1)
   user = User.create! valid_attributes
   get :show, params: {id: user.to_param}, session: valid_session
   expect(assigns(:user)).to eq(user)
  end
end
</code>```

let(:valid_attributes) {
    { "lastName" => "lname", "firstName" => "fname", "face_id" => 1 }
  }

When I run rspec here is the error in the console :

```<code>Failure/Error: user = User.create! valid_attributes

ActiveRecord::RecordInvalid:
   Validation failed: Face must exist
</code>```

How come Face doesn't exist If I created it?

答: The problem was simply that Face needed an additional attribute. Make sure you double check your models, because Rails won't tell you that the object creation failed. (This is what happened in my case.)</p>

Body:
I'm currently writing tests for my web application and I came across something out of my intelligence scope.

The context:
I am testing the "show" method of the UserController. However, User has a 1 to 1 relation with the class Face.

Here is the code testing the show method.

it "assigns the requested user as @user" do
   face = Face.create(:id => 1)
   user = User.create! valid_attributes
   get :show, params: {id: user.to_param}, session: valid_session
   expect(assigns(:user)).to eq(user)
  end
end

let(:valid_attributes) {
    { "lastName" => "lname", "firstName" => "fname", "face_id" => 1 }
  }

When I run rspec here is the error in the console :

Failure/Error: user = User.create! valid_attributes

ActiveRecord::RecordInvalid:
   Validation failed: Face must exist

How come Face doesn't exist If I created it?


问:
use tuple, array, dictionary, or list for estimating unknow parameters from sratch
I need to do parameter estimations by writing estimation procedure from scratch, not using-ready-to-use routines. For example, we need to optimize the parameters by writing out the specific objective functions most the time. For the unknown parameters, it usually comes in the form of vectors such as BETA=[beta1,beta2....beta_n]. When I estimate the parameters in R, I don't really care about data structures. For python, I know tuple is immutable and I have seen people using tuple for parameter vectors,but what is the common practice for parameter estimations? Is there any big difference specifically for parameter estimations (Tuple seems a bit faster?)?

答:
Have you considered using a dictionary? You can have your estimations as a key:value pair such as:

```<code>beta_dict={beta_1:value_of_beta_1, beta_2:value_of_beta_2, etc...}
</code>```

You can then access the values by key:

```<code>beta_dict[beta_n] # returns value_of_beta_n
</code>```

If you are getting the estimates from a loop you can store them as key:value pairs as follows:

```<code>for i in range(length(BETA)): # length(BETA) returns the amount of elements in BETA list
    tmp_key="beta_{}".format(i)
    beta_dict[tmp_key]=BETA[i] # stores the key(tmp_key):value(BETA[i]) pair
</code>```

Body:
Have you considered using a dictionary? You can have your estimations as a key:value pair such as:

beta_dict={beta_1:value_of_beta_1, beta_2:value_of_beta_2, etc...}

You can then access the values by key:

beta_dict[beta_n] # returns value_of_beta_n

If you are getting the estimates from a loop you can store them as key:value pairs as follows:

for i in range(length(BETA)): # length(BETA) returns the amount of elements in BETA list
    tmp_key="beta_{}".format(i)
    beta_dict[tmp_key]=BETA[i] # stores the key(tmp_key):value(BETA[i]) pair


问:
Why is setState returning undefined?
I am trying to close a modal when a user presses outside of the Modal element. Somehow when Dismiss() is called, the state is still the same in the callback.

Why is this happening?

```<code>export default class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            show: false
        };
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    Show(id) {
        this.setState({
            id: id,
            show: true
        });
    }

    Dismiss() {
        this.setState({
            id: '',
            show: false
        }, function (state) {
            console.log(state) // undefined
        });
    }

    render() {
        if (this.state.show) {
            return (
                <Modal close={() => this.Dismiss()}>
                    <h1>{this.state.id}</h1>
                </Modal>
            );
        } else {
            return null
        }
    }
}
</code>```

答:
Yes, that is because this.setState function in React is async. And the new state is only available in the event queue

Here is what I mean:

```<code>this.setState({newAdded: "test"});
let youCannotGetIt = this.state.newAdded; // here is undefined, because this.setSate is async
</code>```

Title: Why is setState returning undefined?

Body:
I am trying to close a modal when a user presses outside of the Modal element. Somehow when Dismiss() is called, the state is still the same in the callback.

Why is this happening?

export default class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            show: false
        };
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    Show(id) {
        this.setState({
            id: id,
            show: true
        });
    }

    Dismiss() {
        this.setState({
            id: '',
            show: false
        }, function (state) {
            console.log(state) // undefined
        });
    }

    render() {
        if (this.state.show) {
            return (
                <Modal close={() => this.Dismiss()}>

{this.state.id}

                </Modal>
            );
        } else {
            return null
        }
    }
}

Body:
Yes, that is because this.setState function in React is async. And the new state is only available in the event queue

Here is what I mean:

this.setState({newAdded: "test"});
let youCannotGetIt = this.state.newAdded; // here is undefined, because this.setSate is async


问:
Ending a while loop with a predetermined input in eclipse
I'm writing a small script that will take miles input by user and gallons input and show the number of trips and the miles per gallon of the total trips taken. Here's what I have.

```<code>public class FuelEfficiency
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        double totalMiles = 0;
        double totalGallons = 0;
        int tripCounter = 0;

        while (tripCounter > -1)
        {
            System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
            double milesDriven = input.nextDouble();
            totalMiles = totalMiles + milesDriven;

            System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
            double gasConsumed = input.nextDouble();
            totalGallons = totalGallons + gasConsumed;

            tripCounter = tripCounter + 1;

            double milesPerGallon = totalMiles / totalGallons;

        System.out.printf("%nYour number of trips is: %s%n", tripCounter);
        System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
        }

    }

}
</code>```

As it is right now, the loop will continue indefinitely. What I want to do is be able to accept a predefined input (like 'quit' or 'q') to end the loop and report the previous trip and milePerGallon without making a new equation or adding another trip. (I have also thought of trying to continue the loop until a value of '0' is entered. I suspect I would be using milesDriven and gasConsumed to loop that way. But whenever I tried that it would still take those values into account when it runs the new milePerGallon.)

Any tips on what I should use to do this?

答:
The reason it still counts the 0 in your code is because the calculations come after the input. To fix this you could change your code like this. So the if statement makes sure the value is above 0, before the calculations run.</p>

```<code>    while (milesDriven>0)
            {
                System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
                double milesDriven = input.nextDouble();
                if (milesDrive>0)
                {
                totalMiles = totalMiles + milesDriven;

                System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
                double gasConsumed = input.nextDouble();
                totalGallons = totalGallons + gasConsumed;

                tripCounter = tripCounter + 1;

                double milesPerGallon = totalMiles / totalGallons;
                }
            System.out.printf("%nYour number of trips is: %s%n", tripCounter);
            System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
            }
</code>```

Body:
I'm writing a small script that will take miles input by user and gallons input and show the number of trips and the miles per gallon of the total trips taken. Here's what I have.

public class FuelEfficiency
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        double totalMiles = 0;
        double totalGallons = 0;
        int tripCounter = 0;

        while (tripCounter > -1)
        {
            System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
            double milesDriven = input.nextDouble();
            totalMiles = totalMiles + milesDriven;

            System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
            double gasConsumed = input.nextDouble();
            totalGallons = totalGallons + gasConsumed;

            tripCounter = tripCounter + 1;

            double milesPerGallon = totalMiles / totalGallons;

        System.out.printf("%nYour number of trips is: %s%n", tripCounter);
        System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
        }

    }

}

As it is right now, the loop will continue indefinitely. What I want to do is be able to accept a predefined input (like 'quit' or 'q') to end the loop and report the previous trip and milePerGallon without making a new equation or adding another trip. (I have also thought of trying to continue the loop until a value of '0' is entered. I suspect I would be using milesDriven and gasConsumed to loop that way. But whenever I tried that it would still take those values into account when it runs the new milePerGallon.)

Any tips on what I should use to do this?

Body:
The reason it still counts the 0 in your code is because the calculations come after the input. To fix this you could change your code like this. So the if statement makes sure the value is above 0, before the calculations run.

    while (milesDriven>0)
            {
                System.out.print("Enter miles driven: "); //Want to say "Enter miles driven or 'q' to quit: "
                double milesDriven = input.nextDouble();
                if (milesDrive>0)
                {
                totalMiles = totalMiles + milesDriven;

                System.out.print("Enter gallons of gas consumed: "); // Similar to the above.
                double gasConsumed = input.nextDouble();
                totalGallons = totalGallons + gasConsumed;

                tripCounter = tripCounter + 1;

                double milesPerGallon = totalMiles / totalGallons;
                }
            System.out.printf("%nYour number of trips is: %s%n", tripCounter);
            System.out.printf("Your mileage per gallon of gas consumed is: %s%n%n", milesPerGallon);
            }


问:
Sending Json data as an object into DataTables
I have been trying to use DataTables. But after my Ajax request i get a Json object which i cannot pass into dataTables.

The Json object i receive is the following

```<code>{"data": [{"attributes": {"purchasedate": "04/01/2017", "medication": "meds", "cost": 100.0, "expirydate": "04/03/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Meds", "cost": 100.0, "expirydate": "04/02/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Super Meds", "cost": 267.0, "expirydate": "04/11/2017", "quantity": 250.0}, "type": "medical_inventory"}], "links": {"self": "/medical_inventory/"}}
</code>```

Following is my HTML code

```<code><table id="myTable" class="display" cellspacing="0" width="90%">
    <thead>
        <tr>
            <th>Medication</th>
            <th>Medication Quantity</th>
            <th>Mediaction Cost</th>
            <th>Purchase Date</th>
            <th>Expiry Date</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Medication</th>
            <th>Medication Quantity</th>
            <th>Mediaction Cost</th>
            <th>Purchase Date</th>
            <th>Expiry Date</th>
        </tr>
    </tfoot>
</table>
</code>```

The Ajax request i do is the following

```<code>$(document).ready(function () {
        $.ajax({
            url : '/api/medical_inventory/',
            type : 'GET',
            dataType : 'json',
            success : function(data) {
                assignToEventsColumns(data);
            }
        });

        function assignToEventsColumns(data) {
            var table = $('#myTable').dataTable({
                "bAutoWidth" : false,
                "aaData" : data,
                "columns" : [ {
                    "data" : "medication"
                }, {
                    "data" : "quantity"
                }, {
                    "data" : "cost"
                }, {
                    "data" : "purchasedate"
                }, {
                    "data" : "expirydate"
                } ]
            })
        }
    });
</code>```

This is the output i am currently getting

答:
Try mapping the data to remove the attributes property of each object

```<code>success : function(data) {
   data.data = data.data.map(function(item){
      return item.attributes;
  });
  assignToEventsColumns(data);
}
</code>```

Body:
I have been trying to use DataTables. But after my Ajax request i get a Json object which i cannot pass into dataTables.

The Json object i receive is the following

{"data": [{"attributes": {"purchasedate": "04/01/2017", "medication": "meds", "cost": 100.0, "expirydate": "04/03/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Meds", "cost": 100.0, "expirydate": "04/02/2017", "quantity": 100.0}, "type": "medical_inventory"}, {"attributes": {"purchasedate": "04/01/2017", "medication": "Extra Super Meds", "cost": 267.0, "expirydate": "04/11/2017", "quantity": 250.0}, "type": "medical_inventory"}], "links": {"self": "/medical_inventory/"}}

Following is my HTML code

            Medication
            Medication Quantity
            Mediaction Cost
            Purchase Date
            Expiry Date

            Medication
            Medication Quantity
            Mediaction Cost
            Purchase Date
            Expiry Date

The Ajax request i do is the following

$(document).ready(function () {
        $.ajax({
            url : '/api/medical_inventory/',
            type : 'GET',
            dataType : 'json',
            success : function(data) {
                assignToEventsColumns(data);
            }
        });

        function assignToEventsColumns(data) {
            var table = $('#myTable').dataTable({
                "bAutoWidth" : false,
                "aaData" : data,
                "columns" : [ {
                    "data" : "medication"
                }, {
                    "data" : "quantity"
                }, {
                    "data" : "cost"
                }, {
                    "data" : "purchasedate"
                }, {
                    "data" : "expirydate"
                } ]
            })
        }
    });

This is the output i am currently getting

Body:
Try mapping the data to remove the attributes property of each object

success : function(data) {
   data.data = data.data.map(function(item){
      return item.attributes;
  });
  assignToEventsColumns(data);
}


问:
Jaxb generated xml - problem with root element prefix
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

```<code> <report>
   <id>rep 1</id>
</report>
</code>```

, But getting as

```<code><ns2:report>
....
</ns2:report>
</code>```

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

答:
If this is your class:

```<code>package example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="report",namespace="urn:report")
public class Root {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}
</code>```

Then it makes sense that there is a prefix on the root element, because you have specified that the "root" element is namespace qualified and the "id" element is not.

```<code><ns2:report xmlns:ns2="urn:report">
    <id>123</id>
</ns2:report>
</code>```

If you add a package-info class to your model, you can leverate the @XmlSchema annotation:

```<code>@XmlSchema(
        namespace = "urn:report",
        elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
</code>```

Then the JAXB implementation may choose to leverage the default namespace, but note now all of the elements are namespace qualified which may or may not match your XML schema:

```<code><report xmlns="urn:report">
    <id>123</id>
</report>
</code>```

For more information on JAXB and namespaces see:

http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html

ContentLicense: CC BY-SA 2.5

Body:
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

 <report>
   <id>rep 1</id>
</report>

, But getting as

<ns2:report>
....
</ns2:report>

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

Body:
If this is your class:

package example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="report",namespace="urn:report")
public class Root {

    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

Then it makes sense that there is a prefix on the root element, because you have specified that the "root" element is namespace qualified and the "id" element is not.

<ns2:report xmlns:ns2="urn:report">
    <id>123</id>
</ns2:report>

If you add a package-info class to your model, you can leverate the @XmlSchema annotation:

@XmlSchema(
        namespace = "urn:report",
        elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Then the JAXB implementation may choose to leverage the default namespace, but note now all of the elements are namespace qualified which may or may not match your XML schema:

<report xmlns="urn:report">
    <id>123</id>
</report>

For more information on JAXB and namespaces see:

http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html


问:
Jackcess: wrong charset for MSAccess database
I have a MS-Access database which has "encrypted" Strings in it. These look like that:

However, I quickly noticed that the length of these Strings matches exactly the length of the plaintext (I know the plaintext). So with a bit of trying with Excel, I found out that if you use the =CODE(<char>)-function (so you get the character-code in the default charset, and =CHAR(<number>) viceversa) and xor this number with the character code of the letter the symbol should represent you always get the same result. Which means I just have to create an array with these values in java and voila. Excel example (on the right the mentioned "Array"):

Example: ">>" has an index of (dec) 187, so 187xor253 yields 70 => "F"

Now, I use jackcess to access these values and the "decryption" is mostly fine but I sometimes get the wrong character out of strings. In Excel everything works just fine. Code with the best results:

```<code>public static final int[] DECRYPT_KEY = { 253, 203, 204, 217, 226, 205, 128, 201, 222, 183, 58, 217, 230, 201, 183, 211, 158, 203, 167, 213, 35, 33, 201, 123, 186, 247 };

public static void main(String[] args) throws IOException
{
    System.out.println(System.getProperty("file.encoding"));

    Database db = DatabaseBuilder.open(new File("/home/***/TM.db"));
    Table table = db.getTable("personal");

    for (Row row : table)
    {
        String vorname = row.getString("vorname");
        byte[] vornameArr = vorname.getBytes("cp1252");
        for (int i1 = 0; i1 < vornameArr.length; i1++)
        {
            vornameArr[i1] = (byte) ((vornameArr[i1] & 0xff) ^ DECRYPT_KEY[i1]);
        }

        System.out.println(new String(vornameArr, "cp1252"));
    }
}
</code>```

But as I said, some characters are still wrong, in Excel however everything is fine. When I print out the number which getBytes("cp1272") gives, it is completely different to the Excel one.

Do you have any ideas, what I could be doing wrong and why java gives sometimes such different values than Excel? What would be a better approach? I already tried all combinations of charsets, some worked where others failed but then had other wrong results.

答:
So thanks to @Gord Thompson and the website he suggested (fileformat.info) I finally found an answer: Sometimes characters look similar, and for some reason in the database the "higher" ones are preferred (such as unicode character 402 and 131). My java code expected everything to have the lower value, as excel provided it. So, if the code is higher than 255 it needs to be substituted by a lower value. For some reason, getBytes("cp1252") will always return that lower value, however toCharArray() and getBytes("UTF-16LE") will return the higher, correct value (Compare: fileformat 192)

So my code is like this now and works perfectly:

```<code>String vorname = row.getString("vorname");
char[] vornameArr = vorname.toCharArray();
for (int i = 0; i < vornameArr.length; i++)
{
    if (vornameArr[i] > 255)
    {
        vornameArr[i] = (char) (String.valueOf(vornameArr[i]).getBytes("cp1252")[0] & 0xff);
    }

    vornameArr[i] = (char) (vornameArr[i] ^ DECRYPT_KEY[i]);
}

System.out.println(String.valueOf(vornameArr));
</code>```

Thank you very much for your help!

Body:
I have a MS-Access database which has "encrypted" Strings in it. These look like that:

However, I quickly noticed that the length of these Strings matches exactly the length of the plaintext (I know the plaintext). So with a bit of trying with Excel, I found out that if you use the =CODE(<char>)-function (so you get the character-code in the default charset, and =CHAR(<number>) viceversa) and xor this number with the character code of the letter the symbol should represent you always get the same result. Which means I just have to create an array with these values in java and voila. Excel example (on the right the mentioned "Array"):

Example: ">>" has an index of (dec) 187, so 187xor253 yields 70 => "F"

Now, I use jackcess to access these values and the "decryption" is mostly fine but I sometimes get the wrong character out of strings. In Excel everything works just fine. Code with the best results:

public static final int[] DECRYPT_KEY = { 253, 203, 204, 217, 226, 205, 128, 201, 222, 183, 58, 217, 230, 201, 183, 211, 158, 203, 167, 213, 35, 33, 201, 123, 186, 247 };

public static void main(String[] args) throws IOException
{
    System.out.println(System.getProperty("file.encoding"));

    Database db = DatabaseBuilder.open(new File("/home/***/TM.db"));
    Table table = db.getTable("personal");

    for (Row row : table)
    {
        String vorname = row.getString("vorname");
        byte[] vornameArr = vorname.getBytes("cp1252");
        for (int i1 = 0; i1 < vornameArr.length; i1++)
        {
            vornameArr[i1] = (byte) ((vornameArr[i1] & 0xff) ^ DECRYPT_KEY[i1]);
        }

        System.out.println(new String(vornameArr, "cp1252"));
    }
}

But as I said, some characters are still wrong, in Excel however everything is fine. When I print out the number which getBytes("cp1272") gives, it is completely different to the Excel one.

Do you have any ideas, what I could be doing wrong and why java gives sometimes such different values than Excel? What would be a better approach? I already tried all combinations of charsets, some worked where others failed but then had other wrong results.

Body:
So thanks to @Gord Thompson and the website he suggested (fileformat.info) I finally found an answer: Sometimes characters look similar, and for some reason in the database the "higher" ones are preferred (such as unicode character 402 and 131). My java code expected everything to have the lower value, as excel provided it. So, if the code is higher than 255 it needs to be substituted by a lower value. For some reason, getBytes("cp1252") will always return that lower value, however toCharArray() and getBytes("UTF-16LE") will return the higher, correct value (Compare: fileformat 192)

So my code is like this now and works perfectly:

String vorname = row.getString("vorname");
char[] vornameArr = vorname.toCharArray();
for (int i = 0; i < vornameArr.length; i++)
{
    if (vornameArr[i] > 255)
    {
        vornameArr[i] = (char) (String.valueOf(vornameArr[i]).getBytes("cp1252")[0] & 0xff);
    }

    vornameArr[i] = (char) (vornameArr[i] ^ DECRYPT_KEY[i]);
}

System.out.println(String.valueOf(vornameArr));

Thank you very much for your help!


问:
How can I ensure that arguments have same type without listing the types explicitly?
Let us assume that we need a function that accepts two arguments of any type as long as both arguments have the same type. How would you check it statically with mypy?

If we only need the function to accept some finite amount of already known types, it is easy:

from typing import TypeVar, List, Callable

T = TypeVar('T', int, str, List[int], Callable[[], int])

def f(a: T, b: T) -> None:
   pass

f(1, 2)
f("1", "2")
f([1], [2])
f(lambda: 1, lambda: 2)
f(1, "2") # mypy will print an error message
```

For this code, mypy can ensure that the arguments to f are either two ints or two strs or two lists of ints or two functions of zero arguments that return int.

But what if we don't know the types in advance? What if we need something similar to let f (a:'t) (b:'t) = () from F# and OCaml? Simply writing T = TypeVar('T') would make things like f(1, "2") valid, and this is not what we want.

答:
What you're asking for is impossible (see below for explanation). But usually, there's no need in python to require that two arguments have precisely identical type.

In your example, int, str, List[int], Callable[[], int] don't have any common methods or attributes (other than what any two object instances have), so unless you manually check the type with isinstance, you can't really do anything with your argument that you couldn't do with object instances. Could you explain your use case?

Explanation of why you can't enforce type equality

Mypy type system has subtyping. So when you write f(a, b), mypy only checks that types of a and b are both subtypes of T rather than precisely equal to T.

In addition mypy subtyping system is mostly pre-defined and not under the programmer control, in particular every type is a subtype of object. (IIUC, in OCaml the programmer needs to say explicitly which types should be in a subtyping relationship, so by default every type constraint is equality constraint. That's why you could do what you wanted in OCaml).

So, when you write

```<code>T = TypeVar('T')
f(a: T, b: T) -> None: ...
f(x, y)
</code>```

you are only telling mypy that the types of x and y must be subtypes of some common type T. And of course, this constraint is always (trivially) satisfied by inferring that T is object.

Update

To your question in the comment (is it possible to ensure that type of y is of subtype of type of x?), the answer is also no.

Even though mypy allows a type variable to be bounded from above by a specified type, that bound cannot be another type variable, so this won't work:

```<code>T = TypeVar('T')
U = TypeVar('U', bound=T, contravariant=True) # error, T not valid here
f(x: T, y: U) -> None
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let us assume that we need a function that accepts two arguments of any type as long as both arguments have the same type. How would you check it statically with mypy?

If we only need the function to accept some finite amount of already known types, it is easy:

from typing import TypeVar, List, Callable

T = TypeVar('T', int, str, List[int], Callable[[], int])

def f(a: T, b: T) -> None:
   pass

f(1, 2)
f("1", "2")
f([1], [2])
f(lambda: 1, lambda: 2)
f(1, "2") # mypy will print an error message

For this code, mypy can ensure that the arguments to f are either two ints or two strs or two lists of ints or two functions of zero arguments that return int.

But what if we don't know the types in advance? What if we need something similar to let f (a:'t) (b:'t) = () from F# and OCaml? Simply writing T = TypeVar('T') would make things like f(1, "2") valid, and this is not what we want.

Body:
What you're asking for is impossible (see below for explanation). But usually, there's no need in python to require that two arguments have precisely identical type.

In your example, int, str, List[int], Callable[[], int] don't have any common methods or attributes (other than what any two object instances have), so unless you manually check the type with isinstance, you can't really do anything with your argument that you couldn't do with object instances. Could you explain your use case?

Explanation of why you can't enforce type equality

Mypy type system has subtyping. So when you write f(a, b), mypy only checks that types of a and b are both subtypes of T rather than precisely equal to T.

In addition mypy subtyping system is mostly pre-defined and not under the programmer control, in particular every type is a subtype of object. (IIUC, in OCaml the programmer needs to say explicitly which types should be in a subtyping relationship, so by default every type constraint is equality constraint. That's why you could do what you wanted in OCaml).

So, when you write

T = TypeVar('T')
f(a: T, b: T) -> None: ...
f(x, y)

you are only telling mypy that the types of x and y must be subtypes of some common type T. And of course, this constraint is always (trivially) satisfied by inferring that T is object.

Update

To your question in the comment (is it possible to ensure that type of y is of subtype of type of x?), the answer is also no.

Even though mypy allows a type variable to be bounded from above by a specified type, that bound cannot be another type variable, so this won't work:

T = TypeVar('T')
U = TypeVar('U', bound=T, contravariant=True) # error, T not valid here
f(x: T, y: U) -> None


答:
You can try this in base R:

```<code>a <- which(df$EUR.20MA.1==1)
b <- which(df$EUR.20MA.1 %in% c(0,-1))
rws <- sapply(b, function(x) any(a==x-1))
df$Difference <- 0
df[b[rws]-1,]$Difference <- abs(df[b[rws]-1,]$EUR.LAST.2 - df[b[rws],]$EUR.LAST.2)

           # EUR.20MA.1 EUR.LAST.2 Difference
# 2013-11-04          1     1.3514     0.0040
# 2013-11-05         -1     1.3474     0.0000
# 2013-11-06          1     1.3513     0.0094
# 2013-11-07          0     1.3419     0.0000
# 2013-11-08         -1     1.3367     0.0000
# 2013-11-11          1     1.3407     0.0000
# 2013-11-12          1     1.3436     0.0000
# 2013-11-13          1     1.3487     0.0026
# 2013-11-14         -1     1.3461     0.0000
# 2013-11-15          1     1.3496     0.0000
</code>```

So you first find the rows where 1 is appeared and assign them to a. Then you search for rows in which 0 or -1 is appeared and assign them to b. Then search for sequence numbers in a or b which are those rows you look after.

OR use this (following the idea of @Lamia to multiply df$EUR.20MA.1 by 2):

```<code>df$Difference <- c(head(df$EUR.LAST.2, -1) - tail(df$EUR.LAST.2, -1), 0)
df[!c(with(df, (2*head(EUR.20MA.1, -1) - tail(EUR.20MA.1, -1)) %in% c(2,3)), FALSE),] <- 0
</code>```

which will give you the same result.

Title: How do I take differences of two rows based on conditional statement?

Body:
I'm having a lot of trouble with this really easy problem. Below is a sample of my data:

            EUR.20MA.1 EUR.LAST.2
2013-11-04          1     1.3514
2013-11-05         -1     1.3474
2013-11-06          1     1.3513
2013-11-07          0     1.3419
2013-11-08         -1     1.3367
2013-11-11          1     1.3407

Basically whenever the signal changes from 1 to 0, or 1 to -1, I want to take the difference of that row with the subsequent row. Hence, output would look like:

         EUR.20MA.1 EUR.LAST.2  Difference
11/4/2013   1       1.3514      0.004
11/5/2013  -1       1.3474      0
11/6/2013   1       1.3513      0.0094
11/7/2013   0       1.3419      0
11/8/2013  -1       1.3367      0
11/11/2013  1       1.3407      0
11/12/2013  1       1.3436      0
11/13/2013  1       1.3487      0.0026
11/14/2013 -1       1.3461      0

Dput below:

structure(list(EUR.20MA.1 = c(1, -1, 1, 0, -1, 1, 1, 1, -1, 1
), EUR.LAST.2 = c(1.3514, 1.3474, 1.3513, 1.3419, 1.3367, 1.3407,
1.3436, 1.3487, 1.3461, 1.3496)), .Names = c("EUR.20MA.1", "EUR.LAST.2"
), row.names = c("2013-11-04", "2013-11-05", "2013-11-06", "2013-11-07",
"2013-11-08", "2013-11-11", "2013-11-12", "2013-11-13", "2013-11-14",
"2013-11-15"), class = "data.frame")

Body:
You can try this in base R:

a <- which(df$EUR.20MA.1==1)
b <- which(df$EUR.20MA.1 %in% c(0,-1))
rws <- sapply(b, function(x) any(a==x-1))
df$Difference <- 0
df[b[rws]-1,]$Difference <- abs(df[b[rws]-1,]$EUR.LAST.2 - df[b[rws],]$EUR.LAST.2)

           # EUR.20MA.1 EUR.LAST.2 Difference
# 2013-11-04          1     1.3514     0.0040
# 2013-11-05         -1     1.3474     0.0000
# 2013-11-06          1     1.3513     0.0094
# 2013-11-07          0     1.3419     0.0000
# 2013-11-08         -1     1.3367     0.0000
# 2013-11-11          1     1.3407     0.0000
# 2013-11-12          1     1.3436     0.0000
# 2013-11-13          1     1.3487     0.0026
# 2013-11-14         -1     1.3461     0.0000
# 2013-11-15          1     1.3496     0.0000

So you first find the rows where 1 is appeared and assign them to a. Then you search for rows in which 0 or -1 is appeared and assign them to b. Then search for sequence numbers in a or b which are those rows you look after.

OR use this (following the idea of @Lamia to multiply df$EUR.20MA.1 by 2):

df$Difference <- c(head(df$EUR.LAST.2, -1) - tail(df$EUR.LAST.2, -1), 0)
df[!c(with(df, (2*head(EUR.20MA.1, -1) - tail(EUR.20MA.1, -1)) %in% c(2,3)), FALSE),] <- 0

which will give you the same result.


问:
How to make interface for std::pair<> with no default constructor in swig & python?
I'm going to make python wrapper using swig.
I have some classes and types in c++ dll.

```<code>class Image
{
public:
    Image(const Image&);
    Image& operator= (const Image&);
    ~Image();

    unsigned int width() const;
    unsigned int height() const;
};
struct Property
{
    std::string path;
    std::string datetime;
};
typedef std::pair<Image, Property> MyImage;
class Manage
{
public:
    Manage();
    ~Manage();
    void addMyImage(MyImage img);
    MyImage getMyImage(int index);
};
</code>```

I made swig interface file following this:

```<code>%include "std_pair.i"
%template(MyImage) std::pair<Image, Property>;
class Image
{
public:
    Image(const Image&);
    ~Image();

    unsigned int width() const;
    unsigned int height() const;
};
class Manage
{
public:
    Manage();
    ~Manage();

    void addMyImage(std::pair<Image, Property> img);
    std::pair<Image, Property> getMyImage(int index);
};
</code>```

I run command swig -c++ -python Test.swig.

I compile Test_wrapper.cxx in Visual Studio, It occurs error following this:

error C2512: 'Image' : no appropriate default constructor available

So I tried with swig -c++ -python -nodefaultctor Test.swig.
But it was same.

============UPDATE============

The problem is std::pair<Image, Property>. When pair create, it calls the constructor of arguments. Image has no default constructor. So erorr occurs.

How can I fix it?
Thanks.

答:
I finally figured out a way to make this work. Firstly, since you've got pass-by-value semantics for addMyImage and getMyImage you need to use %feature("valuewrapper") to turn on pass-by-value wrapping transformation in the generated code otherwise you'll get default constructed pairs in the generated code.

Secondly you need to prevent SWIG from exposing the std::pair constructor that takes no arguments. (This I think is different to the %nodefaultctor directive because one such constructor is explicitly written and not simply assumed to exist). It took me a long time to realise the correct syntax for the easiest(?) way do do this which I believe is using advanced renaming.

So you need to add two lines before your %include <std_pair.i> directive:

```<code>%feature("valuewrapper") std::pair<Image,Property>;
%rename("$ignore",$isconstructor,fullname=1) "std::pair<(Image,Property)>";
%include "std_pair.i"
</code>```

This does however disable all the constructors in std::pair<Image,Property>.

Body:
I'm going to make python wrapper using swig.
I have some classes and types in c++ dll.

class Image
{
public:
    Image(const Image&);
    Image& operator= (const Image&);
    ~Image();

    unsigned int width() const;
    unsigned int height() const;
};
struct Property
{
    std::string path;
    std::string datetime;
};
typedef std::pair<Image, Property> MyImage;
class Manage
{
public:
    Manage();
    ~Manage();
    void addMyImage(MyImage img);
    MyImage getMyImage(int index);
};

I made swig interface file following this:

%include "std_pair.i"
%template(MyImage) std::pair<Image, Property>;
class Image
{
public:
    Image(const Image&);
    ~Image();

    unsigned int width() const;
    unsigned int height() const;
};
class Manage
{
public:
    Manage();
    ~Manage();

    void addMyImage(std::pair<Image, Property> img);
    std::pair<Image, Property> getMyImage(int index);
};

I run command swig -c++ -python Test.swig.

I compile Test_wrapper.cxx in Visual Studio, It occurs error following this:

error C2512: 'Image' : no appropriate default constructor available

So I tried with swig -c++ -python -nodefaultctor Test.swig.
But it was same.

============UPDATE============

The problem is std::pair<Image, Property>. When pair create, it calls the constructor of arguments. Image has no default constructor. So erorr occurs.

How can I fix it?
Thanks.

Body:
I finally figured out a way to make this work. Firstly, since you've got pass-by-value semantics for addMyImage and getMyImage you need to use %feature("valuewrapper") to turn on pass-by-value wrapping transformation in the generated code otherwise you'll get default constructed pairs in the generated code.

Secondly you need to prevent SWIG from exposing the std::pair constructor that takes no arguments. (This I think is different to the %nodefaultctor directive because one such constructor is explicitly written and not simply assumed to exist). It took me a long time to realise the correct syntax for the easiest(?) way do do this which I believe is using advanced renaming.

So you need to add two lines before your %include <std_pair.i> directive:

%feature("valuewrapper") std::pair<Image,Property>;
%rename("$ignore",$isconstructor,fullname=1) "std::pair<(Image,Property)>";
%include "std_pair.i"

This does however disable all the constructors in std::pair<Image,Property>.


问:
How to make a secure php image uploader?
I am making a PHP image uploader using the Zend Framework which will upload images to a public directory for people to be able to freely access.

I have so far implemented these measures for security:
- File size validation
- Extension validation
- MimeType validation
- Upon successful validation file is renamed with a image extension in a public folder, i.e. /images/uploads/...

Is this enough security? Can't run it through some antivirus script can you (is this required)?

答:
you shouldnt be saving your uploads in the public folder at all!
you should save them in a private directory, and use a view helper to load the images for you</p>