docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Remove a detector. Args: detector_id (string): the ID of the detector.
def delete_detector(self, detector_id, **kwargs): resp = self._delete(self._u(self._DETECTOR_ENDPOINT_SUFFIX, detector_id), **kwargs) resp.raise_for_status() # successful delete returns 204, which has no response json ...
632,865
Authenticate a user with SignalFx to acquire a session token. Note that data ingest can only be done with an organization or team API access token, not with a user token obtained via this method. Args: email (string): the email login password (string): the password ...
def login(self, email, password): r = requests.post('{0}/v2/session'.format(self._api_endpoint), json={'email': email, 'password': password}) r.raise_for_status() return r.json()['accessToken']
632,872
Determine the current AWS unique ID Args: timeout (int): How long to wait for a response from AWS metadata IP
def get_aws_unique_id(timeout=DEFAULT_AWS_TIMEOUT): try: resp = requests.get(AWS_ID_URL, timeout=timeout).json() except requests.exceptions.ConnectTimeout: _logger.warning('Connection timeout when determining AWS unique ' 'ID. Not using AWS unique ID.') retur...
632,895
Do something with a cloned repo. Args: path: Path to the repo. api: An instance of :py:class:`repobee.github_api.GitHubAPI`. Returns: optionally returns a HookResult namedtuple for reporting the outcome of the hook. May also return None, in which case no...
def act_on_cloned_repo(self, path: Union[str, pathlib.Path], api) -> Optional[HookResult]:
633,320
Returns list of all catalogs created on this API key Args: Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of catalog objects Example: >>> catalog.list_catalogs() [<catalog - tes...
def list_catalogs(results=30, start=0): result = util.callm("%s/%s" % ('catalog', 'list'), {'results': results, 'start': start}) cats = [Catalog(**util.fix(d)) for d in result['response']['catalogs']] start = result['response']['start'] total = result['response']['total'] return ResultList(cats...
633,697
Create a catalog object (get a catalog by ID or get or create one given by name and type) Args: id (str): A catalog id or name Kwargs: type (str): 'song' or 'artist', specifying the catalog type Returns: A catalog object Example: >>> c = c...
def __init__(self, id, type=None, **kwargs): super(Catalog, self).__init__(id, type, **kwargs)
633,698
Song class Args: id (str): a song ID Kwargs: buckets (list): A list of strings specifying which buckets to retrieve Returns: A Song object Example: >>> s = song.Song('SOPEXHZ12873FD2AC7', buckets=['song_hotttnesss', 'artist_hotttn...
def __init__(self, id, buckets=None, **kwargs): buckets = buckets or [] super(Song, self).__init__(id, buckets, **kwargs)
633,715
Get the types of a song. Args: cache (boolean): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A list of strings, each representing a song type: 'christmas', for example. ...
def get_song_type(self, cache=True): if not (cache and ('song_type' in self.cache)): response = self.get_attribute('profile', bucket='song_type') if response['songs'][0].has_key('song_type'): self.cache['song_type'] = response['songs'][0]['song_type'] ...
633,718
Get the location of a song's artist. Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: An artist location object. Example: >>> s = song.Song('SOQKVPH12A...
def get_artist_location(self, cache=True): if not (cache and ('artist_location' in self.cache)): response = self.get_attribute('profile', bucket='artist_location') self.cache['artist_location'] = response['songs'][0]['artist_location'] return self.cache['artist_location'...
633,721
Create a track object from a public http URL. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: url: A string giving the URL to read from. This must be on a public machine accessible by HTTP. Example: >>> t = track.track_from_url("htt...
def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT): param_dict = dict(url = url) return _upload(param_dict, timeout, data=None)
633,752
Create a track object from an Echo Nest track ID. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: identifier: A string containing the ID of a previously analyzed track. Example: >>> t = track.track_from_id("TRWFIDS128F92CC4CA") ...
def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT): param_dict = dict(id = identifier) return _profile(param_dict, timeout)
633,753
Create a track object from an md5 hash. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: md5: A string 32 characters long giving the md5 checksum of a track already analyzed. Example: >>> t = track.track_from_md5('b8abf85746ab3416ada...
def track_from_md5(md5, timeout=DEFAULT_ASYNC_TIMEOUT): param_dict = dict(md5 = md5) return _profile(param_dict, timeout)
633,754
Returns a list of all assets available in this sandbox Args: sandbox_name (str): A string representing the name of the sandbox Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: ...
def list(sandbox_name, results=15, start=0): result = util.callm("%s/%s" % ('sandbox', 'list'), {'sandbox':sandbox_name, 'results': results, 'start': start}) assets = result['response']['assets'] start = result['response']['start'] total = result['response']['total'] return ResultList(assets, ...
633,757
Artist class Args: id (str): an artistw ID Returns: An artist object Example: >>> a = artist.Artist('ARH6W4X1187B99274F', buckets=['hotttnesss']) >>> a.hotttnesss 0.80098515900997658 >>>
def __init__(self, id, **kwargs): super(Artist, self).__init__(id, **kwargs)
633,764
Get the foreign id for this artist for a specific id space Args: Kwargs: idspace (str): A string indicating the idspace to fetch a foreign id for. Returns: A foreign ID string Example: >>> a = artist.Artist('fab...
def get_foreign_id(self, idspace='musicbrainz', cache=True): if not (cache and ('foreign_ids' in self.cache) and filter(lambda d: d.get('catalog') == idspace, self.cache['foreign_ids'])): response = self.get_attribute('profile', bucket=['id:'+idspace]) foreign_ids = response['ar...
633,767
Get the twitter id for this artist if it exists Args: Kwargs: Returns: A twitter ID string Example: >>> a = artist.Artist('big boi') >>> a.get_twitter_id() u'BigBoi' >>>
def get_twitter_id(self, cache=True): if not (cache and ('twitter' in self.cache)): response = self.get_attribute('twitter') self.cache['twitter'] = response['artist'].get('twitter') return self.cache['twitter']
633,768
Parse the lines of an os-release file. Parameters: * lines: Iterable through the lines in the os-release file. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items.
def _parse_os_release_content(lines): props = {} lexer = shlex.shlex(lines, posix=True) lexer.whitespace_split = True # The shlex module defines its `wordchars` variable using literals, # making it dependent on the encoding of the Python source file. # In Python...
634,970
Copy font attributes from `ufo` either to `self.font` or to `master`. Arguments: self -- The UFOBuilder ufo -- The current UFO being read master -- The current master being written is_initial -- True iff this the first UFO that we process
def to_glyphs_font_attributes(self, source, master, is_initial): if is_initial: _set_glyphs_font_attributes(self, source) else: _compare_and_merge_glyphs_font_attributes(self, source)
636,466
Sends all filters to the API. No fancy, just a wrapper. Any advanced functionality shall be implemented as another method. Args: filters: List of filters (strings) Returns: :py:class:`SearchResult`
def raw_filter(self, filters): return SearchResult(self, self._api.get(self._href, **{"filter[]": filters}))
636,696
Parses glyphs custom filter string into a dict object that ufo2ft can consume. Reference: ufo2ft: https://github.com/googlei18n/ufo2ft Glyphs 2.3 Handbook July 2016, p184 Args: filter_str - a string of glyphs app filter Return: A dictiona...
def parse_glyphs_filter(filter_str, is_pre=False): elements = filter_str.split(";") if elements[0] == "": logger.error( "Failed to parse glyphs filter, expecting a filter name: \ %s", filter_str, ) return None result = {"name": elements[0]}...
636,718
Joint distribution of values from pmf1 and pmf2. Args: pmf1: Pmf object pmf2: Pmf object Returns: Joint pmf of value pairs
def MakeJoint(pmf1, pmf2): joint = Joint() for v1, p1 in pmf1.Items(): for v2, p2 in pmf2.Items(): joint.Set((v1, v2), p1 * p2) return joint
637,272
Makes a histogram from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this histogram Returns: Hist object
def MakeHistFromList(t, name=''): hist = Hist(name=name) [hist.Incr(x) for x in t] return hist
637,273
Makes a PMF from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this PMF Returns: Pmf object
def MakePmfFromList(t, name=''): hist = MakeHistFromList(t) d = hist.GetDict() pmf = Pmf(d, name) pmf.Normalize() return pmf
637,274
Makes a PMF from a map from values to probabilities. Args: d: dictionary that maps values to probabilities name: string name for this PMF Returns: Pmf object
def MakePmfFromDict(d, name=''): pmf = Pmf(d, name) pmf.Normalize() return pmf
637,275
Makes a PMF from a sequence of value-probability pairs Args: t: sequence of value-probability pairs name: string name for this PMF Returns: Pmf object
def MakePmfFromItems(t, name=''): pmf = Pmf(dict(t), name) pmf.Normalize() return pmf
637,276
Makes a normalized PMF from a Hist object. Args: hist: Hist object name: string name Returns: Pmf object
def MakePmfFromHist(hist, name=None): if name is None: name = hist.name # make a copy of the dictionary d = dict(hist.GetDict()) pmf = Pmf(d, name) pmf.Normalize() return pmf
637,277
Makes a normalized Pmf from a Cdf object. Args: cdf: Cdf object name: string name for the new Pmf Returns: Pmf object
def MakePmfFromCdf(cdf, name=None): if name is None: name = cdf.name pmf = Pmf(name=name) prev = 0.0 for val, prob in cdf.Items(): pmf.Incr(val, prob - prev) prev = prob return pmf
637,278
Make a mixture distribution. Args: metapmf: Pmf that maps from Pmfs to probs. name: string name for the new Pmf. Returns: Pmf object.
def MakeMixture(metapmf, name='mix'): mix = Pmf(name=name) for pmf, p1 in metapmf.Items(): for x, p2 in pmf.Items(): mix.Incr(x, p1 * p2) return mix
637,279
Makes a cdf from an unsorted sequence of (value, frequency) pairs. Args: items: unsorted sequence of (value, frequency) pairs name: string name for this CDF Returns: cdf: list of (value, fraction) pairs
def MakeCdfFromItems(items, name=''): runsum = 0 xs = [] cs = [] for value, count in sorted(items): runsum += count xs.append(value) cs.append(runsum) total = float(runsum) ps = [c / total for c in cs] cdf = Cdf(xs, ps, name) return cdf
637,281
Makes a CDF from a Pmf object. Args: pmf: Pmf.Pmf object name: string name for the data. Returns: Cdf object
def MakeCdfFromPmf(pmf, name=None): if name == None: name = pmf.name return MakeCdfFromItems(pmf.Items(), name)
637,282
Makes a suite from an unsorted sequence of values. Args: t: sequence of numbers name: string name for this suite Returns: Suite object
def MakeSuiteFromList(t, name=''): hist = MakeHistFromList(t) d = hist.GetDict() return MakeSuiteFromDict(d)
637,283
Makes a normalized suite from a Hist object. Args: hist: Hist object name: string name Returns: Suite object
def MakeSuiteFromHist(hist, name=None): if name is None: name = hist.name # make a copy of the dictionary d = dict(hist.GetDict()) return MakeSuiteFromDict(d, name)
637,284
Makes a suite from a map from values to probabilities. Args: d: dictionary that maps values to probabilities name: string name for this suite Returns: Suite object
def MakeSuiteFromDict(d, name=''): suite = Suite(name=name) suite.SetDict(d) suite.Normalize() return suite
637,285
Makes a normalized Suite from a Cdf object. Args: cdf: Cdf object name: string name for the new Suite Returns: Suite object
def MakeSuiteFromCdf(cdf, name=None): if name is None: name = cdf.name suite = Suite(name=name) prev = 0.0 for val, prob in cdf.Items(): suite.Incr(val, prob - prev) prev = prob return suite
637,286
Computes a credible interval for a given distribution. If percentage=90, computes the 90% CI. Args: pmf: Pmf object representing a posterior distribution percentage: float between 0 and 100 Returns: sequence of two floats, low and high
def CredibleInterval(pmf, percentage=90): cdf = pmf.MakeCdf() prob = (1 - percentage / 100.0) / 2 interval = cdf.Value(prob), cdf.Value(1 - prob) return interval
637,288
Probability that a value from pmf1 is less than a value from pmf2. Args: pmf1: Pmf object pmf2: Pmf object Returns: float probability
def PmfProbLess(pmf1, pmf2): total = 0.0 for v1, p1 in pmf1.Items(): for v2, p2 in pmf2.Items(): if v1 < v2: total += p1 * p2 return total
637,289
Evaluates the inverse CDF of the gaussian distribution. See http://en.wikipedia.org/wiki/Normal_distribution#Quantile_function Args: p: float mu: mean parameter sigma: standard deviation parameter Returns: float
def GaussianCdfInverse(p, mu=0, sigma=1): x = ROOT2 * erfinv(2 * p - 1) return mu + x * sigma
637,297
Returns a copy. Make a shallow copy of d. If you want a deep copy of d, use copy.deepcopy on the whole object. Args: name: string name for the new Hist
def Copy(self, name=None): new = copy.copy(self) new.d = copy.copy(self.d) new.name = name if name is not None else self.name return new
637,306
Increments the freq/prob associated with the value x. Args: x: number value term: how much to increment by
def Incr(self, x, term=1): self.d[x] = self.d.get(x, 0) + term
637,311
Scales the freq/prob associated with the value x. Args: x: number value factor: how much to multiply by
def Mult(self, x, factor): self.d[x] = self.d.get(x, 0) * factor
637,312
Normalizes this PMF so the sum of all probs is fraction. Args: fraction: what the total should be after normalization Returns: the total probability before normalizing
def Normalize(self, fraction=1.0): if self.log: raise ValueError("Pmf is under a log transform") total = self.Total() if total == 0.0: raise ValueError('total probability is zero.') logging.warning('Normalize: total probability is zero.') ...
637,319
Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance
def Var(self, mu=None): if mu is None: mu = self.Mean() var = 0.0 for x, p in self.d.iteritems(): var += p * (x - mu) ** 2 return var
637,322
Returns a copy of this Cdf. Args: name: string name for the new Cdf
def Copy(self, name=None): if name is None: name = self.name return Cdf(list(self.xs), list(self.ps), name)
637,332
Returns CDF(x), the probability that corresponds to value x. Args: x: number Returns: float probability
def Prob(self, x): if x < self.xs[0]: return 0.0 index = bisect.bisect(self.xs, x) p = self.ps[index - 1] return p
637,336
Returns InverseCDF(p), the value that corresponds to probability p. Args: p: number in the range [0, 1] Returns: number value
def Value(self, p): if p < 0 or p > 1: raise ValueError('Probability p must be in range [0, 1]') if p == 0: return self.xs[0] if p == 1: return self.xs[-1] index = bisect.bisect(self.ps, p) if p == self.ps[index - 1]: return self.xs[index - 1] ...
637,337
Computes the central credible interval. If percentage=90, computes the 90% CI. Args: percentage: float between 0 and 100 Returns: sequence of two floats, low and high
def CredibleInterval(self, percentage=90): prob = (1 - percentage / 100.0) / 2 interval = self.Value(prob), self.Value(1 - prob) return interval
637,339
Updates a suite of hypotheses based on new data. Modifies the suite directly; if you want to keep the original, make a copy. Note: unlike Update, LogUpdate does not normalize. Args: data: any representation of the data
def LogUpdate(self, data): for hypo in self.Values(): like = self.LogLikelihood(data, hypo) self.Incr(hypo, like)
637,342
select sentences in terms of maximum coverage problem Args: text: text to be summarized (unicode string) char_limit: summary length (the number of characters) Returns: list of extracted sentences Reference: Hiroya Takamura, Manabu Okumura. Text summarization model based on m...
def summarize(text, char_limit, sentence_filter=None, debug=False): debug_info = {} sents = list(tools.sent_splitter_ja(text)) words_list = [ # pulp variables should be utf-8 encoded w.encode('utf-8') for s in sents for w in tools.word_segmenter_ja(s) ] tf = collections.Counte...
637,619
Constructor. Args: api_key: string, a key for API authentication. db_path: string, path to SQLite DB file to store cached data. discard_fair_use_policy: boolean, disable request frequency throttling (only for testing). platforms: list, threat lists to look up, de...
def __init__(self, api_key, db_path='/tmp/gsb_v4.db', discard_fair_use_policy=False, platforms=None, timeout=10): self.api_client = SafeBrowsingApiClient(api_key, discard_fair_use_policy=discard_fair_use_policy) self.storage = SqliteStorage(db_path, timeout=timeout) sel...
637,680
Aggregate one repo according to the args. Args: repo (Repo): The repository to aggregate. args (argparse.Namespace): CLI arguments.
def aggregate_repo(repo, args, sem, err_queue): try: logger.debug('%s' % repo) dirmatch = args.dirmatch if not match_dir(repo.cwd, dirmatch): logger.info("Skip %s", repo.cwd) return if args.command == 'aggregate': repo.aggregate() ...
637,770
Checks if the student's query returned a result. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the student's query did not return a result.
def has_result(state, incorrect_msg="Your query did not return a result."): # first check if there is no error has_no_error(state) if not state.solution_result: raise NameError( "You are using has_result() to verify that the student query generated an error, but the solution query...
637,774
Test whether the student and solution query results have equal numbers of rows. Args: incorrect_msg: If specified, this overrides the automatically generated feedback message in case the number of rows in the student and solution query don't match.
def has_nrows( state, incorrect_msg="Your query returned a table with {{n_stu}} row{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} row{{'s' if n_sol > 1 else ''}}.", ): # check that query returned something has_result(state) # assumes that columns cannot be jagged i...
637,775
Wrap each frame in a Colr object, using `Colr.gradient`. Arguments: name : Starting color name. One of `Colr.gradient_names`.
def as_gradient(self, name=None, style=None, rgb_mode=False): return self._as_gradient( ('wrapper', ), name=name, style=style, rgb_mode=rgb_mode, )
637,845
Calculate a single rgb value for a piece of a rainbow. Arguments: freq : "Tightness" of colors (see self.rainbow()) i : Index of character in string to colorize.
def _rainbow_rgb(self, freq, i): # Borrowed from lolcat, translated from ruby. red = math.sin(freq * i + 0) * 127 + 128 green = math.sin(freq * i + 2 * math.pi / 3) * 127 + 128 blue = math.sin(freq * i + 4 * math.pi / 3) * 127 + 128 return int(red), int(green), int(blue)
638,154
A chained method that sets the back color to an RGB value. Arguments: r : Red value. g : Green value. b : Blue value. text : Text to style if not building up color codes. fore : Fore color for the text. ...
def b_rgb(self, r, g, b, text=None, fore=None, style=None): return self.chained(text=text, fore=fore, back=(r, g, b), style=style)
638,156
Called by the various 'color' methods to colorize a single string. The RESET_ALL code is appended to the string unless text is empty. Raises ValueError on invalid color names. Arguments: text : String to colorize, or None for BG/Style change. fore ...
def chained(self, text=None, fore=None, back=None, style=None): self.data = ''.join(( self.data, self.color(text=text, fore=fore, back=back, style=style), )) return self
638,157
A chained method that sets the fore color to an hex value. Arguments: value : Hex value to convert. text : Text to style if not building up color codes. back : Back color for the text. style : Style for the text. r...
def hex(self, value, text=None, back=None, style=None, rgb_mode=False): if rgb_mode: try: colrval = hex2rgb(value, allow_short=True) except ValueError: raise InvalidColr(value) else: try: colrval = hex2term(valu...
638,165
Like str.join, except it returns a Colr. Arguments: colrs : One or more Colrs. If a list or tuple is passed as an argument it will be flattened. Keyword Arguments: fore, back, style... see color().
def join(self, *colrs, **colorkwargs): flat = [] for clr in colrs: if isinstance(clr, (list, tuple, GeneratorType)): # Flatten any lists, at least once. flat.extend(str(c) for c in clr) else: flat.append(str(clr)) ...
638,166
Save cursor position, write some text, and then restore the position. Arguments: Same as `print()`. Keyword Arguments: Same as `print()`, except `end` defaults to '' (empty str), and these: delay : Time in seconds between character writes.
def print_inplace(*args, **kwargs): kwargs.setdefault('file', sys.stdout) kwargs.setdefault('end', '') pos_save(file=kwargs['file']) delay = None with suppress(KeyError): delay = kwargs.pop('delay') if delay is None: print(*args, **kwargs) else: for c in kwargs.g...
638,191
Move to the beginning of the current line, and print some text. Arguments: Same as `print()`. Keyword Arguments: Same as `print()`, except `end` defaults to '' (empty str), and these: delay : Time in seconds between character writes.
def print_overwrite(*args, **kwargs): kwargs.setdefault('file', sys.stdout) kwargs.setdefault('end', '') delay = None with suppress(KeyError): delay = kwargs.pop('delay') erase_line() # Move to the beginning of the line. move_column(1, file=kwargs['file']) if delay is None: ...
638,193
Compares this instance's fields to the supplied instance to test for equality. This will ignore any fields in `fields_to_ignore`. Note that this method ignores many-to-many fields. Args: instance: the model instance to compare fields_to_ignore: List of fields that shoul...
def fields_equal(self, instance, fields_to_ignore=("id", "change_date", "changed_by")): for field in self._meta.get_fields(): if not field.many_to_many and field.name not in fields_to_ignore: if getattr(instance, field.name) != getattr(self, field.name): ...
638,389
View decorator that enables/disables a view based on configuration. Arguments: config_model (ConfigurationModel subclass): The class of the configuration model to check. Returns: HttpResponse: 404 if the configuration model is disabled, otherwise returns the response fr...
def require_config(config_model): def _decorator(func): @wraps(func) def _inner(*args, **kwargs): if not config_model.current().enabled: return HttpResponseNotFound() return func(*args, **kwargs) return _inner return _dec...
638,394
Parse the command's options. Arguments: options (dict): Options with which the command was called. Raises: CommandError, if a user matching the provided username does not exist.
def _parse_options(self, options): for key in ('username', 'client_name', 'client_id', 'client_secret', 'trusted', 'logout_uri'): value = options.get(key) if value is not None: self.fields[key] = value username = self.fields.pop('username', None) ...
638,868
Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the OpenID Connect claims. secret (str): Secret used to e...
def encode(self, secret, algorithm='HS256'): return jwt.encode(self.claims, secret, algorithm)
638,872
Imports renewable (res) and conventional (conv) generators Args: session : sqlalchemy.orm.session.Session Database session debug: If True, information is printed during process Notes: Connection of generators is done later on in NetworkDing0's method ...
def import_generators(self, session, debug=False): def import_res_generators(): # build query generators_sqla = session.query( self.orm['orm_re_generators'].columns.id, self.orm['orm_re_generators'].columns.subst_id, ...
640,565
Performs grid reinforcement measures for all MV and LV grids Args: Returns:
def reinforce_grid(self): # TODO: Finish method and enable LV case for grid_district in self.mv_grid_districts(): # reinforce MV grid grid_district.mv_grid.reinforce_grid() # reinforce LV grids for lv_load_area in grid_district.lv_load_areas():...
640,582
Exports PyPSA network as CSV files to directory Args: network: pypsa.Network export_dir: str Sub-directory in output/debug/grid/ where csv Files of PyPSA network are exported to.
def export_to_dir(network, export_dir): package_path = ding0.__path__[0] network.export_to_csv_folder(os.path.join(package_path, 'output', 'debug', 'grid', ...
640,599
Class constructor Initialize demand Parameters: name: Node name demand: Node demand
def __init__(self, name, demand): self._name = name self._demand = demand self._allocation = None
640,674
Class constructor Initialize all nodes, edges and depot Parameters: data: TSPLIB parsed data
def __init__(self, data): self._coord = data['NODE_COORD_SECTION'] self._nodes = {i: Node(i, data['DEMAND'][i]) for i in data['MATRIX']} self._matrix = {} self._depot = None self._branch_kind = data['BRANCH_KIND'] self._branch_type = data['BRANCH_TYPE'] ...
640,677
Omits the duplications in the strings files. Keys that appear more than once, will be joined to one appearance and the omit will be documented. Args: file_path (str): The path to the strings file.
def handle_duplications(file_path): logging.info('Handling duplications for "%s"', file_path) f = open_strings_file(file_path, "r+") header_comment_key_value_tuples = extract_header_comment_key_value_tuples_from_file(f) file_elements = [] section_file_elements = [] keys_to_objects = {} ...
640,790
Add comments to the localization entry Args: comments (list of str): The comments to be added to the localization entry.
def add_comments(self, comments): for comment in comments: if comment not in self.comments and len(comment) > 0: self.comments.append(comment) if len(self.comments[0]) == 0: self.comments.pop(0)
640,826
Merges the new translation with the old one. The translated files are saved as '.translated' file, and are merged with old translated file. Args: localization_bundle_path (str): The path to the localization bundle.
def merge_translations(localization_bundle_path): logging.info("Merging translations") for lang_dir in os.listdir(localization_bundle_path): if lang_dir == DEFAULT_LANGUAGE_DIRECTORY_NAME: continue for translated_path in glob.glob(os.path.join(localization_bundle_path, lang_dir,...
640,827
Merges the old strings file with the new one. Args: old_strings_file (str): The path to the old strings file (previously produced, and possibly altered) new_strings_file (str): The path to the new strings file (newly produced).
def merge_strings_files(old_strings_file, new_strings_file): old_localizable_dict = generate_localization_key_to_entry_dictionary_from_file(old_strings_file) output_file_elements = [] f = open_strings_file(new_strings_file, "r+") for header_comment, comments, key, value in extract_header_comment_...
640,890
Adds the necessary supported arguments to the argument parser. Args: parser (argparse.ArgumentParser): The parser to add arguments to.
def configure_parser(self, parser): parser.add_argument("--log_path", default="", help="The log file path") parser.add_argument("--verbose", help="Increase logging verbosity", action="store_true")
640,891
Write elements to the string file Args: file_path (str): The path to the strings file file_elements (list) : List of elements to write to the file.
def write_file_elements_to_strings_file(file_path, file_elements): f = open_strings_file(file_path, "w") for element in file_elements: f.write(unicode(element)) f.write(u"\n") f.close()
640,936
Setup logging module. Args: args (optional): The arguments returned by the argparse module.
def setup_logging(args=None): logging_level = logging.WARNING if args is not None and args.verbose: logging_level = logging.INFO config = {"level": logging_level, "format": "jtlocalize:%(message)s"} if args is not None and args.log_path != "": config["filename"] = args.log_path ...
640,937
Generates a dictionary mapping between keys (defined by the given attribute name) and localization entries. Args: file_path (str): The strings file path. localization_entry_attribute_name_for_key: The name of the attribute of LocalizationEntry to use as key. Returns: dict: A dictionary...
def __generate_localization_dictionary_from_file(file_path, localization_entry_attribute_name_for_key): localization_dictionary = {} f = open_strings_file(file_path, "r+") header_comment_key_value_tuples = extract_header_comment_key_value_tuples_from_file(f) if len(header_comment_key_value_tuples)...
640,938
Extracts tuples representing comments and localization entries from strings file. Args: file_descriptor (file): The file to read the tuples from Returns: list : List of tuples representing the headers and localization entries.
def extract_header_comment_key_value_tuples_from_file(file_descriptor): file_data = file_descriptor.read() findall_result = re.findall(HEADER_COMMENT_KEY_VALUE_TUPLES_REGEX, file_data, re.MULTILINE | re.DOTALL) returned_list = [] for header_comment, _ignored, raw_comments, key, value in findall_re...
640,939
Extracts all string pairs matching the JTL pattern from given text file. This can be used as an "extract_func" argument in the extract_string_pairs_in_directory method. Args: results_dict (dict): The dict to add the the string pairs to. file_path (str): The path of the file from which to extra...
def extract_jtl_string_pairs_from_text_file(results_dict, file_path): result_pairs = re.findall(JTL_REGEX, open(file_path).read()) for result_key, result_comment in result_pairs: results_dict[result_key] = result_comment return results_dict
640,940
Writes a localization entry to the file Args: file_descriptor (file, instance): The file to write the entry to. entry_comment (str): The entry's comment. entry_key (str): The entry's key.
def write_entry_to_file(file_descriptor, entry_comment, entry_key): escaped_key = re.sub(r'([^\\])"', '\\1\\"', entry_key) file_descriptor.write(u'/* %s */\n' % entry_comment) file_descriptor.write(u'"%s" = "%s";\n' % (escaped_key, escaped_key))
640,942
Appends dictionary of localization keys and comments to a file Args: localization_key_to_comment (dict): A mapping between localization keys and comments. file_path (str): The path of the file to append to. section_name (str): The name of the section.
def append_dictionary_to_file(localization_key_to_comment, file_path, section_name): output_file = open_strings_file(file_path, "a") write_section_header_to_file(output_file, section_name) for entry_key, entry_comment in sorted(localization_key_to_comment.iteritems(), key=operator.itemgetter(1)): ...
640,943
Writes dictionary of localization keys and comments to a file. Args: localization_key_to_comment (dict): A mapping between localization keys and comments. file_name (str): The path of the file to append to.
def write_dict_to_new_file(file_name, localization_key_to_comment): output_file_descriptor = open_strings_file(file_name, "w") for entry_key, entry_comment in sorted(localization_key_to_comment.iteritems(), key=operator.itemgetter(1)): write_entry_to_file(output_file_descriptor, entry_comment, entr...
640,944
Find all files matching the given extensions. Args: base_dir (str): Path of base directory to search in. extensions (list): A list of file extensions to search for. exclude_dirs (list): A list of directories to exclude from search. Returns: list of paths that match the search
def find_files(base_dir, extensions, exclude_dirs=list()): result = [] for root, dir_names, file_names in os.walk(base_dir): for filename in file_names: candidate = os.path.join(root, filename) if should_include_file_in_search(candidate, extensions, exclude_dirs): ...
640,945
Whether or not a filename matches a search criteria according to arguments. Args: file_name (str): A file path to check. extensions (list): A list of file extensions file should match. exclude_dirs (list): A list of directories to exclude from search. Returns: A boolean of whet...
def should_include_file_in_search(file_name, extensions, exclude_dirs): return (exclude_dirs is None or not any(file_name.startswith(d) for d in exclude_dirs)) and \ any(file_name.endswith(e) for e in extensions)
640,946
Adds the comments produced by the genstrings script for duplicate keys. Args: localization_file (str): The path to the strings file.
def add_genstrings_comments_to_file(localization_file, genstrings_err): errors_to_log = [line for line in genstrings_err.splitlines() if "used with multiple comments" not in line] if len(errors_to_log) > 0: logging.warning("genstrings warnings:\n%s", "\n".join(errors_to_log)) loc_file = open...
640,970
Prepares the localization bundle for translation. This means, after creating the strings files using genstrings.sh, this will produce '.pending' files, that contain the files that are yet to be translated. Args: localization_bundle_path (str): The path to the localization bundle.
def prepare_for_translation(localization_bundle_path): logging.info("Preparing for translation..") for strings_file in os.listdir(os.path.join(localization_bundle_path, DEFAULT_LANGUAGE_DIRECTORY_NAME)): if not strings_file.endswith(".strings"): continue strings_path = os.pat...
640,985
Extract string pairs in the given directory's xib/storyboard files. Args: directory (str): The path to the directory. exclude_dirs (str): A list of directories to exclude from extraction. special_ui_components_prefix (str): If not None, extraction will not warn about internation...
def extract_string_pairs_in_dir(directory, exclude_dirs, special_ui_components_prefix): result = [] for ib_file_path in find_files(directory, [".xib", ".storyboard"], exclude_dirs): result += extract_string_pairs_in_ib_file(ib_file_path, special_ui_components_prefix) return result
641,033
Extracts the xib element's comment, if the element has been internationalized. Args: element (element): The element from which to extract the comment. Returns: The element's internationalized comment, None if it does not exist, or hasn't been internationalized (according to the JTLocal...
def extract_element_internationalized_comment(element): element_entry_comment = get_element_attribute_or_empty(element, 'userLabel') if element_entry_comment == "": try: element_entry_comment = element.getElementsByTagName('string')[0].firstChild.nodeValue except Exception: ...
641,035
Log a warning if the element is not of the given type (indicating that it is not internationalized). Args: element: The xib's XML element. class_name: The type the element should be, but is missing. special_ui_components_prefix: If provided, will not warn about class with this prefix (defau...
def warn_if_element_not_of_class(element, class_suffix, special_ui_components_prefix): valid_class_names = ["%s%s" % (DEFAULT_UI_COMPONENTS_PREFIX, class_suffix)] if special_ui_components_prefix is not None: valid_class_names.append("%s%s" % (special_ui_components_prefix, class_suffix)) if (no...
641,036
Adds string pairs from a UI element with attributed text Args: results (list): The list to add the results to. attributed_element (element): The element from the xib that contains, to extract the fragments from. comment_prefix (str): The prefix of the comment to use for extracted string ...
def add_string_pairs_from_attributed_ui_element(results, ui_element, comment_prefix): attributed_strings = ui_element.getElementsByTagName('attributedString') if attributed_strings.length == 0: return False attributed_element = attributed_strings[0] fragment_index = 1 for fragment in a...
641,037
Adds string pairs from a label element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. label (element): The label element from the xib, to extract the string pairs from. special_ui_components_prefix (str): If not None, extract...
def add_string_pairs_from_label_element(xib_file, results, label, special_ui_components_prefix): label_entry_comment = extract_element_internationalized_comment(label) if label_entry_comment is None: return warn_if_element_not_of_class(label, 'Label', special_ui_components_prefix) if labe...
641,038
Adds string pairs from a textfield element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. text_field(element): The textfield element from the xib, to extract the string pairs from. special_ui_components_prefix (str): If not N...
def add_string_pairs_from_text_field_element(xib_file, results, text_field, special_ui_components_prefix): text_field_entry_comment = extract_element_internationalized_comment(text_field) if text_field_entry_comment is None: return if text_field.hasAttribute('usesAttributedText') and text_fiel...
641,039
Adds string pairs from a textview element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. text_view(element): The textview element from the xib, to extract the string pairs from. special_ui_components_prefix(str): A custom prefix for inte...
def add_string_pairs_from_text_view_element(xib_file, results, text_view, special_ui_components_prefix): text_view_entry_comment = extract_element_internationalized_comment(text_view) if text_view_entry_comment is None: return if text_view.hasAttribute('usesAttributedText') and text_view.attri...
641,040
Adds strings pairs from a button xib element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. button(element): The button element from the xib, to extract the string pairs from. special_ui_components_prefix(str): A custom prefix for intern...
def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix): button_entry_comment = extract_element_internationalized_comment(button) if button_entry_comment is None: return for state in button.getElementsByTagName('state'): state_name = state.attr...
641,041
Extract the strings pairs (key and comment) from a xib file. Args: file_path (str): The path to the xib file. special_ui_components_prefix (str): If not None, extraction will not warn about internationalized UI components with this class prefix. Returns: list: List of tuple...
def extract_string_pairs_in_ib_file(file_path, special_ui_components_prefix): try: results = [] xmldoc = minidom.parse(file_path) element_name_to_add_func = {'label': add_string_pairs_from_label_element, 'button': add_string_pairs_from_button_element...
641,042
Pretty-print XML like ``xmllint`` does. Arguments: xml (string): Serialized XML
def xmllint_format(xml): parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True) document = ET.fromstring(xml, parser) return ('%s\n%s' % ('<?xml version="1.0" encoding="UTF-8"?>', ET.tostring(document, pretty_print=True).decode('utf-8'))).encode('utf-8')
641,108
Serialize all properties as pretty-printed XML Args: xmllint (boolean): Format with ``xmllint`` in addition to pretty-printing
def to_xml(self, xmllint=False): root = self._tree.getroot() ret = ET.tostring(ET.ElementTree(root), pretty_print=True) if xmllint: ret = xmllint_format(ret) return ret
641,113
Validate an object against a schema Args: obj (dict): schema (dict):
def validate(obj, schema): if isinstance(obj, str): obj = json.loads(obj) return JsonValidator(schema)._validate(obj)
641,130
Do the actual validation Arguments: obj (dict): object to validate Returns: ValidationReport
def _validate(self, obj): report = ValidationReport() if not self.validator.is_valid(obj): for v in self.validator.iter_errors(obj): report.add_error("[%s] %s" % ('.'.join(str(vv) for vv in v.path), v.message)) return report
641,131
Create a workspace for mets_url and run processor through it Args: parameter (string): URL to the parameter
def run_processor( processorClass, ocrd_tool=None, mets_url=None, resolver=None, workspace=None, page_id=None, log_level=None, input_file_grp=None, output_file_grp=None, parameter=None, working_dir=None, ): # pylint: disable=too-man...
641,138