code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def get_settings(self): host = '127.0.0.1' port = 6379 db = 0 if self.connection_uri is not None: re_connection_uri = r'redis://(?:([\w]+)@)?([\w\d\.]+):(\d+)(?:/(\d+))?' match = re.match(re_connection_uri, self.connection_uri) if match: ...
This creates a dict with keyword arguments used to create the redis client. It is used like ``redis.StrictClient(**self.get_settings())``. Thus, if the settings string is not enough to generate the wanted setting you can override this function. :return: A dict with keyword arguments for...
def parse_environ(name, parse_class=ParseResult, **defaults): return parse(os.environ[name], parse_class, **defaults)
same as parse() but you pass in an environment variable name that will be used to fetch the dsn :param name: string, the environment variable name that contains the dsn to parse :param parse_class: ParseResult, the class that will be used to hold parsed values :param **defaults: dict, any values you wa...
def parse_environs(name, parse_class=ParseResult, **defaults): ret = [] if name in os.environ: ret.append(parse_environ(name, parse_class, **defaults)) # now try importing _1 -> _N dsns increment_name = lambda name, num: '{name}_{num}'.format(name=name, num=num) dsn_num = 0 if incremen...
same as parse_environ() but will also check name_1, name_2, ..., name_N and return all the found dsn strings from the environment this will look for name, and name_N (where N is 1 through infinity) in the environment, if it finds them, it will assume they are dsn urls and will parse them. The num che...
def parse(dsn, parse_class=ParseResult, **defaults): r = parse_class(dsn, **defaults) return r
parse a dsn to parts similar to parseurl :param dsn: string, the dsn to parse :param parse_class: ParseResult, the class that will be used to hold parsed values :param **defaults: dict, any values you want to have defaults for if they aren't in the dsn :returns: ParseResult() tuple-like instance
def netloc(self): s = '' prefix = '' if self.username: s += self.username prefix = '@' if self.password: s += ":{password}".format(password=self.password) prefix = '@' s += "{prefix}{hostloc}".format(prefix=prefix, hostlo...
return username:password@hostname:port
def hostloc(self): hostloc = self.hostname if self.port: hostloc = '{hostloc}:{port}'.format(hostloc=hostloc, port=self.port) return hostloc
return host:port
def setdefault(self, key, val): if not getattr(self, key, None): setattr(self, key, val)
set a default value for key this is different than dict's setdefault because it will set default either if the key doesn't exist, or if the value at the key evaluates to False, so an empty string or a None value will also be updated :param key: string, the attribute to update :...
def geturl(self): return urlparse.urlunparse(( self.scheme, self.netloc, self.path, self.params, self.query_str, self.fragment, ))
return the dsn back into url form
def preparse(self, context): context.early_args, unused = ( context.early_parser.parse_known_args(context.argv))
Parse a portion of command line arguments with the early parser. This method relies on ``context.argv`` and ``context.early_parser`` and produces ``context.early_args``. The ``context.early_args`` object is the return value from argparse. It is the dict/object like namespace object.
def build_parser(self, context): context.parser, context.max_level = self._create_parser(context)
Create the final argument parser. This method creates the non-early (full) argparse argument parser. Unlike the early counterpart it is expected to have knowledge of the full command tree. This method relies on ``context.cmd_tree`` and produces ``context.parser``. Other ingredi...
def parse(self, context): context.args = context.parser.parse_args(context.argv)
Parse command line arguments. This method relies on ``context.argv`` and ``context.early_parser`` and produces ``context.args``. Note that ``.argv`` is modified by :meth:`preparse()` so it actually has _less_ things in it. The ``context.args`` object is the return value from argparse. ...
def parse(self, context): try: import argcomplete except ImportError: return try: parser = context.parser except AttributeError: raise RecipeError( """ The context doesn't have the parser attribute. ...
Optionally trigger argument completion in the invoking shell. This method is called to see if bash argument completion is requested and to honor the request, if needed. This causes the process to exit (early) without giving other ingredients a chance to initialize or shut down. ...
def ansi_cmd(cmd, *args): try: obj = getattr(ANSI, str('cmd_{}'.format(cmd))) except AttributeError: raise ValueError( "incorrect command: {!r}".format(cmd)) if isinstance(obj, type("")): return obj else: return obj(*args)
Get ANSI command code by name.
def get_visible_color(color): if isinstance(color, (str, type(""))): try: return getattr(_Visible, str('{}'.format(color))) except AttributeError: raise ValueError("incorrect color: {!r}".format(color)) elif isinstance(color, tuple): return (0x80 ^ color[0], ...
Get the visible counter-color.
def sgr_fg_rgb(r, g, b): assert r in range(256) assert g in range(256) assert b in range(256) return '38;2;{};{};{}'.format(r, g, b)
Get SGR (Set Graphics Rendition) foreground RGB color.
def sgr_bg_rgb(r, g, b): assert r in range(256) assert g in range(256) assert b in range(256) return '48;2;{};{};{}'.format(r, g, b)
Get SGR (Set Graphics Rendition) background RGB color.
def _aprint2(self, *values, **kwargs): sep = kwargs.pop(str('sep'), ' ') end = kwargs.pop(str('end'), '\n') file = kwargs.pop(str('file'), None) or sys.stdout flush = kwargs.pop(str('flush'), False) fg = kwargs.pop(str('fg'), None) bg = kwargs.pop(str('bg'), None...
ANSI formatting-aware print(). This method is a version of print() (function) that understands additional ansi control parameters. :param value: The values to print, same as with ``print()`` :param sep: Separator between values, same as with ``print()`` ...
def added(self, context): context.ansi = ANSIFormatter(self._enable) context.aprint = context.ansi.aprint
Ingredient method called before anything else.
def using_git(cwd): try: git_log = shell_out(["git", "log"], cwd=cwd) return True except (CalledProcessError, OSError): # pragma: no cover return False
Test whether the directory cwd is contained in a git repository.
def using_hg(cwd): try: hg_log = shell_out(["hg", "log"], cwd=cwd) return True except (CalledProcessError, OSError): return False
Test whether the directory cwd is contained in a mercurial repository.
def using_bzr(cwd): try: bzr_log = shell_out(["bzr", "log"], cwd=cwd) return True except (CalledProcessError, OSError): return False
Test whether the directory cwd is contained in a bazaar repository.
def from_string(vc): try: # Note: this means all version controls must have # a title naming convention (!) vc = globals()[vc.title()] assert(issubclass(vc, VersionControl)) return vc except (KeyError, AssertionError): rais...
Return the VersionControl superclass from a string, for example VersionControl.from_string('git') will return Git.
def which(cwd=None): # pragma: no cover if cwd is None: cwd = os.getcwd() for (k, using_vc) in globals().items(): if k.startswith('using_') and using_vc(cwd=cwd): return VersionControl.from_string(k[6:]) # Not supported (yet) raise NotIm...
Try to find which version control system contains the cwd directory. Returns the VersionControl superclass e.g. Git, if none were found this will raise a NotImplementedError.
def modified_lines(self, r, file_name): cmd = self.file_diff_cmd(r, file_name) diff = shell_out_ignore_exitcode(cmd, cwd=self.root) return list(self.modified_lines_from_diff(diff))
Returns the line numbers of a file which have been changed.
def modified_lines_from_diff(self, diff): from pep8radius.diff import modified_lines_from_udiff for start, end in modified_lines_from_udiff(diff): yield start, end
Returns the changed lines in a diff. - Potentially this is vc specific (if not using udiff). Note: this returns the line numbers in descending order.
def get_filenames_diff(self, r): cmd = self.filenames_diff_cmd(r) diff_files = shell_out_ignore_exitcode(cmd, cwd=self.root) diff_files = self.parse_diff_filenames(diff_files) return set(f for f in diff_files if f.endswith('.py'))
Get the py files which have been changed since rev.
def parse_diff_filenames(diff_files): # ? .gitignore # M 0.txt files = [] for line in diff_files.splitlines(): line = line.strip() fn = re.findall('[^ ]+\s+(.*.py)', line) if fn and not line.startswith('?'): files.append(fn[...
Parse the output of filenames_diff_cmd.
def render_to_response(self, obj, **response_kwargs): return HttpResponse(self.serialize(obj), content_type='application/json', **response_kwargs)
Returns an ``HttpResponse`` object instance with Content-Type: application/json. The response body will be the return value of ``self.serialize(obj)``
def http_method_not_allowed(self, *args, **kwargs): resp = super(JsonResponseMixin, self).http_method_not_allowed(*args, **kwargs) resp['Content-Type'] = 'application/json' return resp
Returns super after setting the Content-Type header to ``application/json``
def data(self): if self.request.method == 'GET': return self.request.GET else: assert self.request.META['CONTENT_TYPE'].startswith('application/json') charset = self.request.encoding or settings.DEFAULT_CHARSET return json.loads(self.request.body....
Helper class for parsing JSON POST data into a Python object.
def dispatch(self, *args, **kwargs): try: self.auth(*args, **kwargs) return super(RestView, self).dispatch(*args, **kwargs) except ValidationError as e: return self.render_to_response(e.message_dict, status=409) except Http404 as e: return...
Authenticates the request and dispatches to the correct HTTP method function (GET, POST, PUT,...). Translates exceptions into proper JSON serialized HTTP responses: - ValidationError: HTTP 409 - Http404: HTTP 404 - PermissionDenied: HTTP 403 - ValueError:...
def options(self, request, *args, **kwargs): allow = [] for method in self.http_method_names: if hasattr(self, method): allow.append(method.upper()) r = self.render_to_response(None) r['Allow'] = ','.join(allow) return r
Implements a OPTIONS HTTP method function returning all allowed HTTP methods.
def main(args=None, vc=None, cwd=None, apply_config=False): import signal try: # pragma: no cover # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: ...
PEP8 clean only the parts of the files touched since the last commit, a previous commit or branch.
def parse_args(arguments=None, root=None, apply_config=False): if arguments is None: arguments = [] parser = create_parser() args = parser.parse_args(arguments) if apply_config: parser = apply_config_defaults(parser, args, root=root) args = parser.parse_args(arguments) ...
Parse the arguments from the CLI. If apply_config then we first look up and apply configs using apply_config_defaults.
def apply_config_defaults(parser, args, root): if root is None: try: from pep8radius.vcs import VersionControl root = VersionControl.which().root_dir() except NotImplementedError: pass # don't update local, could be using as module config = SafeConfigPa...
Update the parser's defaults from either the arguments' config_arg or the config files given in config_files(root).
def read_vint32(self): result = 0 count = 0 while True: if count > 4: raise ValueError("Corrupt VarInt32") b = self.read_byte() result = result | (b & 0x7F) << (7 * count) count += 1 if not b & 0x80: ...
This seems to be a variable length integer ala utf-8 style
def read_message(self, message_type, compressed=False, read_size=True): if read_size: size = self.read_vint32() b = self.read(size) else: b = self.read() if compressed: b = snappy.decompress(b) m = message_type() m.ParseF...
Read a protobuf message
def run_hooks(self, packet): if packet.__class__ in self.internal_hooks: self.internal_hooks[packet.__class__](packet) if packet.__class__ in self.hooks: self.hooks[packet.__class__](packet)
Run any additional functions that want to process this type of packet. These can be internal parser hooks, or external hooks that process information
def parse_string_table(self, tables): self.info("String table: %s" % (tables.tables, )) for table in tables.tables: if table.table_name == "userinfo": for item in table.items: if len(item.data) > 0: if len(item.data) == 14...
Need to pull out player information from string table
def parse_game_event(self, event): if event.eventid in self.event_lookup: #Bash this into a nicer data format to work with event_type = self.event_lookup[event.eventid] ge = GameEvent(event_type.name) for i, key in enumerate(event.keys): ...
So CSVCMsg_GameEventList is a list of all events that can happen. A game event has an eventid which maps to a type of event that happened
def parse(self): self.important("Parsing demo file '%s'" % (self.filename, )) with open(self.filename, 'rb') as f: reader = Reader(StringIO(f.read())) filestamp = reader.read(8) offset = reader.read_int32() if filestamp != "PBUFDEM\x00": ...
Parse a replay
def convert(data): try: st = basestring except NameError: st = str if isinstance(data, st): return str(data) elif isinstance(data, Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, Iterable): return type(data)(map(convert, data))...
Convert from unicode to native ascii
def get_type_properties(self, property_obj, name, additional_prop=False): property_type = property_obj.get('type', 'object') property_format = property_obj.get('format') property_dict = {} if property_type in ['object', 'array']: schema_type = SchemaTypes.MAPPED if ...
Get internal properties of property (extended in schema) :param dict property_obj: raw property object :param str name: name of property :param bool additional_prop: recursion's param :return: Type, format and internal properties of property :rtype: tuple(str, str, dict)
def set_type_by_schema(self, schema_obj, schema_type): schema_id = self._get_object_schema_id(schema_obj, schema_type) if not self.storage.contains(schema_id): schema = self.storage.create_schema( schema_obj, self.name, schema_type, root=self.root) asser...
Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type:
def tablib_export_action(modeladmin, request, queryset, file_type="xls"): dataset = SimpleDataset(queryset, headers=None) filename = '{0}.{1}'.format( smart_str(modeladmin.model._meta.verbose_name_plural), file_type) response_kwargs = { 'content_type': get_content_type(file_type) ...
Allow the user to download the current filtered list of items :param file_type: One of the formats supported by tablib (e.g. "xls", "csv", "html", etc.)
def _fill_schemas_from_definitions(self, obj): if obj.get('definitions'): self.schemas.clear() all_of_stack = [] for name, definition in obj['definitions'].items(): if 'allOf' in definition: all_of_stack.append((name, definition)) ...
At first create schemas without 'AllOf' :param obj: :return: None
def get_type_properties(self, property_obj, name, additional_prop=False): property_type, property_format, property_dict = \ super(Schema, self).get_type_properties(property_obj, name, additional_prop=additional_prop) _schema = self.storage.get(property_type) if _schema and (...
Extend parents 'Get internal properties of property'-method
def generic_export(request, model_name=None): if model_name not in settings.TABLIB_MODELS: raise Http404() model = get_model(*model_name.split(".", 2)) if not model: raise ImproperlyConfigured( "Model {0} is in settings.TABLIB_MODELS but" " could not be loaded"...
Generic view configured through settings.TABLIB_MODELS Usage: 1. Add the view to ``urlpatterns`` in ``urls.py``:: url(r'export/(?P<model_name>[^/]+)/$', "django_tablib.views.generic_export"), 2. Create the ``settings.TABLIB_MODELS`` dictionary using model names ...
def sorted(collection): if len(collection) < 1: return collection if isinstance(collection, dict): return sorted(collection.items(), key=lambda x: x[0]) if isinstance(list(collection)[0], Operation): key = lambda x: x.operation_id elif isins...
sorting dict by key, schema-collection by schema-name operations by id
def get_regular_properties(self, _type, *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.schema_type == SchemaTypes.DEFINITION and not kwargs.get('definition'): return '' head = """.. csv-tab...
Make table with properties by schema_id :param str _type: :rtype: str
def get_type_description(self, _type, suffix='', *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.all_of: models = ','.join( (self.get_type_description(_type, *args, **kwargs) for _ty...
Get description of type :param suffix: :param str _type: :rtype: str
def get_additional_properties(self, _type, *args, **kwargs): if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) body = [] for sch in schema.nested_schemas: # complex types nested_schema = SchemaObjects.get(sch) ...
Make head and table with additional properties by schema_id :param str _type: :rtype: str
def pre_save(self, instance, add): if not self.natural_text_field or self.attname not in instance.__dict__: return edtf = getattr(instance, self.attname) # Update EDTF field based on latest natural text value, if any natural_text = getattr(instance, self.natural_te...
Updates the edtf value from the value of the display_field. If there's a valid edtf, then set the date values.
def apply_delta(op, time_struct, delta): if not delta: return time_struct # No work to do try: dt_result = op(datetime(*time_struct[:6]), delta) return dt_to_struct_time(dt_result) except (OverflowError, ValueError): # Year is not within supported 1 to 9999 AD range ...
Apply a `relativedelta` to a `struct_time` data structure. `op` is an operator function, probably always `add` or `sub`tract to correspond to `a_date + a_delta` and `a_date - a_delta`. This function is required because we cannot use standard `datetime` module objects for conversion when the date/time ...
def _strict_date(self, lean): return struct_time( ( self._precise_year(lean), self._precise_month(lean), self._precise_day(lean), ) + tuple(TIME_EMPTY_TIME) + tuple(TIME_EMPTY_EXTRAS) )
Return a `time.struct_time` representation of the date.
def _get_fuzzy_padding(self, lean): result = relativedelta(0) if self.year_ua: result += appsettings.PADDING_YEAR_PRECISION * self.year_ua._get_multiplier() if self.month_ua: result += appsettings.PADDING_MONTH_PRECISION * self.month_ua._get_multiplier() ...
This is not a perfect interpretation as fuzziness is introduced for redundant uncertainly modifiers e.g. (2006~)~ will get two sets of fuzziness.
def deploy(self, *lambdas): if not self.role: logger.error('Missing AWS Role') raise ArgumentsError('Role required') logger.debug('Deploying lambda {}'.format(self.lambda_name)) zfh = self.package() if self.lambda_name in self.get_function_names(): ...
Deploys lambdas to AWS
def list(self): for function in self.client.list_functions().get('Functions', []): lines = json.dumps(function, indent=4, sort_keys=True).split('\n') for line in lines: logger.info(line)
Lists already deployed lambdas
def get_info(self): if LooseVersion(django.get_version()) < LooseVersion('1.7.0'): info = self.model._meta.app_label, self.model._meta.module_name else: info = self.model._meta.app_label, self.model._meta.model_name return info
Helper method to get model info in a form of (app_label, model_name). Avoid deprecation warnings and failures with different Django versions.
def date_to_jd(year,month,day): if month == 1 or month == 2: yearp = year - 1 monthp = month + 12 else: yearp = year monthp = month # this checks where we are in relation to October 15, 1582, the beginning # of the Gregorian calendar. if ((year < 1582) or ...
Convert a date to Julian Day. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., Duffet-Smith and Zwart, 2011. Parameters ---------- year : int Year as integer. Years preceding 1 A.D. should be 0 or negative. The year before 1 A.D. is 0, 10 B.C....
def jd_to_date(jd): jd = jd + 0.5 F, I = math.modf(jd) I = int(I) A = math.trunc((I - 1867216.25)/36524.25) if I > 2299160: B = I + 1 + A - math.trunc(A / 4.) else: B = I C = B + 1524 D = math.trunc((C - 122.1) / 365.25) E = math.trunc(365.25 * D) G = ...
Convert Julian Day to date. Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet', 4th ed., Duffet-Smith and Zwart, 2011. Parameters ---------- jd : float Julian Day Returns ------- year : int Year as integer. Years preceding 1 A.D. should be 0 ...
def hmsm_to_days(hour=0,min=0,sec=0,micro=0): days = sec + (micro / 1.e6) days = min + (days / 60.) days = hour + (days / 60.) return days / 24.
Convert hours, minutes, seconds, and microseconds to fractional days. Parameters ---------- hour : int, optional Hour number. Defaults to 0. min : int, optional Minute number. Defaults to 0. sec : int, optional Second number. Defaults to 0. micro : int, optional ...
def days_to_hmsm(days): hours = days * 24. hours, hour = math.modf(hours) mins = hours * 60. mins, min = math.modf(mins) secs = mins * 60. secs, sec = math.modf(secs) micro = round(secs * 1.e6) return int(hour), int(min), int(sec), int(micro)
Convert fractional days to hours, minutes, seconds, and microseconds. Precision beyond microseconds is rounded to the nearest microsecond. Parameters ---------- days : float A fractional number of days. Must be less than 1. Returns ------- hour : int Hour number. min :...
def datetime_to_jd(date): days = date.day + hmsm_to_days(date.hour,date.minute,date.second,date.microsecond) return date_to_jd(date.year,date.month,days)
Convert a `datetime.datetime` object to Julian Day. Parameters ---------- date : `datetime.datetime` instance Returns ------- jd : float Julian day. Examples -------- >>> d = datetime.datetime(1985,2,17,6) >>> d datetime.datetime(1985, 2, 17, 6, 0) >>> jdutil...
def jd_to_datetime(jd): year, month, day = jd_to_date(jd) frac_days,day = math.modf(day) day = int(day) hour,min,sec,micro = days_to_hmsm(frac_days) return datetime(year,month,day,hour,min,sec,micro)
Convert a Julian Day to an `jdutil.datetime` object. Parameters ---------- jd : float Julian day. Returns ------- dt : `jdutil.datetime` object `jdutil.datetime` equivalent of Julian day. Examples -------- >>> jd_to_datetime(2446113.75) datetime(1985, 2, 17, 6,...
def timedelta_to_days(td): seconds_in_day = 24. * 3600. days = td.days + (td.seconds + (td.microseconds * 10.e6)) / seconds_in_day return days
Convert a `datetime.timedelta` object to a total number of days. Parameters ---------- td : `datetime.timedelta` instance Returns ------- days : float Total number of days in the `datetime.timedelta` object. Examples -------- >>> td = datetime.timedelta(4.5) >>> td ...
def create_schema(cls, obj, name, schema_type, root): if schema_type == SchemaTypes.MAPPED: schema = SchemaMapWrapper(obj, storage=cls, name=name, root=root) else: schema = Schema(obj, schema_type, storage=cls, name=name, root=root) cls.add_schema(schema) ...
Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str schema_type: schema location. Can be ``inline``, ``definition`` or ``mapped`` :param BaseSwaggerObject root: root doc :return: new schema :rtype: Schema
def get_schemas(cls, schema_types=None, sort=True): result = filter(lambda x: not x.is_inline_array, cls._schemas.values()) if schema_types: result = filter(lambda x: x.schema_type in schema_types, result) if sort: result = sorted(result, key=attrgetter('name')) ...
Get schemas by type. If ``schema_type`` is None, return all schemas :param schema_types: list of schema types :type schema_types: list or None :param bool sort: sort by name :return: list of schemas :rtype: list
def merge_schemas(cls, schema, _schema): tmp = schema.properties[:] # copy prop = {} to_dict = lambda e: prop.update({e.pop('name'): e}) [to_dict(i) for i in tmp] # map(to_dict, tmp) for _prop in _schema.properties: if prop.get(_prop['name']): ...
Return second Schema, which is extended by first Schema https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#composition-and-inheritance-polymorphism
def dt_to_struct_time(dt): if isinstance(dt, datetime): return struct_time( [dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second] + TIME_EMPTY_EXTRAS ) elif isinstance(dt, date): return struct_time( [dt.year, dt.month, dt.day] + TIME_EMPTY_TI...
Convert a `datetime.date` or `datetime.datetime` to a `struct_time` representation *with zero values* for data fields that we cannot always rely on for ancient or far-future dates: tm_wday, tm_yday, tm_isdst NOTE: If it wasn't for the requirement that the extra fields are unset we could use the `timetu...
def trim_struct_time(st, strip_time=False): if strip_time: return struct_time(list(st[:3]) + TIME_EMPTY_TIME + TIME_EMPTY_EXTRAS) else: return struct_time(list(st[:6]) + TIME_EMPTY_EXTRAS)
Return a `struct_time` based on the one provided but with the extra fields `tm_wday`, `tm_yday`, and `tm_isdst` reset to default values. If `strip_time` is set to true the time value are also set to zero: `tm_hour`, `tm_min`, and `tm_sec`.
def struct_time_to_jd(st): year, month, day = st[:3] hours, minutes, seconds = st[3:6] # Convert time of day to fraction of day day += jdutil.hmsm_to_days(hours, minutes, seconds) return jdutil.date_to_jd(year, month, day)
Return a float number representing the Julian Date for the given `struct_time`. NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are ignored.
def jd_to_struct_time(jd): year, month, day = jdutil.jd_to_date(jd) # Convert time of day from fraction of day day_fraction = day - int(day) hour, minute, second, ms = jdutil.days_to_hmsm(day_fraction) day = int(day) # This conversion can return negative values for items we do not want to...
Return a `struct_time` converted from a Julian Date float number. WARNING: Conversion to then from Julian Date value to `struct_time` can be inaccurate and lose or gain time, especially for BC (negative) years. NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are set to default values, not real...
def _roll_negative_time_fields(year, month, day, hour, minute, second): if second < 0: minute += int(second / 60.0) # Adjust by whole minute in secs minute -= 1 # Subtract 1 for negative second second %= 60 # Convert negative second to positive remainder if minute < 0: ho...
Fix date/time fields which have nonsense negative values for any field except for year by rolling the overall date/time value backwards, treating negative values as relative offsets of the next higher unit. For example minute=5, second=-63 becomes minute=3, second=57 (5 minutes less 63 seconds) Th...
def get_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name=''): if schema.schema_example: return schema.schema_example if ignored_schemas is None: ignored_schemas = [] if paths is None: paths = [] if name: pat...
Get example by schema object :param Schema schema: current schema :param list ignored_schemas: list of previous schemas for avoid circular references :param list paths: list object paths (ex. #/definitions/Model.property) If nested schemas exists, custom examples checks ...
def get_body_example(cls, operation): path = "#/paths/'{0.path}'/{0.method}/parameters/{name}".format( operation, name=operation.body.name or 'body') return cls.get_example_by_schema(operation.body, paths=[path])
Get example for body parameter example by operation :param Operation operation: operation object
def get_response_example(cls, operation, response): path = "#/paths/'{}'/{}/responses/{}".format( operation.path, operation.method, response.name) kwargs = dict(paths=[path]) if response.type in PRIMITIVE_TYPES: result = cls.get_example_value_for_primitive_type(...
Get example for response object by operation object :param Operation operation: operation object :param Response response: response object
def get_header_example(cls, header): if header.is_array: result = cls.get_example_for_array(header.item) else: example_method = getattr(cls, '{}_example'.format(header.type)) result = example_method(header.properties, header.type_format) return {heade...
Get example for header object :param Header header: Header object :return: example :rtype: dict
def get_property_example(cls, property_, nested=None, **kw): paths = kw.get('paths', []) name = kw.get('name', '') result = None if name and paths: paths = list(map(lambda path: '.'.join((path, name)), paths)) result, path = cls._get_custom_example(paths)...
Get example for property :param dict property_: :param set nested: :return: example value
def mkres(self): for d in DENSITY_TYPES: if d == 'ldpi' and not self.ldpi: continue # skip ldpi if d == 'xxxhdpi' and not self.xxxhdpi: continue # skip xxxhdpi try: path = os.path.join(self.out, 'res/drawable-%s' % d...
Create a directory tree for the resized assets
def get_size_for_density(self, size, target_density): current_size = size current_density = DENSITY_MAP[self.source_density] target_density = DENSITY_MAP[target_density] return int(current_size * (target_density / current_density))
Return the new image size for the target density
def resize_image(self, path, im): # Get the original filename _, filename = os.path.split(path) # Generate the new filename filename = self.get_safe_filename(filename) filename = '%s%s' % (self.prefix if self.prefix else '', filename) # Get the original image s...
Generate assets from the given image and path in case you've already called Image.open
def encode_transit(records): '''Returns the records serialized as Transit/json in utf8''' with StringIO() as buf: writer = Writer(buf, "json") writer.write(records) return buf.getvalue().encode('utf8'f encode_transit(records): '''Returns the records serialized as Transit/json in utf8...
Returns the records serialized as Transit/json in utf8
def push(self, message, callback_arg=None): if message['action'] == 'upsert': message.setdefault('key_names', self.key_names) message['client_id'] = self.client_id message.setdefault('table_name', self.table_name) self._add_message(message, callback_arg) ...
message should be a dict recognized by the Stitch Import API. See https://www.stitchdata.com/docs/integrations/import-api.
def _take_batch(self, min_records): '''If we have enough data to build a batch, returns all the data in the buffer and then clears the buffer.''' if not self._buffer: return [] enough_messages = len(self._buffer) >= min_records enough_time = time.time() - self.time_...
If we have enough data to build a batch, returns all the data in the buffer and then clears the buffer.
def get_parameters_by_location(self, locations=None, excludes=None): result = self.parameters if locations: result = filter(lambda x: x.location_in in locations, result) if excludes: result = filter(lambda x: x.location_in not in excludes, result) return ...
Get parameters list by location :param locations: list of locations :type locations: list or None :param excludes: list of excludes locations :type excludes: list or None :return: list of Parameter :rtype: list
def body(self): body = self.get_parameters_by_location(['body']) return self.root.schemas.get(body[0].type) if body else None
Return body request parameter :return: Body parameter :rtype: Parameter or None
def find(node): if node.parent is None: return node root = node while root.parent is not None: root = root.parent parent = node while parent.parent is not root: grandparent = parent.parent parent.parent = root parent = grandparent return root
Find current canonical representative equivalent to node. Adjust the parent pointer of each node along the way to the root to point directly at the root for inverse-Ackerman-fast access.
def union(a, b): a = find(a) b = find(b) if a is not b: if a.rank < b.rank: a.parent = b elif b.rank < a.rank: b.parent = a else: b.parent = a a.rank += 1
Assert equality of two nodes a and b so find(a) is find(b).
def classes(equivalences): node = OrderedDict() def N(x): if x in node: return node[x] n = node[x] = Node(x) return n for x, y in equivalences: union(N(x), N(y)) eqclass = OrderedDict() for x, n in node.iteritems(): x_ = find(n).element ...
Compute mapping from element to list of equivalent elements. `equivalences` is an iterable of (x, y) tuples representing equivalences x ~ y. Returns an OrderedDict mapping each x to the list of elements equivalent to x.
def ascii2h5(dat_fname, h5_fname): table = np.loadtxt(dat_fname, skiprows=1, dtype='f4') filter_kwargs = dict( chunks=True, compression='gzip', compression_opts=3) # Filter out pixels with all zeros idx = ~np.all(table[:,2:32] < 1.e-5, axis=1) with h5py.File(h5_fname,...
Converts from the original ASCII format of the Chen+ (2014) 3D dust map to the HDF5 format. Args: dat_fname (:obj:`str`): Filename of the original ASCII .dat file. h5_fname (:obj:`str`): Output filename to write the resulting HDF5 file to.
def fetch(clobber=False): dest_dir = fname_pattern = os.path.join(data_dir(), 'chen2014') url = 'http://lamost973.pku.edu.cn/site/Photometric-Extinctions-and-Distances/table2.dat' dat_fname = os.path.join(dest_dir, 'chen2014.dat') h5_fname = os.path.join(dest_dir, 'chen2014.h5') md5 = 'f8a2bc4...
Downloads the Chen et al. (2014) dust map. Args: clobber (Optional[:obj:`bool`]): If ``True``, any existing file will be overwritten, even if it appears to match. If ``False`` (the default), :obj:`fetch()` will attempt to determine if the dataset already exists. This det...
def lpad(msg, symbol, length): if len(msg) >= length: return msg return symbol * (length - len(msg)) + msg
Left-pad a given string (msg) with a character (symbol) for a given number of bytes (length). Return the padded string
def changebase(string, frm, to, minlen=0): if frm == to: return lpad(string, get_code_string(frm)[0], minlen) return encode(decode(string, frm), to, minlen)
Change a string's characters from one base to another. Return the re-encoded string
def num_to_var_int(x): x = int(x) if x < 253: return from_int_to_byte(x) elif x < 65536: return from_int_to_byte(253) + encode(x, 256, 2)[::-1] elif x < 4294967296: return from_int_to_byte(254) + encode(x, 256, 4)[::-1] else: return from_int_to_byte(255) + enc...
(bitcoin-specific): convert an integer into a variable-length integer
def encode(val, base, minlen=0): base, minlen = int(base), int(minlen) code_string = get_code_string(base) result = "" while val > 0: result = code_string[val % base] + result val //= base return code_string[0] * max(minlen - len(result), 0) + result
Given an integer value (val) and a numeric base (base), encode it into the string of symbols with the given base. (with minimum length minlen) Returns the (left-padded) re-encoded val as a string.
def decode(string, base): base = int(base) code_string = get_code_string(base) result = 0 if base == 16: string = string.lower() while len(string) > 0: result *= base result += code_string.find(string[0]) string = string[1:] return result
Given a string (string) and a numeric base (base), decode the string into an integer. Returns the integer
def json_is_base(obj, base): alpha = get_code_string(base) if isinstance(obj, (str, unicode)): for i in range(len(obj)): if alpha.find(obj[i]) == -1: return False return True elif isinstance(obj, (int, long, float)) or obj is None: return True ...
Given a primitive compound Python object (i.e. a dict, string, int, or list) and a numeric base, verify whether or not the object and all relevant sub-components have the given numeric base. Return True if so. Return False if not.
def json_changebase(obj, changer): if isinstance(obj, (str, unicode)): return changer(obj) elif isinstance(obj, (int, long)) or obj is None: return obj elif isinstance(obj, list): return [json_changebase(x, changer) for x in obj] elif isinstance(obj, dict): retur...
Given a primitive compound Python object (i.e. a dict, string, int, or list) and a changer function that takes a primitive Python object as an argument, apply the changer function to the object and each sub-component. Return the newly-reencoded object.
def get_CrossCatClient(client_type, **kwargs): client = None if client_type == 'local': import crosscat.LocalEngine as LocalEngine le = LocalEngine.LocalEngine(**kwargs) client = CrossCatClient(le) elif client_type == 'multiprocessing': import crosscat.MultiprocessingE...
Helper which instantiates the appropriate Engine and returns a Client