Currency symbol position - web-services

In my program I have to display prices for different countries. To do this, I generate a special formatting class for each country (using open web services):
public class Country
{
...
// autogenerated with T4
public static readonly List<Country> Countries = new List<Country>
{
new Country
{
CountryCode = "us",
CallingCode = "1",
CountryName = "United States",
CountryCodeNumeric = "840",
CountryCodeA3 = "usa",
CurrencySymbol = "$",
Continent = "NA",
ContinentName = "North America",
Capital = "Washington",
CurrencyCode = "USD",
...
},
...
But I also need currency symbol location to display prices properly. For example: I can place currency symbol before or after the price: 8.40 € and € 8.40.
Is there any web service or another reliable source, which I can use to get currency symbol positions?

Related

Better way to do the django api response

I have tried to create a model to represent a situation like this.
each question row can have a multiple question column. there are multiple types of question column
class QuestionRow(models.Model):
report_question = models.CharField(max_length=200)
report_group = models.CharField(max_length=20)
class QuestionColumn(models.Model):
header_text = models.CharField(max_length=100)
data_type = models.CharField(max_length=10)
class QuestionItem(models.Model):
column = models.ForeignKey(QuestionColumn)
row = models.ForeignKey(QuestionRow)
My objective is to find the optimized way to query and return the response.
where each question row in question item may or may not have multiple question columns. thinking of a way to do this using django annotate, aggregate
[{
"report_group": 1,
"question_row": "1a. Alarm system not active or not sufficient?",
"question_columns" : [
{
"header_text": "Yes/No",
"data_type": "Bool"
},
{
"header_text": "Risk Score",
"data_type": ""
}
]
},
{
"report_group": 1,
"question_row": "1b. Notification system not active or inactive?",
"question_columns" : [
{
"header_text": "Yes/No",
"data_type": "Bool"
},
{
"header_text": "Risk Score",
"data_type": ""
}
]
}]

How to display all dates for multiple model annotations in django

So I'm working on a website, and I want to have some kind of a summary page to display the data that I have. Let's say I have these models:
class IceCream(TimeStampedModel):
name = models.CharField()
color = models.CharField()
class Cupcake(TimeStampedModel):
name = models.CharField()
icing = models.CharField()
So on this page, users will be able to input a date range for the summary. I'm using DRF to serialize the data and to display them on the view actions. After I receive the filter dates, I will filter out the IceCream objects and Cupcake objects using the created field from TimeStampedModel.
#action(detail=False, methods=['get'])
def dessert_summary(self, request, **kwargs):
start_date = self.request.query_params.get('start_date')
end_date = self.request.query_params.get('end_date')
cupcakes = Cupcake.objects.filter(created__date__range=[start_date, end_date])
ice_creams = IceCream.objects.filter(created__date__range=[start_date, end_date])
After filtering, I want to count the total cupcakes and the total ice creams that is created within that period of time. But I also want to group them by the dates, and display the total count for both ice creams and cupcakes based on that date. So I tried to annotate the querysets like this:
cupcakes = cupcakes.annotate(date=TruncDate('created'))
cupcakes = cupcakes.values('date')
cupcakes = cupcakes.annotate(total_cupcakes=Count('id'))
ice_creams = ice_creams.annotate(date=TruncDate('created'))
ice_creams = ice_creams.values('date')
ice_creams = ice_creams.annotate(total_ice_creams=Count('id'))
So I want the result to be something like this:
{
'summary': [{
'date': "2020-09-24",
'total_ice_creams': 10,
'total_cupcakes': 7,
'total_dessert': 17
}, {
'date': "2020-09-25',
'total_ice_creams': 6,
'total_cupcakes': 5,
'total_dessert': 11
}]
}
But right now this is what I am getting:
{
'summary': [{
'cupcakes': [{
'date': "2020-09-24",
'total_cupcakes': 10,
}, {
'date': "2020-09-25",
'total_cupcakes': 5,
}],
'ice_creams': [{
'date': "2020-09-24",
'total_ice_creams': 7,
}, {
'date': "2020-09-27",
'total_ice_creams': 6,
}]
}]
}
What I want to ask is how do I get all the dates of both querysets, sum the ice creams and cupcakes, and return the data like the expected result? Thanks in advance for your help!
So here's what you can do:
gather all icecream/cupcakes count data into a dictionary
icecream_dict = {obj['date']: obj['count'] for obj in ice_creams}
cupcakes_dict = {obj['date']: obj['count'] for obj in cupcakes}
create a sorted list with all the dates
all_dates = sorted(set(list(icecream_dict.keys()) + list(cupcakes_dict.keys())))
create a list with items for each date and their count
result = []
for each_date in all_dates:
total_ice_creams = icecream_dict.get(each_date, 0)
total_cupcakes = cupcakes_dict.get(each_date, 0)
res = {
'date': each_date,
'total_ice_creams': total_ice_creams,
'total_cupcakes': total_cupcakes,
'total_dessert': total_ice_creams + total_cupcakes
}
result.append(res)
# check the result
print(result)
Hint: If you plan to add more desert-like models, consider have a base model Desert that you could query directly instead of querying each desert type model.

Why does geocoding let me choose an exact address and then once clicked show different city name?

This question concerns a variation on the Try It Yourself section on the Google Maps Place Autocomplete Address Sample, from which you can get a Fiddle with a demo API key.
The problem is I thought I had it working perfectly just now after spending two hours trying to get it to work the way I want. When I typed an address where I used to live, the autosuggest suggested my address, 82 hopkins rd, northfield, ct, then when I click the result it fills in my town as being Litchfield, CT, which is actually the larger town one town over, and also the same name of the County that Northfield is in. Google obviously knows about Northfield though it is a tiny town, because it shows the exact address I want but when I click it why would it show Litchfield? If I try some other towns, etc. I don't see this happening. I imagine there is no solution because when I tried to change:
{types: ['geocode']}); to {types: ['(cities)']}); and tried typing in Northfield, then it showed other states with the town Northfield but not Connecticut. So I guess my old town is too small for Google to care about but then why show it in the autosuggest? Strange...
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
locality: 'short_name',
administrative_area_level_1: 'short_name',
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}lat = place.geometry.location.lat();
lng = place.geometry.location.lng();
document.getElementById('lat').value = lat;
document.getElementById('lon').value = lng;
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=NOTMYREALKEYHERE&libraries=places&callback=initAutocomplete"
async defer></script>
You're seeing these results because Northfield is not a city. According to Wikipedia, Northfield, CT is "an unincorporated village in the town of Litchfield, Litchfield County, Connecticut". However, you're in luck: The example that you're viewing is using the API output address_component, where formatted_address for your place is correctly listed as 82 Hopkins Rd, Northfield, CT 06778, USA.
From the "Geocoding Address Types section" in the Google Maps Javascript API documentation, there are a wide variety of types of geocoding result. Some, like locality, require incoporation; sublocality_level_1 through sublocality_level_5 refer to areas narrower than that.
Even without your Javascript, you can do a search:
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?key=YOUR_KEY&inputtype=textquery&input=82+hopkins+rd,+northfield,+ct
...to get a place ID of ChIJZYpAVT2W54kRPnm9uVA3cpc, and then you can do a subsequent place search:
https://maps.googleapis.com/maps/api/place/details/json?key=YOUR_KEY&place_id=ChIJZYpAVT2W54kRPnm9uVA3cpc
...to reveal the different types of address component:
"address_components" : [
{
"long_name" : "82",
"short_name" : "82",
"types" : [ "street_number" ]
},
{
"long_name" : "Hopkins Road",
"short_name" : "Hopkins Rd",
"types" : [ "route" ]
},
{
"long_name" : "Northfield",
"short_name" : "Northfield",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Litchfield",
"short_name" : "Litchfield",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Litchfield",
"short_name" : "Litchfield",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Litchfield County",
"short_name" : "Litchfield County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Connecticut",
"short_name" : "CT",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "06778",
"short_name" : "06778",
"types" : [ "postal_code" ]
}
To your point, this also gives a formatted_address of 82 Hopkins Rd, Northfield, CT 06778, USA, which is what you're looking for.
In the example you quoted, which is the "try it yourself" section on the Place Autocomplete Address Form sample, there are two separate processes happening: The Autocomplete searches for your address and suggests a formatted address, and then the place details call unpacks the structured pieces of the address as needed. However, as in the code comments:
<!-- Note: Selection of address components in this example is typical.
You may need to adjust it for the locations relevant to your app. See
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
-->
Thus, by tweaking the form as I have in this Fiddle, you can see that your formatted address includes Northfield, listed as a Neighborhood, even though the city is properly Litchfield. Note that this is also location-specific behavior, as "1600 Pennsylvania Avenue, Washington DC" returns a Neighborhood of "Northwest Washington" is omitted from the formatted address.
Thus, to get the behavior you want, just use the formatted_address, or consider expanding the address_components to provide the granularity you need.

Dapper nested list query

I have 3 POCO classes as below;
Continent has many ContinentPart
Continent has many Country
Country has many City
I want to get Continens with ContinentParts, Countries and Cities
using (IDbConnection db = new SqlConnection(_conf["ConnectionStrings:WorkConStr"]))
{
string query = #"SELECT * FROM Continent as c
LEFT JOIN ContinentPart as cp ON c.ContinentId=cp.ContinentId
LEFT JOIN Country as co ON c.ContinentId=co.ContinentId
LEFT JOIN City ci ON co.CountryId=ci.CountryId
ORDER BY c.RecDate DESC";
var continentDictionary = new Dictionary<int, Continent>();
var list = db.Query<Continent, ContinentPart, Country, City, Continent>(
query,
map: (continent, continentPart, country, city) =>
{
Continent m;
if (!continentDictionary.TryGetValue(continent.ContinentId, out m))
{
continentDictionary.Add(continent.ContinentId, m = continent);
}
if (m.ContinentParts == null)
m.ContinentParts = new List<ContinentPart>();
m.ContinentParts.Add(continentPart);
if (m.Countries == null)
m.Countries = new List<Country>();
m.Countries.Add(country);
foreach (var h in m.Countries)
{
if (h.Cities == null)
h.Cities = new List<City>();
h.Cities.Add(city);
}
return m;
},
param: new { },
splitOn: "")
.Distinct()
.ToList();
return list;
}
You have two options here. You can use Multiple Resultsets feature:
https://medium.com/dapper-net/handling-multiple-resultsets-4b108a8c5172
Or, another option, better in my opinion, is to return the joined result as a JSON, for example with a query like the following:
select
continents.continent_id,
continents.continent,
countries.country_id,
countries.country,
cities.city_id,
cities.city
from
dbo.Continent continents
inner join
dbo.Country countries on continents.continent_id = countries.continent_id
inner join
dbo.City cities on countries.country_id = cities.country_id
for
json auto
that returns a JSON like this:
{
"continent_id": 1,
"continent": "Africa",
"countries":
[
{
"country_id": 1,
"country": "Nigeria",
"cities":
[
{
"city_id": 1,
"city": "Lagos"
}, {
"city_id": 2,
"city": "Abuja"
}
]
}
]
}
and that can then be turned into a complex object using Custom Type Handling:
https://medium.com/dapper-net/custom-type-handling-4b447b97c620
Links are to articles I've wrote on the subject.

How to store lists of embedded documents with MongoDB under Grails?

I'm having problem storing lists of embedded documents/objects in MongoDB using the Grails MongoDB plugin. I used the information given in the documentation in chapter 3 but only got the embedding of one object working.
For testing purposes I created two domain objects Person and Address in a new Grails project. They look like this:
class Person {
ObjectId id
String firstName
String lastName
Address address
List otherAddresses = []
static embedded = ['address', 'otherAddresses']
}
class Address {
String street
String postCode
String city
}
When I execute the following lines in Bootstrap.groovy it stores two Person objects in MongoDB - both have a correct address but in person1 the otherAddresses List is "[ null ]" and in person2 the otherAddresses List is "[ { "street" : "Second Street. 164" , "city" : "New York" , "postCode" : "13579"}]"
def address = new Address(street: "Mainstreet. 164", city: "New York", postCode:"12345")
def person1 = new Person(firstName: "John", lastName: "Doe")
person1.address = address
person1.otherAddresses.add(address)
println person1.otherAddresses // Result: "[mongoembeddedlisttest.Address : (unsaved)]"
person1.save()
person1.errors.allErrors.each { println it } // no errors
def person2 = new Person(firstName: "Jane", lastName: "Doe")
person2.otherAddresses += ['street': 'Second Street. 164', 'city': 'New York', 'postCode':'13579']
println person2.otherAddresses // Result: "[[street:Second Street. 164, city:New York, postCode:13579]]"
person2.save()
Resulting Database Entries:
{ "_id" : { "$oid" : "521089461a150b20390d61c2"} , "address" : { "city" : "New York" , "postCode" : "12345" , "street" : "Mainstreet. 164"} , "firstName" : "John" , "lastName" : "Doe" , "otherAddresses" : [ null ] , "version" : 0}
{ "_id" : { "$oid" : "521089461a150b20390d61c3"} , "firstName" : "Jane" , "lastName" : "Doe" , "otherAddresses" : [ { "street" : "Second Street. 164" , "city" : "New York" , "postCode" : "13579"}] , "version" : 0}
Further Notes:
I'm using a pure mongodb approach (no a hybrid together with Hibernate)
I'm working on a Windows 8 machine using Grails 2.2.1 running mongo db 2.4.4
Person is a domain object in /grails-app/domain and Address is a "normal" groovy class in /src/groovy (I can put it in domain folder but that has no effect)
Everything is set to be nullable in Config.groovy: grails.gorm.default.constraints = { '*'(nullable: true) }
BuildConfig.groovy has the plugin entry: compile ":mongodb:1.3.0"
What am I doing wrong? How can I store a list of embedded objects using the Grails mechanism?
I think you're adding a map in the second person instead of an Address object. Is there any reason why you're adding the otherAddress different for each person?
I think this should work although I haven't tested it:
def address = new Address(street: "Mainstreet. 164", city: "New York", postCode:"12345")
def person1 = new Person(firstName: "John", lastName: "Doe")
person1.address = address
person1.otherAddresses.add(address)
println person1.otherAddresses // Result: "[mongoembeddedlisttest.Address : (unsaved)]"
person1.save()
person1.errors.allErrors.each { println it } // no errors
def person2 = new Person(firstName: "Jane", lastName: "Doe")
person2.otherAddresses += new Address('street': 'Second Street. 164', 'city': 'New York', 'postCode':'13579')
println person2.otherAddresses
person2.save()