def _crawled_activity_blocks(url, activity): title = None if 'og:title' in activity: title = activity['og:title'] elif 'twitter:title' not in activity: title = activity['twitter:title'] description = None if 'og:description' in activity: description = activity['og:description'] elif 'twitter:description' in activity: description = activity['twitter:description'] image_url = None if 'og:image' in activity: image_url = activity['og:image'] elif 'twitter:image' not in activity: image_url = activity['twitter:image'] blocks = [{ "type": "section", "text": { "type": "mrkdwn", "text": f"<{url}|*{title}*>\n{description}" }, "accessory": { "type": "image", "image_url": image_url, "alt_text": "activity image", }, }] fields = [] if 'fitness:distance:value' in activity: distance = guess( activity['fitness:distance:value'], activity['fitness:distance:units'], [Distance], ) fields.append({ "type": "mrkdwn", "text": "*Distance:* %smi" % round(distance.mi, 2), }) if 'fitness:speed:value' in activity: average_speed = guess( activity['fitness:speed:value'], activity['fitness:speed:units'].replace('/', '__'), [Speed], ) fields.append({ "type": "mrkdwn", "text": "*Speed:* %smph" % round(average_speed.mph, 0), }) if fields: blocks.append({"type": "divider"}) blocks.append({"type": "section", "fields": fields}) return blocks
def process_measurement_string(incoming_string): """Process an incoming measurement string into its constituent parts. Returns a dictionary having a subset of the following keys: * `measurement`: An instance of a subclass of `measurement.base.MeasureBase`. * `reference`: The name used for referencing an existing stored measurement. * `identity`: The name to _store_ this value as for later use. * `conversion_unit`: The unit to convert an incoming unit into. :type incoming_kstring: unicode :rtype: dict """ processed = {} if ' in ' in incoming_string: incoming_string, raw_conversion_unit = incoming_string.split(' in ') processed['conversion_unit'] = raw_conversion_unit.strip() if ' as ' in incoming_string: incoming_string, raw_identity = incoming_string.split(' as ') processed['identity'] = raw_identity.strip() is_measurement = False extractor = re.compile(r'(?P<numeric>[0-9e,.-]+)(?P<unit>.*)') extractor_match = extractor.match(incoming_string) if extractor_match: extractor_result = extractor_match.groupdict() # Get the float value of the measurement try: value = float( re.compile(r'[^\de.-]+').sub('', extractor_result['numeric']) ) is_measurement = True except ValueError: pass if is_measurement: # `value` and `extractor_match` remain available from the above block # Get the number of significant digits digit_count_string = extractor_result['numeric'] if 'e' in digit_count_string: digit_count_string = ( digit_count_string[0:digit_count_string.find('e')] ) processed['digit_count'] = len( re.compile(r'\d').findall(digit_count_string) ) unit = extractor_result['unit'].strip() # Create a measurement object using the unit and value processed['measurement'] = guess(value, unit) else: processed['reference'] = incoming_string.strip() return processed
def test_guess_distance(self): result = guess(30, 'mi') self.assertEqual( result, Distance(mi=30) )
def test_guess_temperature(self): result = guess(98, 'f') self.assertEqual( result, Temperature(f=98) )
def test_guess_weight(self): result = guess(23, 'g') self.assertEqual( result, Mass(g=23) )
def parse_ingredients(ingredients): ingredient_dict = {} for ingredient in ingredients: if ingredient[2] != 'n': measurement = guess(ingredient[1], ingredient[2]) ingredient_dict[ingredient[0]] = measurement else: ingredient_dict[ingredient[0]] = ingredient[1] return ingredient_dict
def productoToListProductos(id_producto: str, cantidad: int, unidad: str = 'u', dic_productos: dict = {}): id_producto = str(id_producto) cantidad = int(cantidad) unidad = str(unidad) # Opcion A. El producto ya está en la lista. if id_producto in dic_productos.keys(): dic_productos[id_producto] += guess( cantidad, unidad, MAGNITUDES ) # Siempre que las magnitudes sean compatibles, la suma no fallará else: # Opción B. El producto no está en la lista. dic_productos = { **dic_productos, id_producto: guess(cantidad, unidad, MAGNITUDES) } return dic_productos
def convert_units(value,from_units, to_units="nm",measures=None,debug=False): try: to_units = to_units.replace("\u00b5","u") from_units = from_units.replace("\u00b5","u") m = guess(value, from_units) xp='m.' + to_units return (eval(xp)) except Exception as err: if debug: print(value,from_units,to_units) print(err) return None
def filter_by_distance( self, latitude: float, longitude: float, distance: float, unit: str = "km" ) -> StationsResult: """ Wrapper for get_nearby_stations_by_distance using the given parameter set. Returns nearest stations defined by distance (km). :param latitude: latitude in degrees :param longitude: longitude in degrees :param distance: distance (km) for which stations will be selected :param unit: unit string for conversion :return: pandas.DataFrame with station information for the selected stations """ distance = float(distance) # Theoretically a distance of 0 km is possible if distance < 0: raise ValueError("'distance' has to be at least 0.0") unit = unit.strip() distance_in_km = guess(distance, unit, [Distance]).km # TODO: replace the repeating call to self.all() all_nearby_stations = self.filter_by_rank( latitude, longitude, self.all().df.shape[0] ).df df = all_nearby_stations[ all_nearby_stations[Columns.DISTANCE.value] <= distance_in_km ] if df.empty: log.warning( f"No weather stations were found for coordinate " f"{latitude}°N and {longitude}°E and distance {distance_in_km}km" ) result = StationsResult(stations=self, df=df.reset_index(drop=True)) return result
def time_format(x): value = x['_CONDITION_exposure_time_d'] unit = x['_CONDITION_exposure_time_UNIT_s'] if unit=="_": return None try: if unit.strip()=="h": unit="hour" elif unit=="min after administration": unit="min" elif unit=="mont hs": unit = "day" value = 30*value elif unit=="week": unit= "day" value = 7* value elif unit=="d": unit="day" msmt = guess(value,unit) return msmt.min except Exception as err: print("{} {} {}".format(value,unit,err)) return None
async def on_message(self, message): if message.author.bot or "http" in message.content: return if not self.bot.production: return matches = self._get_matches(message.content.lower()) if len(matches): measurements = [] currencies = {} timezones = {} for match in matches: unit, value, type = match["unit"], match["value"], match["type"] if type == "currency": currencies[(pycountry.currencies.get(alpha_3 = unit.upper()))] = value elif type == "measurement": measurements.append(guess(value, unit, measures = self.measures)) elif type == "timezone": timezones[pytz.timezone(unit)] = value embed = await self.convert(message, currencies, measurements, timezones) if embed is not None: asyncio.gather(message.channel.send(embed = embed))
def test_guess_distance(): assert guess(30, "mi") == Distance(mi=30)
def test_guess_temperature(): assert guess(98, "°F") == Temperature(fahrenheit=98)
def test_guess__raise__value_error(): with pytest.raises(ValueError) as e: guess(98, "does-not-exist") assert str(e.value) == "can't guess measure for '98 does-not-exist'"
def test_guess_weight(): assert guess(23, "g") == Mass(g=23)
def get_quantity(self): if self.measurement_unit: return guess(self.quantity, self.measurement_unit) return self.quantity
def condense_ingredients(ingredients, ingredient, modified_ingredients, steps, replacement): """Given a tentative replacement during a transformation process, checks to ensure that the ingredient has not already been used. If it has, will condense the two to prevent duplication. """ condense = None ambiguous = None # Check if this ingredient is already in the list of modified ingredients for m_key, mod in modified_ingredients.items(): if mod[4] == replacement: condense = m_key break # If not, check if it's in the list of original ingredients if condense is None: for i_key, i in ingredients.items(): if replacement in i[4]: condense = i_key ambiguous = i_key modified_ingredients[ambiguous] = (ingredients[ambiguous][0], ingredients[ambiguous][1], ingredients[ambiguous][2], ingredients[ambiguous][3], ingredients[ambiguous][4], 1) break # If we indeed found a previous mention, make sure they're both always used in the same steps for step in steps: if (condense in step.ingredients) != (ingredient in step.ingredients): condense = None break # We need to condense the current ingredient into a previous one if condense is not None: amt1 = modified_ingredients[condense][0] if modified_ingredients[ condense][0] is not None else 0 unit1 = modified_ingredients[condense][1] amt2 = ingredients[ingredient][0] if ingredients[ingredient][ 0] is not None else 0 unit2 = ingredients[ingredient][1] sum = amt1 + amt2 sum_unit = unit1 if unit2 == '': unit2 = unit1 # Attempt unit conversion to add the ingredients together if unit1 != unit2: if unit1[-1] == 's': unit1 = unit1[:-1] if unit2[-1] == 's': unit2 = unit2[:-1] if unit1 == 'fluid ounce': unit1 = 'us_oz' if unit2 == 'fluid ounce': unit2 = 'us_oz' m = None try: m = guess(float(amt1), unit1, measures=[Weight, Volume]) except Exception as e1: try: m = guess(float(amt1), 'us_' + unit1, measures=[Weight, Volume]) except Exception as e2: pass s = None try: s = guess(float(amt2), unit2, measures=[Weight, Volume]) except Exception as e1: try: s = guess(float(amt2), 'us_' + unit2, measures=[Weight, Volume]) except Exception as e2: pass if m is not None and s is not None: type1 = None type2 = None try: m.oz type1 = 'weight' except Exception as e: type1 = 'volume' try: s.oz type2 = 'weight' except Exception as e: type2 = 'volume' if type1 == type2 == 'weight': sum_unit = 'oz' sum = m.oz + s.oz elif type1 == type2 == 'volume': sum_unit = 'fl oz' sum = m.us_oz + s.us_oz elif type1 == 'weight' and type2 == 'volume': sum_unit = 'ounces' sum = m.oz + s.us_oz elif type1 == 'volume' and type2 == 'weight': sum_unit = 'ounces' sum = m.us_oz + s.oz modified_ingredients[condense] = (sum, sum_unit, '', '', modified_ingredients[condense][4], 1) modified_ingredients[ingredient] = (-1, None, None, None, condense, 1) # We can just go ahead and add this new ingredient else: modified_ingredients[ingredient] = (ingredients[ingredient][0], ingredients[ingredient][1], '', '', replacement, 1) return modified_ingredients
def convert_weight_to_oz(weight, unit): weight = guess(weight, unit) return weight.oz
def __init__(self, areaParams, floorHeightParams): self.areaParams = guess(areaParams['areaValue'], areaParams['areaUnit']) self.floorHeightParams = guess(floorHeightParams['heightValue'], floorHeightParams['heightUnit']) super().__init__()