Search is not available for this dataset
text
stringlengths
75
104k
def measure_string(self, str): '''Calculates the width of the given string in this font. :param str: the string to measure :return float: width of the string, in pixels ''' style = bacon.text.Style(self) run = bacon.text.GlyphRun(style, str) glyph_layout = bacon....
def is_modified(self): """ Determines whether this record set has been modified since the last retrieval or save. :rtype: bool :returns: ``True` if the record set has been modified, and ``False`` if not. """ for key, val in self._initial_vals.items()...
def delete(self): """ Deletes this record set. """ cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id) cset.add_change('DELETE', self) return self.connection._change_resource_record_sets(cset)
def save(self): """ Saves any changes to this record set. """ cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id) # Record sets can't actually be modified. You have to delete the # existing one and create a new one. Since this happens within a singl...
def delete(filename, delete_v1=True, delete_v2=True): """Remove tags from a file. Keyword arguments: * delete_v1 -- delete any ID3v1 tag * delete_v2 -- delete any ID3v2 tag """ f = open(filename, 'rb+') if delete_v1: try: f.seek(-128, 2) except IOError: ...
def ParseID3v1(data): """Parse an ID3v1 tag, returning a list of ID3v2.4 frames.""" try: data = data[data.index(b'TAG'):] except ValueError: return None if 128 < len(data) or len(data) < 124: return None # Issue #69 - Previous versions of Mutagen, when encountering # ou...
def MakeID3v1(id3): """Return an ID3v1.1 tag string from a dict of ID3v2.4 frames.""" v1 = {} for v2id, name in {"TIT2": "title", "TPE1": "artist", "TALB": "album"}.items(): if v2id in id3: text = id3[v2id].text[0].encode('latin1', 'replace')[:30] else: ...
def __fullread(self, size): """ Read a certain number of bytes from the source file. """ try: if size < 0: raise ValueError('Requested bytes (%s) less than zero' % size) if size > self.__filesize: raise EOFError('Requested %#x of %#x (%s)' % ( ...
def load(self, filename, known_frames=None, translate=True, v2_version=4): """Load tags from a filename. Keyword arguments: * filename -- filename to load tag data from * known_frames -- dict mapping frame IDs to Frame objects * translate -- Update all tags to ID3v2.3/4 interna...
def getall(self, key): """Return all frames with a given name (the list may be empty). This is best explained by examples:: id3.getall('TIT2') == [id3['TIT2']] id3.getall('TTTT') == [] id3.getall('TXXX') == [TXXX(desc='woo', text='bar'), ...
def delall(self, key): """Delete all tags of a given kind; see getall.""" if key in self: del(self[key]) else: key = key + ":" for k in self.keys(): if k.startswith(key): del(self[k])
def loaded_frame(self, tag): """Deprecated; use the add method.""" # turn 2.2 into 2.3/2.4 tags if len(type(tag).__name__) == 3: tag = type(tag).__base__(tag) self[tag.HashKey] = tag
def save(self, filename=None, v1=1, v2_version=4, v23_sep='/'): """Save changes to a file. If no filename is given, the one most recently loaded is used. Keyword arguments: v1 -- if 0, ID3v1 tags will be removed if 1, ID3v1 tags will be updated but not added ...
def delete(self, filename=None, delete_v1=True, delete_v2=True): """Remove tags from a file. If no filename is given, the one most recently loaded is used. Keyword arguments: * delete_v1 -- delete any ID3v1 tag * delete_v2 -- delete any ID3v2 tag """ if filenam...
def __update_common(self): """Updates done by both v23 and v24 update""" if "TCON" in self: # Get rid of "(xx)Foobr" format. self["TCON"].genres = self["TCON"].genres if self.version < self._V23: # ID3v2.2 PIC frames are slightly different. pics ...
def update_to_v24(self): """Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag. """ self.__update_...
def update_to_v23(self): """Convert older (and newer) tags into an ID3v2.3 tag. This updates incompatible ID3v2 frames to ID3v2.3 ones. If you intend to save tags as ID3v2.3, you must call this function at some point. If you want to to go off spec and include some v2.4 frames ...
def load(self, filename, ID3=None, **kwargs): """Load stream and tag information from a file. A custom tag reader may be used in instead of the default mutagen.id3.ID3 object, e.g. an EasyID3 reader. """ if ID3 is None: ID3 = self.ID3 else: # If ...
def unload(self): '''Release all resources associated with the sound.''' if self._handle != -1: lib.UnloadSound(self._handle) self._handle = -1
def play(self, gain=None, pan=None, pitch=None): '''Play the sound as a `one-shot`. The sound will be played to completion. If the sound is played more than once at a time, it will mix with all previous instances of itself. If you need more control over the playback of sounds, see :cl...
def set_loop_points(self, start_sample=-1, end_sample=0): '''Set the loop points within the sound. The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to the entire sound duration. :note: There is currently no API for converting ...
def list_hosted_zones_parser(root, connection): """ Parses the API responses for the :py:meth:`route53.connection.Route53Connection.list_hosted_zones` method. :param lxml.etree._Element root: The root node of the etree parsed response from the API. :param Route53Connection connection: The c...
def adobe_glyph_values(): """return the list of glyph names and their unicode values""" lines = string.split( adobe_glyph_list, '\n' ) glyphs = [] values = [] for line in lines: if line: fields = string.split( line, ';' ) # print fields[1] + ' - ' + fields[0] subfields = string.split( f...
def filter_glyph_names( alist, filter ): """filter `alist' by taking _out_ all glyph names that are in `filter'""" count = 0 extras = [] for name in alist: try: filtered_index = filter.index( name ) except: extras.append( name ) return extras
def dump_encoding( file, encoding_name, encoding_list ): """dump a given encoding""" write = file.write write( " /* the following are indices into the SID name table */\n" ) write( " static const unsigned short " + encoding_name + "[" + repr( len( encoding_list ) ) + "] =\n" ) write( " {\n" ) ...
def dump_array( the_array, write, array_name ): """dumps a given encoding""" write( " static const unsigned char " + array_name + "[" + repr( len( the_array ) ) + "L] =\n" ) write( " {\n" ) line = "" comma = " " col = 0 for value in the_array: line += comma line += "%3d" % ord...
def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "w\n" ) write = file.write count_sid = len( sid_standard_names ) # `mac_extras' contains the list of glyph names in the Macintosh standard # encoding which are not ...
def file_exists( pathname ): """checks that a given file exists""" result = 1 try: file = open( pathname, "r" ) file.close() except: result = None sys.stderr.write( pathname + " couldn't be accessed\n" ) return result
def make_file_list( args = None ): """builds a list of input files from command-line arguments""" file_list = [] # sys.stderr.write( repr( sys.argv[1 :] ) + '\n' ) if not args: args = sys.argv[1 :] for pathname in args: if string.find( pathname, '*' ) >= 0: newpath = g...
def parse_hosted_zone(e_zone, connection): """ This a common parser that allows the passing of any valid HostedZone tag. It will spit out the appropriate HostedZone object for the tag. :param lxml.etree._Element e_zone: The root node of the etree parsed response from the API. :param Route53...
def parse_delegation_set(zone, e_delegation_set): """ Parses a DelegationSet tag. These often accompany HostedZone tags in responses like CreateHostedZone and GetHostedZone. :param HostedZone zone: An existing HostedZone instance to populate. :param lxml.etree._Element e_delegation_set: A Delegatio...
def writeblocks(blocks): """Render metadata block as a byte string.""" data = [] codes = [[block.code, block.write()] for block in blocks] codes[-1][0] |= 128 for code, datum in codes: byte = chr_(code) if len(datum) > 2**24: raise error("b...
def group_padding(blocks): """Consolidate FLAC padding metadata blocks. The overall size of the rendered blocks does not change, so this adds several bytes of padding for each merged block. """ paddings = [b for b in blocks if isinstance(b, Padding)] for p in paddings: ...
def delete(self, filename=None): """Remove Vorbis comments from a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename for s in list(self.metadata_blocks): if isinstance(s, VCFLACDict): ...
def load(self, filename): """Load file information from a filename.""" self.metadata_blocks = [] self.tags = None self.cuesheet = None self.seektable = None self.filename = filename fileobj = StrictFileObject(open(filename, "rb")) try: self.__...
def save(self, filename=None, deleteid3=False): """Save metadata blocks to a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename f = open(filename, 'rb+') try: # Ensure we've got...
def parse_rrset_alias(e_alias): """ Parses an Alias tag beneath a ResourceRecordSet, spitting out the two values found within. This is specific to A records that are set to Alias. :param lxml.etree._Element e_alias: An Alias tag beneath a ResourceRecordSet. :rtype: tuple :returns: A tuple in th...
def parse_rrset_record_values(e_resource_records): """ Used to parse the various Values from the ResourceRecords tags on most rrset types. :param lxml.etree._Element e_resource_records: A ResourceRecords tag beneath a ResourceRecordSet. :rtype: list :returns: A list of resource record s...
def parse_rrset(e_rrset, connection, zone_id): """ This a parser that allows the passing of any valid ResourceRecordSet tag. It will spit out the appropriate ResourceRecordSet object for the tag. :param lxml.etree._Element e_rrset: The root node of the etree parsed response from the API. :p...
def list_resource_record_sets_by_zone_id_parser(e_root, connection, zone_id): """ Parses the API responses for the :py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id` method. :param lxml.etree._Element e_root: The root node of the etree parsed response from ...
def nameservers(self): """ :rtype: list :returns: A list of nameserver strings for this hosted zone. """ # If this HostedZone was instantiated by ListHostedZones, the nameservers # attribute didn't get populated. If the user requests it, we'll # lazy load by quer...
def delete(self, force=False): """ Deletes this hosted zone. After this method is ran, you won't be able to add records, or do anything else with the zone. You'd need to re-create it, as zones are read-only after creation. :keyword bool force: If ``True``, delete the ...
def _add_record(self, record_set_class, name, values, ttl=60, weight=None, region=None,set_identifier=None, alias_hosted_zone_id=None, alias_dns_name=None): """ Convenience method for creating ResourceRecordSets. Most of the calls are basically the same, t...
def create_a_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None, alias_hosted_zone_id=None, alias_dns_name=None): """ Creates and returns an A record attached to this hosted zone. :param str name: The fully qualified name o...
def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates an AAAA record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings...
def create_cname_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates a CNAME record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value str...
def create_mx_record(self, name, values, ttl=60): """ Creates a MX record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (i...
def create_ns_record(self, name, values, ttl=60): """ Creates a NS record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (i...
def create_ptr_record(self, name, values, ttl=60): """ Creates a PTR record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
def create_spf_record(self, name, values, ttl=60): """ Creates a SPF record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
def create_srv_record(self, name, values, ttl=60): """ Creates a SRV record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
def create_txt_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None): """ Creates a TXT record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings ...
def RegisterTXXXKey(cls, key, desc): """Register a user-defined text frame key. Some ID3 tags are stored in TXXX frames, which allow a freeform 'description' which acts as a subkey, e.g. TXXX:BARCODE.:: EasyID3.RegisterTXXXKey('barcode', 'BARCODE'). """ fram...
def get_change_values(change): """ In the case of deletions, we pull the change values for the XML request from the ResourceRecordSet._initial_vals dict, since we want the original values. For creations, we pull from the attributes on ResourceRecordSet. Since we're dealing with attributes vs. dict ...
def write_change(change): """ Creates an XML element for the change. :param tuple change: A change tuple from a ChangeSet. Comes in the form of ``(action, rrset)``. :rtype: lxml.etree._Element :returns: A fully baked Change tag. """ action, rrset = change change_vals = get_cha...
def change_resource_record_set_writer(connection, change_set, comment=None): """ Forms an XML string that we'll send to Route53 in order to change record sets. :param Route53Connection connection: The connection instance used to query the API. :param change_set.ChangeSet change_set: The Cha...
def init_logs(): """Initiate log file.""" start_time = dt.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M') logname = os.path.join(os.path.expanduser("~") + "/nanoGUI_" + start_time + ".log") handlers = [logging.FileHandler(logname)] logging.basicConfig( format='%(asctime)s %(message)s', ...
def validate_integer(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): """Check if text Entry is valid (number). I have no idea what all these arguments are doing here but took this from https://stackoverflow.com/ques...
def alias_item(self, alias): """Gets an item by its alias.""" ident = self.alias[alias] return self.items[ident]
def freeze_dict(dict_): """Freezes ``dict`` into ``tuple``. A typical usage is packing ``dict`` into hashable. e.g.:: >>> freeze_dict({'a': 1, 'b': 2}) (('a', 1), ('b', 2)) """ pairs = dict_.items() key_getter = operator.itemgetter(0) return tuple(sorted(pairs, key=key_get...
def join_html_attrs(attrs): """Joins the map structure into HTML attributes. The return value is a 2-tuple ``(template, ordered_values)``. It should be passed into :class:`markupsafe.Markup` to prevent XSS attacked. e.g.:: >>> join_html_attrs({'href': '/', 'data-active': 'true'}) ('da...
def init_app(self, app): """Initializes an app to work with this extension. The app-context signals will be subscribed and the template context will be initialized. :param app: the :class:`flask.Flask` app instance. """ # connects app-level signals appcontext_pu...
def initialize_bars(self, sender=None, **kwargs): """Calls the initializers of all bound navigation bars.""" for bar in self.bars.values(): for initializer in bar.initializers: initializer(self)
def bind_bar(self, sender=None, **kwargs): """Binds a navigation bar into this extension instance.""" bar = kwargs.pop('bar') self.bars[bar.name] = bar
def args(self): """The arguments which will be passed to ``url_for``. :type: :class:`dict` """ if self._args is None: return {} if callable(self._args): return dict(self._args()) return dict(self._args)
def url(self): """The final url of this navigation item. By default, the value is generated by the :attr:`self.endpoint` and :attr:`self.args`. .. note:: The :attr:`url` property require the app context without a provided config value :const:`SERVER_NAME`, becaus...
def is_current(self): """``True`` if current request has same endpoint with the item. The property should be used in a bound request context, or the :class:`RuntimeError` may be raised. """ if not self.is_internal: return False # always false for external url ...
def lang(self, language): """Set lang""" if isinstance(language, str): self._lang = [language] elif isinstance(language, collections.Iterable): self._lang = list(language) if any(lang not in self._supported_langs for lang in self._lang): raise BadArgu...
def config_path(self, value): """Set config_path""" self._config_path = value or '' if not isinstance(self._config_path, str): raise BadArgumentError("config_path must be string: {}".format( self._config_path))
def dictionary(self, value): """Set dictionary""" self._dictionary = value or {} if not isinstance(self._dictionary, dict): raise BadArgumentError("dictionary must be dict: {}".format( self._dictionary))
def api_options(self): """ current spelling settings :return: api options as number """ options = 0 if self._ignore_uppercase: options |= 1 if self._ignore_digits: options |= 2 if self._ignore_urls: options |= 4 ...
def validate(metric_class): """ Does basic Metric option validation. """ if not hasattr(metric_class, 'label'): raise ImproperlyConfigured("No 'label' attribute found for metric %s." % metric_class.__name__) if not hasattr(metric_class, 'widget'): raise ImproperlyConfigured("No...
def get_statistic_by_name(stat_name): """ Fetches a statistics based on the given class name. Does a look-up in the gadgets' registered statistics to find the specified one. """ if stat_name == 'ALL': return get_statistic_models() for stat in get_statistic_models(): if stat.__n...
def calculate_statistics(stat, frequencies): """ Calculates all of the metrics associated with the registered gadgets. """ stats = ensure_list(stat) frequencies = ensure_list(frequencies) for stat in stats: for f in frequencies: print "Calculating %s (%s)..." % (stat.__name_...
def reset_statistics(stat, frequencies, reset_cumulative, recalculate=False): """ Resets the specified statistic's data (deletes it) for the given frequency/ies. """ stats = ensure_list(stat) frequencies = ensure_list(frequencies) for s in stats: for f in frequencies: i...
def autodiscover(): """ Auto-discover INSTALLED_APPS gadgets.py modules and fail silently when not present. This forces an import on them to register any gadgets they may want. """ from django.conf import settings from django.utils.importlib import import_module from django.utils.module_...
def csv_dump(request, uid): """ Returns a CSV dump of all of the specified metric's counts and cumulative counts. """ metric = Metric.objects.get(uid=uid) frequency = request.GET.get('frequency', settings.STATISTIC_FREQUENCY_DAILY) response = HttpResponse(mimetype='text/csv') response[...
def calculate(cls, frequency=settings.STATISTIC_FREQUENCY_DAILY, verbose=settings.STATISTIC_CALCULATION_VERBOSE): """ Runs the calculator for this type of statistic. """ if verbose: print _("Calculating statistics for %(class)s...") % {'class': cls.get_label()} start...
def handle(self, *args, **kwargs): """ Command handler for the "metrics" command. """ frequency = kwargs['frequency'] frequencies = settings.STATISTIC_FREQUENCY_ALL if frequency == 'a' else (frequency.split(',') if ',' in frequency else [frequency]) if kwargs['list']: ...
def get_GET_array(request, var_name, fail_silently=True): """ Returns the GET array's contents for the specified variable. """ vals = request.GET.getlist(var_name) if not vals: if fail_silently: return [] else: raise Exception, _("No array called '%(varname)s...
def get_GET_bool(request, var_name, default=True): """ Tries to extract a boolean variable from the specified request. """ val = request.GET.get(var_name, default) if isinstance(val, str) or isinstance(val, unicode): val = True if val[0] == 't' else False return val
def get_next_colour(): """ Gets the next colour in the Geckoboard colour list. """ colour = settings.GECKOBOARD_COLOURS[get_next_colour.cur_colour] get_next_colour.cur_colour += 1 if get_next_colour.cur_colour >= len(settings.GECKOBOARD_COLOURS): get_next_colour.cur_colour = 0 ret...
def get_gecko_params(request, uid=None, days_back=0, cumulative=True, frequency=settings.STATISTIC_FREQUENCY_DAILY, min_val=0, max_val=100, chart_type='standard', percentage='show', sort=False): """ Returns the default GET parameters for a particular Geckoboard view request. """ return { ...
def geckoboard_number_widget(request): """ Returns a number widget for the specified metric's cumulative total. """ params = get_gecko_params(request, days_back=7) metric = Metric.objects.get(uid=params['uid']) try: latest_stat = metric.statistics.filter(frequency=params['frequency']).o...
def geckoboard_rag_widget(request): """ Searches the GET variables for metric UIDs, and displays them in a RAG widget. """ params = get_gecko_params(request) print params['uids'] max_date = datetime.now()-timedelta(days=params['days_back']) metrics = Metric.objects.filter(uid__in=param...
def geckoboard_pie_chart(request): """ Shows a pie chart of the metrics in the uids[] GET variable array. """ params = get_gecko_params(request, cumulative=True) from_date = datetime.now()-timedelta(days=params['days_back']) metrics = Metric.objects.filter(uid__in=params['uids']) results =...
def geckoboard_line_chart(request): """ Returns the data for a line chart for the specified metric. """ params = get_gecko_params(request, cumulative=False, days_back=7) metric = Metric.objects.get(uid=params['uid']) start_date = datetime.now()-timedelta(days=params['days_back']) stats = [...
def geckoboard_geckometer(request): """ Returns a Geck-o-Meter control for the specified metric. """ params = get_gecko_params(request, cumulative=True) metric = Metric.objects.get(uid=params['uid']) return (metric.latest_count(frequency=params['frequency'], count=not params['cumulative'], ...
def geckoboard_funnel(request, frequency=settings.STATISTIC_FREQUENCY_DAILY): """ Returns a funnel chart for the metrics specified in the GET variables. """ # get all the parameters for this function params = get_gecko_params(request, cumulative=True) metrics = Metric.objects.filter(uid__in=par...
def get_active_stats(self): """ Returns all of the active statistics for the gadgets currently registered. """ stats = [] for gadget in self._registry.values(): for s in gadget.stats: if s not in stats: stats.append(s) retur...
def register(self, gadget): """ Registers a gadget object. If a gadget is already registered, this will raise AlreadyRegistered. """ if gadget in self._registry: raise AlreadyRegistered else: self._registry.append(gadget)
def unregister(self, gadgets): """ Unregisters the specified gadget(s) if it/they has/have already been registered. "gadgets" can be a single class or a tuple/list of classes to unregister. """ gadgets = maintenance.ensure_list(gadgets) for gadget in gadgets: ...
def get_context_data(self, **kwargs): """ Get the context for this view. """ #max_columns, max_rows = self.get_max_dimension() context = { 'gadgets': self._registry, 'columns': self.columns, 'rows': self.rows, 'column_ratio': 100 - ...
def error(self, message, code=1): """ Print error and stop command """ print >>sys.stderr, message sys.exit(code)
def get_model(self, model_name): """ TODO: Need to validate model name has 2x '.' chars """ klass = None try: module_name, class_name = model_name.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) klass = getattr(mod, class_na...
def custom(self, code, message): """ Specific server side errors use: -32000 to -32099 reserved for implementation-defined server-errors """ if -32000 < code or -32099 > code: code = -32603 message = 'Internal error' return JResponse(jsonrpc={ ...
def decode(request): """ Get/decode/validate json from request """ try: data = yield from request.json(loader=json.loads) except Exception as err: raise ParseError(err) try: validate(data, REQ_JSONRPC20) except ValidationError as err: raise InvalidRequest(err) ex...
def valid(schema=None): """ Validation data by specific validictory configuration """ def dec(fun): @wraps(fun) def d_func(self, ctx, data, *a, **kw): try: validate(data['params'], schema) except ValidationError as err: ...
def __run(self, ctx): """ Run service """ try: data = yield from decode(ctx) except ParseError: return JError().parse() except InvalidRequest: return JError().request() except InternalError: return JError().internal() try: ...
def string_input(prompt=''): """Python 3 input()/Python 2 raw_input()""" v = sys.version[0] if v == '3': return input(prompt) else: return raw_input(prompt)