Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_app(self): # First see to connection stack ctx = connection_stack.top if ctx is not None: return ctx.app # Next return app from instance cache if self.app is not None: return self.app ...
[ "Get current app from Flast stack to use.\n\n This will allow to ensure which Redis connection to be used when\n accessing Redis connection public methods via plugin.\n " ]
Please provide a description of the function:def init_app(self, app, config_prefix=None): # Put redis to application extensions if 'redis' not in app.extensions: app.extensions['redis'] = {} # Which config prefix to use, custom or default one? self.config_prefix = c...
[ "\n Actual method to read redis settings from app configuration, initialize\n Redis connection and copy all public connection methods to current\n instance.\n\n :param app: :class:`flask.Flask` application instance.\n :param config_prefix: Config prefix to use. By default: ``REDIS...
Please provide a description of the function:def _build_connection_args(self, klass): bases = [base for base in klass.__bases__ if base is not object] all_args = [] for cls in [klass] + bases: try: args = inspect.getfullargspec(cls.__init__).args ...
[ "Read connection args spec, exclude self from list of possible\n\n :param klass: Redis connection class.\n " ]
Please provide a description of the function:def _include_public_methods(self, connection): for attr in dir(connection): value = getattr(connection, attr) if attr.startswith('_') or not callable(value): continue self.__dict__[attr] = self._wrap_public...
[ "Include public methods from Redis connection to current instance.\n\n :param connection: Redis connection instance.\n " ]
Please provide a description of the function:def _wrap_public_method(self, attr): def wrapper(*args, **kwargs): return getattr(self.connection, attr)(*args, **kwargs) return wrapper
[ "\n Ensure that plugin will call current connection method when accessing\n as ``plugin.<public_method>(*args, **kwargs)``.\n " ]
Please provide a description of the function:def prepare(self): '''Prepare to run the docker command''' self.__make_scubadir() if self.is_remote_docker: ''' Docker is running remotely (e.g. boot2docker on OSX). We don't need to do any user setup whatsoever. ...
[]
Please provide a description of the function:def add_env(self, name, val): '''Add an environment variable to the docker run invocation ''' if name in self.env_vars: raise KeyError(name) self.env_vars[name] = val
[]
Please provide a description of the function:def add_volume(self, hostpath, contpath, options=None): '''Add a volume (bind-mount) to the docker run invocation ''' if options is None: options = [] self.volumes.append((hostpath, contpath, options))
[]
Please provide a description of the function:def __locate_scubainit(self): '''Determine path to scubainit binary ''' pkg_path = os.path.dirname(__file__) self.scubainit_path = os.path.join(pkg_path, 'scubainit') if not os.path.isfile(self.scubainit_path): raise Scuba...
[]
Please provide a description of the function:def __load_config(self): '''Find and load .scuba.yml ''' # top_path is where .scuba.yml is found, and becomes the top of our bind mount. # top_rel is the relative path from top_path to the current working directory, # and is where we'...
[]
Please provide a description of the function:def __make_scubadir(self): '''Make temp directory where all ancillary files are bind-mounted ''' self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir') self.__scubadir_contpath = '/.scuba' self.add_volume(self.__scubadir_hostpa...
[]
Please provide a description of the function:def __setup_native_run(self): # These options are appended to mounted volume arguments # NOTE: This tells Docker to re-label the directory for compatibility # with SELinux. See `man docker-run` for more information. self.vol_opts = ['z'] ...
[]
Please provide a description of the function:def open_scubadir_file(self, name, mode): '''Opens a file in the 'scubadir' This file will automatically be bind-mounted into the container, at a path given by the 'container_path' property on the returned file object. ''' path = os.p...
[]
Please provide a description of the function:def copy_scubadir_file(self, name, source): '''Copies source into the scubadir Returns the container-path of the copied file ''' dest = os.path.join(self.__scubadir_hostpath, name) assert not os.path.exists(dest) shutil.copy2(...
[]
Please provide a description of the function:def format_cmdline(args, maxwidth=80): '''Format args into a shell-quoted command line. The result will be wrapped to maxwidth characters where possible, not breaking a single long argument. ''' # Leave room for the space and backslash at the end of eac...
[]
Please provide a description of the function:def parse_env_var(s): parts = s.split('=', 1) if len(parts) == 2: k, v = parts return (k, v) k = parts[0] return (k, os.getenv(k, ''))
[ "Parse an environment variable string\n\n Returns a key-value tuple\n\n Apply the same logic as `docker run -e`:\n \"If the operator names an environment variable without specifying a value,\n then the current value of the named variable is propagated into the\n container's environment\n " ]
Please provide a description of the function:def __wrap_docker_exec(func): '''Wrap a function to raise DockerExecuteError on ENOENT''' def call(*args, **kwargs): try: return func(*args, **kwargs) except OSError as e: if e.errno == errno.ENOENT: raise Docke...
[]
Please provide a description of the function:def docker_inspect(image): '''Inspects a docker image Returns: Parsed JSON data ''' args = ['docker', 'inspect', '--type', 'image', image] p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout, stderr = p.communicate() stdou...
[]
Please provide a description of the function:def docker_pull(image): '''Pulls an image''' args = ['docker', 'pull', image] # If this fails, the default docker stdout/stderr looks good to the user. ret = call(args) if ret != 0: raise DockerError('Failed to pull image "{}"'.format(image))
[]
Please provide a description of the function:def get_image_command(image): '''Gets the default command for an image''' info = docker_inspect_or_pull(image) try: return info['Config']['Cmd'] except KeyError as ke: raise DockerError('Failed to inspect image: JSON result missing key {}'.for...
[]
Please provide a description of the function:def get_image_entrypoint(image): '''Gets the image entrypoint''' info = docker_inspect_or_pull(image) try: return info['Config']['Entrypoint'] except KeyError as ke: raise DockerError('Failed to inspect image: JSON result missing key {}'.forma...
[]
Please provide a description of the function:def make_vol_opt(hostdir, contdir, options=None): '''Generate a docker volume option''' vol = '--volume={}:{}'.format(hostdir, contdir) if options != None: if isinstance(options, str): options = (options,) vol += ':' + ','.join(options...
[]
Please provide a description of the function:def find_config(): '''Search up the diretcory hierarchy for .scuba.yml Returns: path, rel on success, or None if not found path The absolute path of the directory where .scuba.yml was found rel The relative path from the directory where .scuba...
[]
Please provide a description of the function:def from_yaml(self, node): ''' Implementes a !from_yaml constructor with the following syntax: !from_yaml filename key Arguments: filename: Filename of external YAML document from which to load, relat...
[]
Please provide a description of the function:def process_command(self, command): '''Processes a user command using aliases Arguments: command A user command list (e.g. argv) Returns: A ScubaContext object with the following attributes: script: a list of command line...
[]
Please provide a description of the function:def open(self, filename): ''' Opens a database file ''' # Ensure old file is closed before opening a new one self.close() self._f = open(filename, 'rb') self._dbtype = struct.unpack('B', self._f.read(1))[0] self._dbcolumn = st...
[]
Please provide a description of the function:def get_country_short(self, ip): ''' Get country_short ''' rec = self.get_all(ip) return rec and rec.country_short
[]
Please provide a description of the function:def get_country_long(self, ip): ''' Get country_long ''' rec = self.get_all(ip) return rec and rec.country_long
[]
Please provide a description of the function:def get_region(self, ip): ''' Get region ''' rec = self.get_all(ip) return rec and rec.region
[]
Please provide a description of the function:def get_city(self, ip): ''' Get city ''' rec = self.get_all(ip) return rec and rec.city
[]
Please provide a description of the function:def get_isp(self, ip): ''' Get isp ''' rec = self.get_all(ip) return rec and rec.isp
[]
Please provide a description of the function:def get_latitude(self, ip): ''' Get latitude ''' rec = self.get_all(ip) return rec and rec.latitude
[]
Please provide a description of the function:def get_longitude(self, ip): ''' Get longitude ''' rec = self.get_all(ip) return rec and rec.longitude
[]
Please provide a description of the function:def get_domain(self, ip): ''' Get domain ''' rec = self.get_all(ip) return rec and rec.domain
[]
Please provide a description of the function:def get_zipcode(self, ip): ''' Get zipcode ''' rec = self.get_all(ip) return rec and rec.zipcode
[]
Please provide a description of the function:def get_timezone(self, ip): ''' Get timezone ''' rec = self.get_all(ip) return rec and rec.timezone
[]
Please provide a description of the function:def get_netspeed(self, ip): ''' Get netspeed ''' rec = self.get_all(ip) return rec and rec.netspeed
[]
Please provide a description of the function:def get_idd_code(self, ip): ''' Get idd_code ''' rec = self.get_all(ip) return rec and rec.idd_code
[]
Please provide a description of the function:def get_area_code(self, ip): ''' Get area_code ''' rec = self.get_all(ip) return rec and rec.area_code
[]
Please provide a description of the function:def get_weather_code(self, ip): ''' Get weather_code ''' rec = self.get_all(ip) return rec and rec.weather_code
[]
Please provide a description of the function:def get_weather_name(self, ip): ''' Get weather_name ''' rec = self.get_all(ip) return rec and rec.weather_name
[]
Please provide a description of the function:def get_mcc(self, ip): ''' Get mcc ''' rec = self.get_all(ip) return rec and rec.mcc
[]
Please provide a description of the function:def get_mnc(self, ip): ''' Get mnc ''' rec = self.get_all(ip) return rec and rec.mnc
[]
Please provide a description of the function:def get_mobile_brand(self, ip): ''' Get mobile_brand ''' rec = self.get_all(ip) return rec and rec.mobile_brand
[]
Please provide a description of the function:def get_elevation(self, ip): ''' Get elevation ''' rec = self.get_all(ip) return rec and rec.elevation
[]
Please provide a description of the function:def get_usage_type(self, ip): ''' Get usage_type ''' rec = self.get_all(ip) return rec and rec.usage_type
[]
Please provide a description of the function:def _parse_addr(self, addr): ''' Parses address and returns IP version. Raises exception on invalid argument ''' ipv = 0 try: socket.inet_pton(socket.AF_INET6, addr) # Convert ::FFFF:x.y.z.y to IPv4 if addr.lower()...
[]
Please provide a description of the function:def rates_for_location(self, postal_code, location_deets=None): request = self._get("rates/" + postal_code, location_deets) return self.responder(request)
[ "Shows the sales tax rates for a given location." ]
Please provide a description of the function:def tax_for_order(self, order_deets): request = self._post('taxes', order_deets) return self.responder(request)
[ "Shows the sales tax that should be collected for a given order." ]
Please provide a description of the function:def list_orders(self, params=None): request = self._get('transactions/orders', params) return self.responder(request)
[ "Lists existing order transactions." ]
Please provide a description of the function:def show_order(self, order_id): request = self._get('transactions/orders/' + str(order_id)) return self.responder(request)
[ "Shows an existing order transaction." ]
Please provide a description of the function:def create_order(self, order_deets): request = self._post('transactions/orders', order_deets) return self.responder(request)
[ "Creates a new order transaction." ]
Please provide a description of the function:def update_order(self, order_id, order_deets): request = self._put("transactions/orders/" + str(order_id), order_deets) return self.responder(request)
[ "Updates an existing order transaction." ]
Please provide a description of the function:def delete_order(self, order_id): request = self._delete("transactions/orders/" + str(order_id)) return self.responder(request)
[ "Deletes an existing order transaction." ]
Please provide a description of the function:def list_refunds(self, params=None): request = self._get('transactions/refunds', params) return self.responder(request)
[ "Lists existing refund transactions." ]
Please provide a description of the function:def show_refund(self, refund_id): request = self._get('transactions/refunds/' + str(refund_id)) return self.responder(request)
[ "Shows an existing refund transaction." ]
Please provide a description of the function:def create_refund(self, refund_deets): request = self._post('transactions/refunds', refund_deets) return self.responder(request)
[ "Creates a new refund transaction." ]
Please provide a description of the function:def update_refund(self, refund_id, refund_deets): request = self._put('transactions/refunds/' + str(refund_id), refund_deets) return self.responder(request)
[ "Updates an existing refund transaction." ]
Please provide a description of the function:def delete_refund(self, refund_id): request = self._delete('transactions/refunds/' + str(refund_id)) return self.responder(request)
[ "Deletes an existing refund transaction." ]
Please provide a description of the function:def list_customers(self, params=None): request = self._get('customers', params) return self.responder(request)
[ "Lists existing customers." ]
Please provide a description of the function:def show_customer(self, customer_id): request = self._get('customers/' + str(customer_id)) return self.responder(request)
[ "Shows an existing customer." ]
Please provide a description of the function:def create_customer(self, customer_deets): request = self._post('customers', customer_deets) return self.responder(request)
[ "Creates a new customer." ]
Please provide a description of the function:def update_customer(self, customer_id, customer_deets): request = self._put("customers/" + str(customer_id), customer_deets) return self.responder(request)
[ "Updates an existing customer." ]
Please provide a description of the function:def delete_customer(self, customer_id): request = self._delete("customers/" + str(customer_id)) return self.responder(request)
[ "Deletes an existing customer." ]
Please provide a description of the function:def validate_address(self, address_deets): request = self._post('addresses/validate', address_deets) return self.responder(request)
[ "Validates a customer address and returns back a collection of address matches." ]
Please provide a description of the function:def validate(self, vat_deets): request = self._get('validation', vat_deets) return self.responder(request)
[ "Validates an existing VAT identification number against VIES." ]
Please provide a description of the function:def get_score(self, terms): assert isinstance(terms, list) or isinstance(terms, tuple) score_li = np.asarray([self._get_score(t) for t in terms]) s_pos = np.sum(score_li[score_li > 0]) s_neg = -np.sum(score_li[score_li < 0]) ...
[ "Get score for a list of terms.\n \n :type terms: list\n :param terms: A list of terms to be analyzed.\n \n :returns: dict\n " ]
Please provide a description of the function:def choose_plural(amount, variants): try: if isinstance(variants, six.string_types): uvariants = smart_text(variants, encoding) else: uvariants = [smart_text(v, encoding) for v in variants] res = numeral.choose_plural(...
[ "\n Choose proper form for plural.\n\n Value is a amount, parameters are forms of noun.\n Forms are variants for 1, 2, 5 nouns. It may be tuple\n of elements, or string where variants separates each other\n by comma.\n\n Examples::\n {{ some_int|choose_plural:\"пример,примера,примеров\" }}\...
Please provide a description of the function:def rubles(amount, zero_for_kopeck=False): try: res = numeral.rubles(amount, zero_for_kopeck) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} return res
[ "Converts float value to in-words representation (for money)" ]
Please provide a description of the function:def in_words(amount, gender=None): try: res = numeral.in_words(amount, getattr(numeral, str(gender), None)) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} return ...
[ "\n In-words representation of amount.\n\n Parameter is a gender: MALE, FEMALE or NEUTER\n\n Examples::\n {{ some_int|in_words }}\n {{ some_other_int|in_words:FEMALE }}\n " ]
Please provide a description of the function:def sum_string(amount, gender, items): try: if isinstance(items, six.string_types): uitems = smart_text(items, encoding, default_uvalue) else: uitems = [smart_text(i, encoding) for i in items] res = numeral.sum_string(...
[ "\n in_words and choose_plural in a one flask\n Makes in-words representation of value with\n choosing correct form of noun.\n\n First parameter is an amount of objects. Second is a\n gender (MALE, FEMALE, NEUTER). Third is a variants\n of forms for object name.\n\n Examples::\n {% sum_s...
Please provide a description of the function:def _sub_patterns(patterns, text): for pattern, repl in patterns: text = re.sub(pattern, repl, text) return text
[ "\n Apply re.sub to bunch of (pattern, repl)\n " ]
Please provide a description of the function:def rl_cleanspaces(x): patterns = ( # arguments for re.sub: pattern and repl # удаляем пробел перед знаками препинания (r' +([\.,?!\)]+)', r'\1'), # добавляем пробел после знака препинания, если только за ним нет другого (r'([...
[ "\n Clean double spaces, trailing spaces, heading spaces,\n spaces before punctuations\n " ]
Please provide a description of the function:def rl_ellipsis(x): patterns = ( # если больше трех точек, то не заменяем на троеточие # чтобы не было глупых .....->….. (r'([^\.]|^)\.\.\.([^\.]|$)', u'\\1\u2026\\2'), # если троеточие в начале строки или возле кавычки -- # ...
[ "\n Replace three dots to ellipsis\n " ]
Please provide a description of the function:def rl_initials(x): return re.sub( re.compile(u'([А-Я])\\.\\s*([А-Я])\\.\\s*([А-Я][а-я]+)', re.UNICODE), u'\\1.\\2.\u2009\\3', x )
[ "\n Replace space between initials and surname by thin space\n " ]
Please provide a description of the function:def rl_dashes(x): patterns = ( # тире (re.compile(u'(^|(.\\s))\\-\\-?(([\\s\u202f].)|$)', re.MULTILINE|re.UNICODE), u'\\1\u2014\\3'), # диапазоны между цифрами - en dash (re.compile(u'(\\d[\\s\u2009]*)\\-([\\s\u2009]*\d)', re.MULTILIN...
[ "\n Replace dash to long/medium dashes\n " ]
Please provide a description of the function:def rl_wordglue(x): patterns = ( # частицы склеиваем с предыдущим словом (re.compile(u'(\\s+)(же|ли|ль|бы|б|ж|ка)([\\.,!\\?:;]?\\s+)', re.UNICODE), u'\u202f\\2\\3'), # склеиваем короткие слова со следующим словом (re.compile(u'\\b([a-...
[ "\n Glue (set nonbreakable space) short words with word before/after\n " ]
Please provide a description of the function:def rl_marks(x): # простые замены, можно без регулярок replacements = ( (u'(r)', u'\u00ae'), # ® (u'(R)', u'\u00ae'), # ® (u'(p)', u'\u00a7'), # § (u'(P)', u'\u00a7'), # § (u'(tm)', u'\u2122'), # ™ (u'(TM)', u'\u21...
[ "\n Replace +-, (c), (tm), (r), (p), etc by its typographic eqivalents\n " ]
Please provide a description of the function:def rl_quotes(x): patterns = ( # открывающие кавычки ставятся обычно вплотную к слову слева # а закрывающие -- вплотную справа # открывающие русские кавычки-ёлочки (re.compile(r'((?:^|\s))(")((?u))', re.UNICODE), u'\\1\xab\\3'), ...
[ "\n Replace quotes by typographic quotes\n " ]
Please provide a description of the function:def distance_of_time(from_time, accuracy=1): try: to_time = None if conf.settings.USE_TZ: to_time=utils.timezone.now() res = dt.distance_of_time_in_words(from_time, accuracy, to_time) except Exception as err: # because...
[ "\n Display distance of time from current time.\n\n Parameter is an accuracy level (deafult is 1).\n Value must be numeral (i.e. time.time() result) or\n datetime.datetime (i.e. datetime.datetime.now()\n result).\n\n Examples::\n {{ some_time|distance_of_time }}\n {{ some_dtime|dista...
Please provide a description of the function:def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False): try: res = dt.ru_strftime(format, date, inflected=True, inflected_day=inflected_day, ...
[ "\n Russian strftime, formats date with given format.\n\n Value is a date (supports datetime.date and datetime.datetime),\n parameter is a format (string). For explainings about format,\n see documentation for original strftime:\n http://docs.python.org/lib/module-time.html\n\n Examples::\n ...
Please provide a description of the function:def distance_of_time_in_words(from_time, accuracy=1, to_time=None): current = False if to_time is None: current = True to_time = datetime.datetime.now() check_positive(accuracy, strict=True) if not isinstance(from_time, datetime.dateti...
[ "\n Represents distance of time in words\n\n @param from_time: source time (in seconds from epoch)\n @type from_time: C{int}, C{float} or C{datetime.datetime}\n\n @param accuracy: level of accuracy (1..3), default=1\n @type accuracy: C{int}\n\n @param to_time: target time (in seconds from epoch),\...
Please provide a description of the function:def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False, inflected_day=False, preposition=False): if date is None: date = datetime.datetime.today() weekday = date.weekday() prepos = preposition and DAY_NAMES[weekday][3] or u"...
[ "\n Russian strftime without locale\n\n @param format: strftime format, default=u'%d.%m.%Y'\n @type format: C{unicode}\n\n @param date: date value, default=None translates to today\n @type date: C{datetime.date} or C{datetime.datetime}\n\n @param inflected: is month inflected, default False\n @...
Please provide a description of the function:def _get_float_remainder(fvalue, signs=9): check_positive(fvalue) if isinstance(fvalue, six.integer_types): return "0" if isinstance(fvalue, Decimal) and fvalue.as_tuple()[2] == 0: # Decimal.as_tuple() -> (sign, digit_tuple, exponent) ...
[ "\n Get remainder of float, i.e. 2.05 -> '05'\n\n @param fvalue: input value\n @type fvalue: C{integer types}, C{float} or C{Decimal}\n\n @param signs: maximum number of signs\n @type signs: C{integer types}\n\n @return: remainder\n @rtype: C{str}\n\n @raise ValueError: fvalue is negative\n ...
Please provide a description of the function:def choose_plural(amount, variants): if isinstance(variants, six.text_type): variants = split_values(variants) check_length(variants, 3) amount = abs(amount) if amount % 10 == 1 and amount % 100 != 11: variant = 0 elif amoun...
[ "\n Choose proper case depending on amount\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param variants: variants (forms) of object in such form:\n (1 object, 2 objects, 5 objects).\n @type variants: 3-element C{sequence} of C{unicode}\n or C{unicode} (three...
Please provide a description of the function:def get_plural(amount, variants, absence=None): if amount or absence is None: return u"%d %s" % (amount, choose_plural(amount, variants)) else: return absence
[ "\n Get proper case with value\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param variants: variants (forms) of object in such form:\n (1 object, 2 objects, 5 objects).\n @type variants: 3-element C{sequence} of C{unicode}\n or C{unicode} (three variants wi...
Please provide a description of the function:def _get_plural_legacy(amount, extra_variants): absence = None if isinstance(extra_variants, six.text_type): extra_variants = split_values(extra_variants) if len(extra_variants) == 4: variants = extra_variants[:3] absence = extra_vari...
[ "\n Get proper case with value (legacy variant, without absence)\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param variants: variants (forms) of object in such form:\n (1 object, 2 objects, 5 objects, 0-object variant).\n 0-object variant is similar to C{abse...
Please provide a description of the function:def rubles(amount, zero_for_kopeck=False): check_positive(amount) pts = [] amount = round(amount, 2) pts.append(sum_string(int(amount), 1, (u"рубль", u"рубля", u"рублей"))) remainder = _get_float_remainder(amount, 2) iremainder = int(remainder) ...
[ "\n Get string for money\n\n @param amount: amount of money\n @type amount: C{integer types}, C{float} or C{Decimal}\n\n @param zero_for_kopeck: If false, then zero kopecks ignored\n @type zero_for_kopeck: C{bool}\n\n @return: in-words representation of money's amount\n @rtype: C{unicode}\n\n ...
Please provide a description of the function:def in_words_float(amount, _gender=FEMALE): check_positive(amount) pts = [] # преобразуем целую часть pts.append(sum_string(int(amount), 2, (u"целая", u"целых", u"целых"))) # теперь то, что после запятой remainder = _ge...
[ "\n Float in words\n\n @param amount: float numeral\n @type amount: C{float} or C{Decimal}\n\n @return: in-words reprsentation of float numeral\n @rtype: C{unicode}\n\n @raise ValueError: when ammount is negative\n " ]
Please provide a description of the function:def in_words(amount, gender=None): check_positive(amount) if isinstance(amount, Decimal) and amount.as_tuple()[2] == 0: # если целое, # т.е. Decimal.as_tuple -> (sign, digits tuple, exponent), exponent=0 # то как целое amount = in...
[ "\n Numeral in words\n\n @param amount: numeral\n @type amount: C{integer types}, C{float} or C{Decimal}\n\n @param gender: gender (MALE, FEMALE or NEUTER)\n @type gender: C{int}\n\n @return: in-words reprsentation of numeral\n @rtype: C{unicode}\n\n raise ValueError: when amount is negative...
Please provide a description of the function:def sum_string(amount, gender, items=None): if isinstance(items, six.text_type): items = split_values(items) if items is None: items = (u"", u"", u"") try: one_item, two_items, five_items = items except ValueError: raise ...
[ "\n Get sum in words\n\n @param amount: amount of objects\n @type amount: C{integer types}\n\n @param gender: gender of object (MALE, FEMALE or NEUTER)\n @type gender: C{int}\n\n @param items: variants of object in three forms:\n for one object, for two objects and for five objects\n @ty...
Please provide a description of the function:def _sum_string_fn(into, tmp_val, gender, items=None): if items is None: items = (u"", u"", u"") one_item, two_items, five_items = items check_positive(tmp_val) if tmp_val == 0: return into, tmp_val words = [] rest = tmp_v...
[ "\n Make in-words representation of single order\n\n @param into: in-words representation of lower orders\n @type into: C{unicode}\n\n @param tmp_val: temporary value without lower orders\n @type tmp_val: C{integer types}\n\n @param gender: gender (MALE, FEMALE or NEUTER)\n @type gender: C{int}...
Please provide a description of the function:def detranslify(in_string): try: russian = six.text_type(in_string) except UnicodeDecodeError: raise ValueError("We expects if in_string is 8-bit string," + \ "then it consists only ASCII chars, but now it doesn't. " + \ ...
[ "\n Detranslify\n\n @param in_string: input string\n @type in_string: C{basestring}\n\n @return: detransliterated string\n @rtype: C{unicode}\n\n @raise ValueError: if in_string is C{str}, but it isn't ascii\n " ]
Please provide a description of the function:def slugify(in_string): try: u_in_string = six.text_type(in_string).lower() except UnicodeDecodeError: raise ValueError("We expects when in_string is str type," + \ "it is an ascii, but now it isn't. Use unicode " + \ ...
[ "\n Prepare string for slug (i.e. URL or file/dir name)\n\n @param in_string: input string\n @type in_string: C{basestring}\n\n @return: slug-string\n @rtype: C{str}\n\n @raise ValueError: if in_string is C{str}, but it isn't ascii\n " ]
Please provide a description of the function:def check_length(value, length): _length = len(value) if _length != length: raise ValueError("length must be %d, not %d" % \ (length, _length))
[ "\n Checks length of value\n\n @param value: value to check\n @type value: C{str}\n\n @param length: length checking for\n @type length: C{int}\n\n @return: None when check successful\n\n @raise ValueError: check failed\n " ]
Please provide a description of the function:def check_positive(value, strict=False): if not strict and value < 0: raise ValueError("Value must be positive or zero, not %s" % str(value)) if strict and value <= 0: raise ValueError("Value must be positive, not %s" % str(value))
[ "\n Checks if variable is positive\n\n @param value: value to check\n @type value: C{integer types}, C{float} or C{Decimal}\n\n @return: None when check successful\n\n @raise ValueError: check failed\n " ]
Please provide a description of the function:def split_values(ustring, sep=u','): assert isinstance(ustring, six.text_type), "uvalue must be unicode, not %s" % type(ustring) # unicode have special mark symbol 0xffff which cannot be used in a regular text, # so we use it to mark a place where escaped co...
[ "\n Splits unicode string with separator C{sep},\n but skips escaped separator.\n \n @param ustring: string to split\n @type ustring: C{unicode}\n \n @param sep: separator (default to u',')\n @type sep: C{unicode}\n \n @return: tuple of splitted elements\n " ]
Please provide a description of the function:def translify(text): try: res = translit.translify(smart_text(text, encoding)) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
[ "Translify russian text" ]
Please provide a description of the function:def detranslify(text): try: res = translit.detranslify(text) except Exception as err: # because filter must die silently res = default_value % {'error': err, 'value': text} return res
[ "Detranslify russian text" ]
Please provide a description of the function:def apply(diff, recs, strict=True): index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_columns, strict=strict) _remove_records(indexed, diff['removed'], index_column...
[ "\n Transform the records with the patch. May fail if the records do not\n match those expected in the patch.\n " ]