def set_from_unit(self, txt): if not self.ingkey: return if txt: self.fromUnitLabel.set_text(txt) self.fromUnitComboBoxEntry.get_children()[0].set_text(txt) self.fromUnit = txt curamt = ' '.join([ convert.float_to_frac(self.amount, fractions=convert.FRACTIONS_ASCII), self.fromUnit, self.ingkey ]) else: self.fromUnitLabel.set_text(self.ingkey + ' (no unit)') self.fromUnit = '' curamt = convert.float_to_frac( self.amount, fractions=convert.FRACTIONS_ASCII) + ' ' + self.ingkey self.convertUnitLabel.set_markup( '<span weight="bold" size="larger">' + \ _('Convert unit for %s')%self.ingkey + \ '</span>' + \ '\n<i>' + \ _('In order to calculate nutritional information, Gourmet needs you to help it convert "%s" into a unit it understands.')%curamt + \ '</i>')
def convert (self, amt1, unit1, unit2): density=None #if self.useDensityCheckButton.get_active(): density=self.densitySpinButton.get_value() if density <= 0 or not self.expander1.get_expanded(): density = None conversion = self.conv.convert_fancy(unit1, unit2, density=density) message = "" if conversion: amt2 = amt1 * conversion if amt2 < (0.05): retAmt = "%1.3e"%amt2 else: retAmt = convert.float_to_frac(amt2) result = "%s %s = <b>%s</b> %s"%(convert.float_to_frac(amt1), unit1, retAmt, unit2) else: result = _("Cannot convert %s to %s")%(unit1,unit2) if not density: message= _("Need density information.") if not self.expander1.get_expanded(): self.expander1.set_expanded(True) self.changed() self.itemComboBox.activate() self.resultLabel.set_text(result) self.resultLabel.set_use_markup(True) self.resultLabel.set_line_wrap(True) self.messageLabel.set_text("<i>%s</i>"%message) self.messageLabel.set_use_markup(True)
def _grab_attr_(self, obj, attr): # This is a bit ugly -- we allow exporting categories as if # they were a single attribute even though we in fact allow # multiple categories. if attr == 'category': return ', '.join(self.rd.get_cats(obj)) try: ret = getattr(obj, attr) except: return None else: if attr in ['preptime', 'cooktime']: # this 'if' ought to be unnecessary, but is kept around # for db converting purposes -- e.g. so we can properly # export an old DB if ret and not isinstance(ret, str): ret = convert.seconds_to_timestring( ret, fractions=self.fractions) elif attr == 'rating' and ret and not isinstance(ret, str): if ret / 2 == ret / 2.0: ret = "%s/5 %s" % (ret / 2, _('stars')) else: ret = "%s/5 %s" % (ret / 2.0, _('stars')) elif attr == 'servings' and not isinstance(ret, str): ret = convert.float_to_frac(ret, fractions=self.fractions) elif attr == 'yields': ret = convert.float_to_frac(ret, fractions=self.fractions) yield_unit = self._grab_attr_(obj, 'yield_unit') if yield_unit: ret = '%s %s' % ( ret, yield_unit ) # FIXME: i18n? (fix also below in exporter_mult) return ret
def convert(self, amt1, unit1, unit2): density = None #if self.useDensityCheckButton.get_active(): density = self.densitySpinButton.get_value() if density <= 0 or not self.expander1.get_expanded(): density = None conversion = self.conv.convert_fancy(unit1, unit2, density=density) message = "" if conversion: amt2 = amt1 * conversion if amt2 < (0.05): retAmt = "%1.3e" % amt2 else: retAmt = convert.float_to_frac(amt2) result = "%s %s = <b>%s</b> %s" % (convert.float_to_frac(amt1), unit1, retAmt, unit2) else: result = _("Cannot convert %s to %s") % (unit1, unit2) if not density: message = _("Need density information.") if not self.expander1.get_expanded(): self.expander1.set_expanded(True) self.changed() self.itemComboBox.activate() self.resultLabel.set_text(result) self.resultLabel.set_use_markup(True) self.resultLabel.set_line_wrap(True) self.messageLabel.set_text("<i>%s</i>" % message) self.messageLabel.set_use_markup(True)
def edit_units(self, amount, unit, ingkey, indx=None): self.set_ingkey(ingkey) self.set_from_unit(unit) if indx is not None: self.amount_index = indx self.fromAmountEntry.set_text( convert.float_to_frac(amount, fractions=convert.FRACTIONS_ASCII)) self.toAmountEntry.set_text( convert.float_to_frac(amount, fractions=convert.FRACTIONS_ASCII)) self.goto_page_unit_convert()
def edit_units (self, amount, unit, ingkey, indx=None): self.set_ingkey(ingkey) self.set_from_unit(unit) if indx is not None: self.amount_index = indx self.fromAmountEntry.set_text(convert.float_to_frac(amount, fractions=convert.FRACTIONS_ASCII) ) self.toAmountEntry.set_text(convert.float_to_frac(amount, fractions=convert.FRACTIONS_ASCII) ) self.goto_page_unit_convert()
def _format_amount_string_from_amount (self, amt, fractions=convert.FRACTIONS_ALL): """Format our amount string given an amount tuple. If you're thinking of using this function from outside, you should probably just use a convenience function like get_amount_as_string or get_amount_and_unit """ if type(amt)==tuple: return "%s-%s"%(convert.float_to_frac(amt[0],fractions=fractions).strip(), convert.float_to_frac(amt[1],fractions=fractions).strip()) elif type(amt)==float: return convert.float_to_frac(amt,fractions=fractions) else: return ""
def set_value(self, n): if type(n) == tuple: if len(n) == 1: n = n[0] if len(n) > 2: raise ValueError else: self.set_text( convert.float_to_frac(n[0], fractions=convert.FRACTIONS_ASCII) + " - " + convert.float_to_frac(n[1], fractions=convert.FRACTIONS_ASCII) ) return NumberEntry.set_value(self, n)
def write_ing (self, amount="1", unit=None, item=None, key=None, optional=False): if type(amount)==type(1.0) or type(amount)==type(1): amount = convert.float_to_frac(amount) if not amount: amount = "" if not unit: unit = "" unit_bad = False if len(unit) > 2 or '.' in unit: unit_bad = True # Try to fix the unit if self.conv.unit_dict.has_key(unit): new_u = self.conv.unit_dict[unit] if len(new_u) <= 2 and not '.' in new_u: unit = new_u; unit_bad = False else: if self.uc.has_key(new_u): unit = self.uc[new_u]; unit_bad = False if unit_bad: # If we couldn't fix the unit... we add it to # the item if unit: item="%s %s"%(unit,item) unit="" if len(unit)>self.ulen: self.ulen=len(unit) if len(amount)>self.amtlen: self.amtlen=len(amount) #print "DEBUG: %s length %s"%(amount,self.amtlen) # we hold off writing ings until we know the lengths # of strings since we need to write out neat columns if optional: item="%s (optional)"%item self.ings.append([amount,unit,item])
def set_value (self, n): if type(n)==tuple: if len(n)==1: n = n[0] if len(n)>2: raise ValueError else: self.set_text( convert.float_to_frac(n[0], fractions=convert.FRACTIONS_ASCII)\ +' - '+\ convert.float_to_frac(n[1], fractions=convert.FRACTIONS_ASCII) ) return NumberEntry.set_value(self,n)
def check_attrs (self): self.txt = self.txt.decode('utf-8') for attr in ['title','cuisine', 'source','link']: if getattr(self.rec,attr): assert re.search('<%(attr)s>\s*%(val)s\s*</%(attr)s>'%{ 'attr':attr, 'val':getattr(self.rec,attr) }, self.txt), \ 'Did not find %s value %s'%(attr,getattr(self.rec,attr)) if self.rec.yields: assert re.search('<yields>\s*%s\s*%s\s*</yields>'%( self.rec.yields, self.rec.yield_unit), self.txt) or \ re.search('<yields>\s*%s\s*%s\s*</yields>'%( float_to_frac(self.rec.yields), self.rec.yield_unit), self.txt), \ 'Did not find yields value %s %s'%(self.rec.yields, self.rec.yield_unit) for att in ['preptime','cooktime']: if getattr(self.rec,att): tstr = seconds_to_timestring(getattr(self.rec,att)) assert re.search('<%(att)s>\s*%(tstr)s\s*</%(att)s>'%locals(),self.txt),\ 'Did not find %s value %s'%(att,tstr)
def info_edit_equivalent (self, button, eq): """Edit equivalents callback. eq is a nutalias DB object. """ self.amounts[self.ingkey] = {} self.amount = 1 self.ingkey = self.info_nutalias.ingkey self.set_from_unit(eq.unit) self.fromAmountEntry.set_text('1') conv = self.nd.get_conversion_for_amt(1,eq.unit,self.info_nutalias.ingkey) amt_in_grams = conv * 100 self.setup_to_units() to_unit = cb.cb_set_active_text(self.toUnitCombo,'g') self.toAmountEntry.set_text(convert.float_to_frac(amt_in_grams, fractions=convert.FRACTIONS_ASCII )) # Hack to avoid adding ourselves to the path on a "back" event # -- if button is None, then we know we were called # artificially from previous_page_cb (not from a button press # event) if button: self.path.append( (self.info_edit_equivalent, [None,eq]) ) self.goto_page_unit_convert()
def prettynumber(value, fractions=convert.FRACTIONS_NORMAL): """ Return a pretty-printed, human number. >>> prettynumber(1.5) u'1 \\xbd' >>> prettynumber(2) '2' >>> prettynumber(2999) '2999' >>> prettynumber(0.25) u'\\xbc' """ try: intv = int(value) floatv = float(value) except ValueError: # Non-numeric return value remainder = floatv - intv if remainder == 0: return '%d' % intv else: return convert.float_to_frac(n=floatv, fractions=fractions)
def check_attrs(self): self.txt = self.txt.decode('utf-8') for attr in ['title', 'cuisine', 'source', 'link']: if getattr(self.rec, attr): assert re.search('<%(attr)s>\s*%(val)s\s*</%(attr)s>'%{ 'attr':attr, 'val':getattr(self.rec,attr) }, self.txt), \ 'Did not find %s value %s'%(attr,getattr(self.rec,attr)) if self.rec.yields: assert re.search('<yields>\s*%s\s*%s\s*</yields>'%( self.rec.yields, self.rec.yield_unit), self.txt) or \ re.search('<yields>\s*%s\s*%s\s*</yields>'%( float_to_frac(self.rec.yields), self.rec.yield_unit), self.txt), \ 'Did not find yields value %s %s'%(self.rec.yields, self.rec.yield_unit) for att in ['preptime', 'cooktime']: if getattr(self.rec, att): tstr = seconds_to_timestring(getattr(self.rec, att)) assert re.search('<%(att)s>\s*%(tstr)s\s*</%(att)s>'%locals(),self.txt),\ 'Did not find %s value %s'%(att,tstr)
def _format_amount_string_from_amount(self, amt, fractions=convert.FRACTIONS_ALL): """Format our amount string given an amount tuple. If you're thinking of using this function from outside, you should probably just use a convenience function like get_amount_as_string or get_amount_and_unit """ if type(amt) == tuple: return "%s-%s" % ( convert.float_to_frac(amt[0], fractions=fractions).strip(), convert.float_to_frac(amt[1], fractions=fractions).strip()) elif type(amt) == float: return convert.float_to_frac(amt, fractions=fractions) else: return ""
def set_value (self, n): if self.default_to_fractions: self.set_text(convert.float_to_frac(n,fractions=convert.FRACTIONS_ASCII)) else: if self.decimals >= 0: decimals = self.decimals while n < 10**-decimals: decimals += 1 format_string = "%" +"." + "%i"%decimals + "f" self.set_text(format_string%n) else: self.set_text("%s"%n)
def set_value(self, number: int): if self.default_to_fractions: self.set_text(float_to_frac(number, fractions=FRACTIONS_ASCII)) else: if self.decimals >= 0: decimals = self.decimals while number < 10**-decimals: decimals += 1 format_string = "%" + "." + "%i" % decimals + "f" self.set_text(format_string % number) else: self.set_text(str(number))
def write_ing (self, amount=1, unit=None, item=None, key=None, optional=False): ing_txt='' if type(amount)==type(1.0) or type(amount)==type(1): amount = convert.float_to_frac(amount) ing_txt = ing_txt + amount if unit: ing_txt = ing_txt + ' ' + unit if item: ing_txt = ing_txt + ' ' + item ing_el = self.create_text_element('li',ing_txt) self.inglist_el.appendChild(ing_el)
def write_ing (self, amount=1, unit=None, item=None, key=None, optional=False): ing_txt='' if isinstance(amount, (float, int)): amount = convert.float_to_frac(amount) ing_txt = ing_txt + amount if unit: ing_txt = ing_txt + ' ' + unit if item: ing_txt = ing_txt + ' ' + item ing_el = self.create_text_element('li',ing_txt) self.inglist_el.appendChild(ing_el)
def set_from_unit (self, txt): if not self.ingkey: return if txt: self.fromUnitLabel.set_text(txt) self.fromUnitComboBoxEntry.get_children()[0].set_text(txt) self.fromUnit = txt curamt = ' '.join([convert.float_to_frac(self.amount, fractions=convert.FRACTIONS_ASCII), self.fromUnit,self.ingkey]) else: self.fromUnitLabel.set_text(self.ingkey+' (no unit)') self.fromUnit = '' curamt = convert.float_to_frac( self.amount, fractions=convert.FRACTIONS_ASCII)+' '+self.ingkey self.convertUnitLabel.set_markup( '<span weight="bold" size="larger">' + \ _('Convert unit for %s')%self.ingkey + \ '</span>' + \ '\n<i>' + \ _('In order to calculate nutritional information, Gourmet needs you to help it convert "%s" into a unit it understands.')%curamt + \ '</i>')
def _grab_attr_(self, obj, attr): # This is a bit ugly -- we allow exporting categories as if # they were a single attribute even though we in fact allow # multiple categories. if attr == "category": return ", ".join(self.rd.get_cats(obj)) try: ret = getattr(obj, attr) except: return None else: if attr in ["preptime", "cooktime"]: # this 'if' ought to be unnecessary, but is kept around # for db converting purposes -- e.g. so we can properly # export an old DB if ret and type(ret) != str: ret = convert.seconds_to_timestring(ret, fractions=self.fractions) elif attr == "rating" and ret and type(ret) != str: if ret / 2 == ret / 2.0: ret = "%s/5 %s" % (ret / 2, _("stars")) else: ret = "%s/5 %s" % (ret / 2.0, _("stars")) elif attr == "servings" and type(ret) != str: ret = convert.float_to_frac(ret, fractions=self.fractions) elif attr == "yields": ret = convert.float_to_frac(ret, fractions=self.fractions) yield_unit = self._grab_attr_(obj, "yield_unit") if yield_unit: ret = "%s %s" % (ret, yield_unit) # FIXME: i18n? (fix also below in exporter_mult) if type(ret) in [str, unicode] and attr not in ["thumb", "image"]: try: ret = ret.encode(self.DEFAULT_ENCODING) except: print "oops:", ret, "doesn't look like unicode." raise return ret
def grab_attr(self, ing, name): if name in gglobals.ING_ATTRS.keys(): attval = getattr(ing, name) if name in self.numerics: return convert.float_to_frac(attval) else: return attval elif name == 'USDA': nutrow = self.nd.get_nutinfo(ing.ingkey) if nutrow: return nutrow.desc else: return None elif name == 'grams': #nutrow=self.nd.get_nutinfo(ing.ingkey) #densities,extra_units=self.nd.get_conversions(nutrow) amt = self.nd.get_conversion_for_amt(ing.amount, ing.unit, ing.ingkey) if amt: return 100 * amt else: return 0
def write_ing (self, amount="1", unit=None, item=None, key=None, optional=False): if type(amount)==type(1.0) or type(amount)==type(1): amount = convert.float_to_frac(amount) if not amount: amount = "" if self.conv.unit_dict.has_key(unit) and self.uc.has_key(self.conv.unit_dict[unit]): unit=self.uc[self.conv.unit_dict[unit]] or "" else: # if we don't recognize the unit, we add it to # the item if unit: item="%s %s"%(unit,item) unit="" if len(unit)>self.ulen: self.ulen=len(unit) if len(amount)>self.amtlen: self.amtlen=len(amount) #print "DEBUG: %s length %s"%(amount,self.amtlen) # we hold off writing ings until we know the lengths # of strings since we need to write out neat columns if optional: item="%s (optional)"%item self.ings.append([amount,unit,item])
def check_attrs(self): self.txt = self.txt.decode("utf-8") for attr in ["title", "cuisine", "source", "link"]: if getattr(self.rec, attr): assert re.search( "<%(attr)s>\s*%(val)s\s*</%(attr)s>" % {"attr": attr, "val": getattr(self.rec, attr)}, self.txt ), "Did not find %s value %s" % (attr, getattr(self.rec, attr)) if self.rec.yields: assert re.search( "<yields>\s*%s\s*%s\s*</yields>" % (self.rec.yields, self.rec.yield_unit), self.txt ) or re.search( "<yields>\s*%s\s*%s\s*</yields>" % (float_to_frac(self.rec.yields), self.rec.yield_unit), self.txt ), ( "Did not find yields value %s %s" % (self.rec.yields, self.rec.yield_unit) ) for att in ["preptime", "cooktime"]: if getattr(self.rec, att): tstr = seconds_to_timestring(getattr(self.rec, att)) assert re.search( "<%(att)s>\s*%(tstr)s\s*</%(att)s>" % locals(), self.txt ), "Did not find %s value %s" % (att, tstr)
def grab_attr (self, ing, name): if name in gglobals.ING_ATTRS.keys(): attval = getattr(ing,name) if name in self.numerics: return convert.float_to_frac(attval) else: return attval elif name=='USDA': nutrow=self.nd.get_nutinfo(ing.ingkey) if nutrow: return nutrow.desc else: return None elif name=='grams': #nutrow=self.nd.get_nutinfo(ing.ingkey) #densities,extra_units=self.nd.get_conversions(nutrow) amt = self.nd.get_conversion_for_amt(ing.amount, ing.unit, ing.ingkey ) if amt: return 100 * amt else: return 0
def _grab_attr_(self, obj, attr): """Grab attribute attr of obj obj. Possibly manipulate the attribute we get to hand out export something readable. """ if attr == "servings" or attr == "yields" and self.mult: ret = getattr(obj, attr) if type(ret) in [int, float]: fl_ret = float(ret) else: if ret is not None: print "WARNING: IGNORING serving value ", ret fl_ret = None if fl_ret: ret = convert.float_to_frac(fl_ret * self.mult, fractions=self.fractions) if attr == "yields": yield_unit = self._grab_attr_(obj, "yield_unit") if yield_unit: ret = "%s %s" % (ret, yield_unit) # FIXME: i18n? return ret else: return exporter._grab_attr_(self, obj, attr)
def _grab_attr_(self, obj, attr): """Grab attribute attr of obj obj. Possibly manipulate the attribute we get to hand out export something readable. """ if attr == 'servings' or attr == 'yields' and self.mult: ret = getattr(obj, attr) if isinstance(ret, (int, float)): fl_ret = float(ret) else: if ret is not None: print('WARNING: IGNORING serving value ', ret) fl_ret = None if fl_ret: ret = convert.float_to_frac(fl_ret * self.mult, fractions=self.fractions) if attr == 'yields': yield_unit = self._grab_attr_(obj, 'yield_unit') if yield_unit: ret = '%s %s' % (ret, yield_unit) # FIXME: i18n? return ret else: return exporter._grab_attr_(self, obj, attr)
def testFractionGenerator(self): for d in [2, 3, 4, 5, 6, 8, 10, 16]: self.assertEqual( convert.float_to_frac(1.0 / d, fractions=convert.FRACTIONS_ASCII), ('1/%s' % d))