code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def extern_drop_handles(self, context_handle, handles_ptr, handles_len): c = self._ffi.from_handle(context_handle) handles = self._ffi.unpack(handles_ptr, handles_len) c.drop_handles(handles)
Drop the given Handles.
def get_subgroupiteminsertion( cls, itemgroup, model, subgroup, indent) -> str: blanks1 = ' ' * (indent * 4) blanks2 = ' ' * ((indent+5) * 4 + 1) subs = [ f'{blanks1}<element name="{subgroup.name}"', f'{blanks1} minOccurs="0"', f'{blanks1} ...
Return a string defining the required types for the given combination of an exchange item group and a specific variable subgroup of an application model or class |Node|. Note that for `setitems` and `getitems` `setitemType` and `getitemType` are referenced, respectively, and for all oth...
def _maybe_restore_index_levels(self, result): names_to_restore = [] for name, left_key, right_key in zip(self.join_names, self.left_on, self.right_on): if (self.orig_left._is_level_reference(left_key) ...
Restore index levels specified as `on` parameters Here we check for cases where `self.left_on` and `self.right_on` pairs each reference an index level in their respective DataFrames. The joined columns corresponding to these pairs are then restored to the index of `result`. **N...
def validate(self): super().validate() message_dsm = 'Matrix at [%s:%s] is not an instance of '\ 'DesignStructureMatrix or MultipleDomainMatrix.' message_ddm = 'Matrix at [%s:%s] is not an instance of '\ 'DomainMappingMatrix or MultipleDomainMatrix.' ...
Base validation + each cell is instance of DSM or MDM.
def wv45(msg): d = hex2bin(data(msg)) if d[12] == '0': return None ws = bin2int(d[13:15]) return ws
Wake vortex. Args: msg (String): 28 bytes hexadecimal message string Returns: int: Wake vortex level. 0=NIL, 1=Light, 2=Moderate, 3=Severe
def isPlantOrigin(taxid): assert isinstance(taxid, int) t = TaxIDTree(taxid) try: return "Viridiplantae" in str(t) except AttributeError: raise ValueError("{0} is not a valid ID".format(taxid))
Given a taxid, this gets the expanded tree which can then be checked to see if the organism is a plant or not >>> isPlantOrigin(29760) True
def serialize(self, content): content = super(JSONPTemplateEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return '%s(%s)' % (callback, content)
Move rendered content to callback. :return string: JSONP
def bech32_hrp_expand(hrp): return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
Expand the HRP into values for checksum computation.
def load_videos(template, video_length, frame_shape): filenames = tf.gfile.Glob(template) if not filenames: raise ValueError("no files found.") filenames = sorted(filenames) dataset_len = len(filenames) filenames = tf.constant(filenames) dataset = tf.data.Dataset.from_tensor_slices(filenames) dataset ...
Loads videos from files. Args: template: template string for listing the image files. video_length: length of the video. frame_shape: shape of each frame. Returns: dataset: the tf dataset frame by frame. dataset_len: number of the items which is the number of image files. Raises: ValueE...
def setter(self, fset): self.fset = fset if self.attr_write == AttrWriteType.READ: if getattr(self, 'fget', None): self.attr_write = AttrWriteType.READ_WRITE else: self.attr_write = AttrWriteType.WRITE return self
To be used as a decorator. Will define the decorated method as a write attribute method to be called when client writes the attribute
def time_window_cutoff(sw_time, time_cutoff): sw_time = np.array( [(time_cutoff / DAYS) if x > (time_cutoff / DAYS) else x for x in sw_time]) return(sw_time)
Allows for cutting the declustering time window at a specific time, outside of which an event of any magnitude is no longer identified as a cluster
def json(self): if self.board_data: board_dict = json.loads(self.board_data) board_dict['id'] = self.id del board_dict['__version__'] else: board_dict = { 'id': self.id, 'title': '', 'panels': [] } return board_dict
A JSON-encoded description of this board. Format: {'id': board_id, 'title': 'The title of the board', 'panels': [{ 'title': 'The title of the panel' 'data_source': { 'source_type': PanelSource.TYPE, 'refresh_seconds': 600, ...source_specific_details... ...
def install_excepthook(hook_type="color", **kwargs): try: from IPython.core import ultratb except ImportError: import warnings warnings.warn( "Cannot install excepthook, IPyhon.core.ultratb not available") return 1 hook = dict( color=ultratb.ColorTB, ...
This function replaces the original python traceback with an improved version from Ipython. Use `color` for colourful traceback formatting, `verbose` for Ka-Ping Yee's "cgitb.py" version kwargs are the keyword arguments passed to the constructor. See IPython.core.ultratb.py for more info. Return: ...
def make_nxml_from_text(text): text = _escape_xml(text) header = '<?xml version="1.0" encoding="UTF-8" ?>' + \ '<OAI-PMH><article><body><sec id="s1"><p>' footer = '</p></sec></body></article></OAI-PMH>' nxml_str = header + text + footer return nxml_str
Return raw text wrapped in NXML structure. Parameters ---------- text : str The raw text content to be wrapped in an NXML structure. Returns ------- nxml_str : str The NXML string wrapping the raw text input.
def send_media_file(self, filename): cache_timeout = self.get_send_file_max_age(filename) return send_from_directory(self.config['MEDIA_FOLDER'], filename, cache_timeout=cache_timeout)
Function used to send media files from the media folder to the browser.
def extract_value(self, data): errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self.type_: errors.append('Invalid `type` specified') ...
Extract the id key and validate the request structure.
def _parse_canonical_int64(doc): l_str = doc['$numberLong'] if len(doc) != 1: raise TypeError('Bad $numberLong, extra field(s): %s' % (doc,)) return Int64(l_str)
Decode a JSON int64 to bson.int64.Int64.
def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts): if blockchain == 'bitcoin': return btc_is_multisig_script(script, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
Is the given script a multisig script?
def set_wm_wallpaper(img): if shutil.which("feh"): util.disown(["feh", "--bg-fill", img]) elif shutil.which("nitrogen"): util.disown(["nitrogen", "--set-zoom-fill", img]) elif shutil.which("bgs"): util.disown(["bgs", "-z", img]) elif shutil.which("hsetroot"): util.disown(...
Set the wallpaper for non desktop environments.
def _apply_cond(self, apply_fn, grad, var, *args, **kwargs): grad_acc = self.get_slot(var, "grad_acc") def apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs): total_grad = (grad_acc + grad) / tf.cast(self._n_t, grad.dtype) adam_op = apply_fn(total_grad, var, *args, **kwargs) with tf.co...
Apply conditionally if counter is zero.
def subp(cmd): proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() return ReturnTuple(proc.returncode, stdout=out, stderr=err)
Run a command as a subprocess. Return a triple of return code, standard out, standard err.
def _findExpressionStart(self, block): expEndBlock, expEndColumn = self._findExpressionEnd(block) text = expEndBlock.text()[:expEndColumn + 1] if text.endswith(')'): try: return self.findBracketBackward(expEndBlock, expEndColumn, '(') except ValueError: ...
Find start of not finished expression Raise UserWarning, if not found
def excmessage_decorator(description) -> Callable: @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): try: return wrapped(*args, **kwargs) except BaseException: info = kwargs.copy() info['self'] = instance argnames = inspect.getfullargs...
Wrap a function with |augment_excmessage|. Function |excmessage_decorator| is a means to apply function |augment_excmessage| more efficiently. Suppose you would apply function |augment_excmessage| in a function that adds and returns to numbers: >>> from hydpy.core import objecttools >>> def ...
def validate_with_schema(self, model=None, context=None): if self._schema is None or model is None: return result = self._schema.validate( model=model, context=context if self.use_context else None ) return result
Perform model validation with schema
def classifierPredict(testVector, storedVectors): numClasses = storedVectors.shape[0] output = np.zeros((numClasses,)) for i in range(numClasses): output[i] = np.sum(np.minimum(testVector, storedVectors[i, :])) return output
Return overlap of the testVector with stored representations for each object.
def get_urls(htmlDoc, limit=200): soup = BeautifulSoup( htmlDoc ) anchors = soup.findAll( 'a' ) urls = {} counter = 0 for i,v in enumerate( anchors ): href = anchors[i].get( 'href' ) if ('dots' in href and counter < limit): href = href.split('/')[2] text = anc...
takes in html document as string, returns links to dots
def run(image, name=None, command=None, environment=None, ports=None, volumes=None): if ports and not name: abort('The ports flag currently only works if you specify a container name') if ports: ports = [parse_port_spec(p) for p in ports.split(',')] else: ports = None if environm...
Run a docker container. Args: * image: Docker image to run, e.g. orchardup/redis, quay.io/hello/world * name=None: Container name * command=None: Command to execute * environment: Comma separated environment variables in the format NAME=VALUE * ports=None: Comma separated po...
def normalize(value, series, offset=0): r if not _isreal(value): raise RuntimeError("Argument `value` is not valid") if not _isreal(offset): raise RuntimeError("Argument `offset` is not valid") try: smin = float(min(series)) smax = float(max(series)) except: r...
r""" Scale a value to the range defined by a series. :param value: Value to normalize :type value: number :param series: List of numbers that defines the normalization range :type series: list :param offset: Normalization offset, i.e. the returned value will be in the ran...
def get_actions(self, request): actions = super(EntryAdmin, self).get_actions(request) if not actions: return actions if (not request.user.has_perm('zinnia.can_change_author') or not request.user.has_perm('zinnia.can_view_all')): del actions['make_mine'] ...
Define actions by user's permissions.
def parse_json(json_file): if not os.path.exists(json_file): return None try: with open(json_file, "r") as f: info_str = f.readlines() info_str = "".join(info_str) json_info = json.loads(info_str) return unicode2str(json_info) except BaseExcept...
Parse a whole json record from the given file. Return None if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. Returns: A dict of json info.
def search(self, category, term='', index=0, count=100): search_category = self._get_search_prefix_map().get(category, None) if search_category is None: raise MusicServiceException( "%s does not support the '%s' search category" % ( self.service_name, cate...
Search for an item in a category. Args: category (str): The search category to use. Standard Sonos search categories are 'artists', 'albums', 'tracks', 'playlists', 'genres', 'stations', 'tags'. Not all are available for each music service. Call avail...
def set_folder_names(self, folder_names): assert self.root_path is not None path_list = [osp.join(self.root_path, dirname) for dirname in folder_names] self.proxymodel.setup_filter(self.root_path, path_list)
Set folder names
def add_to_inventory(self): if not self.server_attrs: return for addy in self.server_attrs[A.server.PUBLIC_IPS]: self.stack.add_host(addy, self.groups, self.hostvars)
Adds host to stack inventory
def binop_return_dtype(op, left, right): if is_comparison(op): if left != right: raise TypeError( "Don't know how to compute {left} {op} {right}.\n" "Comparisons are only supported between Factors of equal " "dtypes.".format(left=left, op=op, right...
Compute the expected return dtype for the given binary operator. Parameters ---------- op : str Operator symbol, (e.g. '+', '-', ...). left : numpy.dtype Dtype of left hand side. right : numpy.dtype Dtype of right hand side. Returns ------- outdtype : numpy.dtyp...
def headers(self): if self._headers is None: query = CellQuery() query.max_row = '1' feed = self._service.GetCellsFeed(self._ss.id, self.id, query=query) self._headers = feed.entry return [normalize_header(h.ce...
Return the name of all headers currently defined for the table.
def get_instances(self, state_filter=None): instances = [] for instance in self._get_instances(self._get_cluster_group_name(), state_filter): instances.append(Instance(instance.id, instance.dns_name, instance.private_dns_name, ...
Get all the instances filtered by state. @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states
def manage_signal(self, sig, frame): if sig in [signal.SIGINT, signal.SIGTERM]: logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig]) self.kill_request = True self.kill_timestamp = time.time() logger.info("request to stop in progress") else: ...
Manage signals caught by the process Specific behavior for the arbiter when it receives a sigkill or sigterm :param sig: signal caught by the process :type sig: str :param frame: current stack frame :type frame: :return: None
def get_price(ctx, currency): appid = ctx.obj['appid'] title = ctx.obj['title'] item_ = Item(appid, title) item_.get_price_data(currency) click.secho('Lowest price: %s %s' % (item_.price_lowest, item_.price_currency), fg='green')
Prints out market item price.
def create_audit_student_enrollment(self, course_id): audit_enrollment = { "mode": "audit", "course_details": {"course_id": course_id} } resp = self.requester.post( urljoin(self.base_url, self.enrollment_url), json=audit_enrollment ) ...
Creates an audit enrollment for the user in a given course Args: course_id (str): an edX course id Returns: Enrollment: object representing the student enrollment in the provided course
def from_json_file(cls, json_file): with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() return cls.from_dict(json.loads(text))
Constructs a `GPT2Config` from a json file of parameters.
def merge(self, commit_message='', sha=None): parameters = {'commit_message': commit_message} if sha: parameters['sha'] = sha url = self._build_url('merge', base_url=self._api) json = self._json(self._put(url, data=dumps(parameters)), 200) self.merge_commit_sha = json...
Merge this pull request. :param str commit_message: (optional), message to be used for the merge commit :returns: bool
def asStructTime(self, tzinfo=None): dtime = self.asDatetime(tzinfo) if tzinfo is None: return dtime.utctimetuple() else: return dtime.timetuple()
Return this time represented as a time.struct_time. tzinfo is a datetime.tzinfo instance coresponding to the desired timezone of the output. If is is the default None, UTC is assumed.
async def populate_projects(self, force=False): if force or not self.projects: with tempfile.TemporaryDirectory() as tmpdirname: self.projects = await load_json_or_yaml_from_url( self, self.config['project_configuration_url'], os.path.join(tmpd...
Download the ``projects.yml`` file and populate ``self.projects``. This only sets it once, unless ``force`` is set. Args: force (bool, optional): Re-run the download, even if ``self.projects`` is already defined. Defaults to False.
def update_from_yaml(self, path=join('config', 'hdx_dataset_static.yml')): super(Dataset, self).update_from_yaml(path) self.separate_resources()
Update dataset metadata with static metadata from YAML file Args: path (str): Path to YAML dataset metadata. Defaults to config/hdx_dataset_static.yml. Returns: None
def close(self): self._wr_lock.acquire() self._rd_lock.acquire() try: self._running.clear() if self.socket: self._close_socket() if self._inbound_thread: self._inbound_thread.join(timeout=self._parameters['timeout']) ...
Close Socket. :return:
def min_pos(self): if self.__len__() == 0: return ArgumentError('empty set has no minimum positive value.') if self.contains(0): return None positive = [interval for interval in self.intervals if interval.left > 0] if len(positive) == 0: ...
Returns minimal positive value or None.
def longest_one_seg_prefix(self, word): match = self.seg_regex.match(word) if match: return match.group(0) else: return ''
Return longest IPA Unicode prefix of `word` Args: word (unicode): word as IPA string Returns: unicode: longest single-segment prefix of `word`
def colors(self): try: return get_console_info(self._kernel32, self._stream_handle)[:2] except OSError: return WINDOWS_CODES['white'], WINDOWS_CODES['black']
Return the current foreground and background colors.
def memoize_by_args(func): memory = {} @functools.wraps(func) def memoized(*args): if args not in memory.keys(): value = func(*args) memory[args] = value return memory[args] return memoized
Memoizes return value of a func based on args.
def ifusergroup(parser, token): try: tokensp = token.split_contents() groups = [] groups+=tokensp[1:] except ValueError: raise template.TemplateSyntaxError("Tag 'ifusergroup' requires at least 1 argument.") nodelist_true = parser.parse(('else', 'endifusergroup')) token = ...
Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins Clients Sellers %} ... {% else %} ... {% endifusergroup %}
def feedback_form(context): user = None url = None if context.get('request'): url = context['request'].path if context['request'].user.is_authenticated(): user = context['request'].user return { 'form': FeedbackForm(url=url, user=user), 'background_color': FEE...
Template tag to render a feedback form.
def gauge(self, slug, current_value): k = self._gauge_key(slug) self.r.sadd(self._gauge_slugs_key, slug) self.r.set(k, current_value)
Set the value for a Gauge. * ``slug`` -- the unique identifier (or key) for the Gauge * ``current_value`` -- the value that the gauge should display
def update(self, observable, handlers): addedreaders, removedreaders = handlers for reader in addedreaders: item = self.Append(str(reader)) self.SetClientData(item, reader) for reader in removedreaders: item = self.FindString(str(reader)) if wx.NOT...
Toolbar ReaderObserver callback that is notified when readers are added or removed.
def failure_line_summary(formatter, failure_line): if failure_line.action == "test_result": action = "test_status" if failure_line.subtest is not None else "test_end" elif failure_line.action == "truncated": return else: action = failure_line.action try: mozlog_func = get...
Create a mozlog formatted error summary string from the given failure_line. Create a string which can be compared to a TextLogError.line string to see if they match.
def header(header_text: str, level: int = 1, expand_full: bool = False): r = _get_report() r.append_body(render.header( header_text, level=level, expand_full=expand_full ))
Adds a text header to the display with the specified level. :param header_text: The text to display in the header. :param level: The level of the header, which corresponds to the html header levels, such as <h1>, <h2>, ... :param expand_full: Whether or not the header will e...
def create(self, key, value): base64_key = _encode(key) base64_value = _encode(value) txn = { 'compare': [{ 'key': base64_key, 'result': 'EQUAL', 'target': 'CREATE', 'create_revision': 0 }], 'succ...
Atomically create the given key only if the key doesn't exist. This verifies that the create_revision of a key equales to 0, then creates the key with the value. This operation takes place in a transaction. :param key: key in etcd to create :param value: value of the key ...
def filepath(self, filename): return os.path.join(self.node.full_path, filename)
The full path to a file
def _get_representative_batch(merged): out = {} for mgroup in merged: mgroup = sorted(list(mgroup)) for x in mgroup: out[x] = mgroup[0] return out
Prepare dictionary matching batch items to a representative within a group.
def set_s3_prefix(self, region, name): ct = self.session.client('cloudtrail', region_name=region) ct.update_trail(Name=name, S3KeyPrefix=self.account.account_name) auditlog( event='cloudtrail.set_s3_prefix', actor=self.ns, data={ 'account': sel...
Sets the S3 prefix for a CloudTrail Trail Args: region (`str`): Name of the AWS region name (`str`): Name of the CloudTrail Trail Returns: `None`
def to_text(self): if self.text is None: return level = '*' * self.level return '%s%s\n' % (level, self.text)
Render a Heading MessageElement as plain text :returns: The plain text representation of the Heading MessageElement.
def _process(self, name): if self.token.nature == name: self.token = self.lexer.next_token() else: self._error()
Process the current token.
def _parse_filter_string(filter_string): assert "=" in filter_string, "filter string requires an '=', got {0}".format(filter_string) split_values = filter_string.split('=') assert len(split_values) == 2, "more than one equals found in filter string {0}!".format(filter_string) return split_values
parse a filter string into a key-value pair
def get_range_info(array, component): r = array.GetRange(component) comp_range = {} comp_range['min'] = r[0] comp_range['max'] = r[1] comp_range['component'] = array.GetComponentName(component) return comp_range
Get the data range of the array's component
def jarsign(storepass, keypass, keystore, source, alias, path=None): cmd = [ 'jarsigner', '-verbose', '-storepass', storepass, '-keypass', keypass, '-keystore', keystore, source, alias ] common.run_cmd(cmd, log='jarsign.log', cwd=path)
Uses Jarsign to sign an apk target file using the provided keystore information. :param storepass(str) - keystore storepass :param keypass(str) - keystore keypass :param keystore(str) - keystore file path :param source(str) - apk path :param alias(str) - keystore alias :param path(str) - basedir to run the...
def labels_to_indices(self, labels: Sequence[str]) -> List[int]: return [self.LABEL_TO_INDEX[label] for label in labels]
Converts a sequence of labels into their corresponding indices.
def find_ca_bundle(): extant_cert_paths = filter(os.path.isfile, cert_paths) return ( get_win_certfile() or next(extant_cert_paths, None) or _certifi_where() )
Return an existing CA bundle path, or None
def _handle_template(self, token): params = [] default = 1 self._push() while self._tokens: token = self._tokens.pop() if isinstance(token, tokens.TemplateParamSeparator): if not params: name = self._pop() param ...
Handle a case where a template is at the head of the tokens.
def write(self, b): self.__buffer += bytes(b) bytes_written = 0 while len(self.__buffer) >= self.__cipher_block_size: io.BufferedWriter.write(self, self.__cipher.encrypt_block(self.__buffer[:self.__cipher_block_size])) self.__buffer = self.__buffer[self.__cipher_block_size:] bytes_written += self.__ciphe...
Encrypt and write data :param b: data to encrypt and write :return: None
def _method_url(self, method_name): return "{base_url}/api/{api}/{method}".format( base_url=self._base_url(), api=self.api_version, method=method_name )
Generate the URL for the requested method Args: method_name (str): Name of the method Returns: A string containing the URL of the method
def get_sv_chroms(items, exclude_file): exclude_regions = {} for region in pybedtools.BedTool(exclude_file): if int(region.start) == 0: exclude_regions[region.chrom] = int(region.end) out = [] with pysam.Samfile(dd.get_align_bam(items[0]) or dd.get_work_bam(items[0]))as pysam_work_ba...
Retrieve chromosomes to process on, avoiding extra skipped chromosomes.
def transpose(self): java_transposed_matrix = self._java_matrix_wrapper.call("transpose") return BlockMatrix(java_transposed_matrix, self.colsPerBlock, self.rowsPerBlock)
Transpose this BlockMatrix. Returns a new BlockMatrix instance sharing the same underlying data. Is a lazy operation. >>> blocks = sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11, 12]))]) >>>...
def mv_files(src, dst): files = os.listdir(src) for file in files: shutil.move(os.path.join(src, file), os.path.join(dst, file)) return
Move all files from one directory to another :param str src: Source directory :param str dst: Destination directory :return none:
def add_number_widget(self, ref, x=1, value=1): if ref not in self.widgets: widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value) self.widgets[ref] = widget return self.widgets[ref]
Add Number Widget
def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M', '%I.%M'], show_example=False, rofi_args=None, **kwargs): def time_validator(text): for format in formats: try: dt = datetime.strptime(text, format) except ...
Prompt the user to enter a time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter time...
def flush(self): self._check_open_file() if self.allow_update and not self.is_stream: contents = self._io.getvalue() if self._append: self._sync_io() old_contents = (self.file_object.byte_contents if is_byte_string(c...
Flush file contents to 'disk'.
def generate_random_schema(valid): schema_type = choice(['literal', 'type']) if schema_type == 'literal': type, gen = generate_random_type(valid) value = next(gen) return value, (value if valid else None for i in itertools.count()) elif schema_type == 'type': return generate_...
Generate a random plain schema, and a sample generation function. :param valid: Generate valid samples? :type valid: bool :returns: schema, sample-generator :rtype: *, generator
def as_unit(self, unit, location='suffix', *args, **kwargs): f = Formatter( as_unit(unit, location=location), args, kwargs ) return self._add_formatter(f)
Format subset as with units :param unit: string to use as unit :param location: prefix or suffix :param subset: Pandas subset
def resolve_relative_rst_links(text: str, base_link: str): document = parse_rst(text) visitor = SimpleRefCounter(document) document.walk(visitor) for target in visitor.references: name = target.attributes['name'] uri = target.attributes['refuri'] new_link = '`{} <{}{}>`_'.format(...
Resolve all relative links in a given RST document. All links of form `link`_ become `link <base_link/link>`_.
def address_reencode(address, blockchain='bitcoin', **blockchain_opts): if blockchain == 'bitcoin': return btc_address_reencode(address, **blockchain_opts) else: raise ValueError("Unknown blockchain '{}'".format(blockchain))
Reencode an address
def convert(isbn, code='978'): isbn = _isbn_cleanse(isbn) if len(isbn) == 10: isbn = code + isbn[:-1] return isbn + calculate_checksum(isbn) else: if isbn.startswith('978'): return isbn[3:-1] + calculate_checksum(isbn[3:-1]) else: raise IsbnError('Only...
Convert ISBNs between ISBN-10 and ISBN-13. Note: No attempt to hyphenate converted ISBNs is made, because the specification requires that *any* hyphenation must be correct but allows ISBNs without hyphenation. Args: isbn (str): SBN, ISBN-10 or ISBN-13 code (str): EAN Bo...
def load(self, container_name, slot, label=None, share=False): if share: raise NotImplementedError("Sharing not supported") try: name = self.LW_TRANSLATION[container_name] except KeyError: if container_name in self.LW_NO_EQUIVALENT: raise NotIm...
Load a piece of labware by specifying its name and position. This method calls :py:meth:`.ProtocolContext.load_labware_by_name`; see that documentation for more information on arguments and return values. Calls to this function should be replaced with calls to :py:meth:`.Protocolcontext...
def can_proceed(bound_method, check_conditions=True): if not hasattr(bound_method, '_django_fsm'): im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__')) raise TypeError('%s method is not transition' % im_func.__name__) meta = bound_method._django_fsm im_self = getattr...
Returns True if model in state allows to call bound_method Set ``check_conditions`` argument to ``False`` to skip checking conditions.
def check_empty_locations(self, locations=None): if locations is None: locations = self.locations if not locations: err_exit('mkrelease: option -d is required\n%s' % USAGE)
Fail if 'locations' is empty.
def save_model(self, model_filename): line = "save_{}|".format(model_filename) self.vw_process.sendline(line)
Pass a "command example" to the VW subprocess requesting that the current model be serialized to model_filename immediately.
def from_soup_tag(tag): "Returns an instance from a given soup tag." periods = [] notes = [] for elem in tag.findAll(recursive=False): if elem.name not in ('period', 'note'): raise TypeError("Unknown tag found: " + str(elem)) if elem.name == 'note'...
Returns an instance from a given soup tag.
def _get_implicit_requirements( self, fields, requirements ): for name, field in six.iteritems(fields): source = field.source requires = getattr(field, 'requires', None) or [source] for require in requires: if not require: ...
Extract internal prefetch requirements from serializer fields.
def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30): start_time = time.time() while self.current_state != state: self.check_for_errors() if time.time() - start_time > rpc_timeout: raise AMQPConnectionError('Connection timed out') ...
Wait for a Connection state. :param int state: State that we expect :raises AMQPConnectionError: Raises if we are unable to establish a connection to RabbitMQ. :return:
def get_response(self): user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation['state'] = 'normal' self.conversation.insert( tk.END, "Human: " + user_input + "\n" + "ChatBot: " + str(respon...
Get a response from the chatbot and display it.
def HiResHDU(model): cards = model._mission.HDUCards(model.meta, hdu=5) cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVEREST INFO *')) cards.append(('COMMENT', '************************')) cards.append(('MISSION', model.mission, 'Mission name')) cards...
Construct the HDU containing the hi res image of the target.
def scripts(cls, pkg, metadata, paths=[], **kwargs): for path in paths: try: fP = pkg_resources.resource_filename(pkg, path) except ImportError: cls.log.warning( "No package called {}".format(pkg) ) else: ...
This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among scripts against particular criteria. Its use is application specific...
def _on_delete(self, builder): column = self._get_deleted_at_column(builder) return builder.update({column: builder.get_model().fresh_timestamp()})
The delete replacement function. :param builder: The query builder :type builder: orator.orm.builder.Builder
def write_elec_file(filename, mesh): elecs = [] electrodes = np.loadtxt(filename) for i in electrodes: for nr, j in enumerate(mesh['nodes']): if np.isclose(j[1], i[0]) and np.isclose(j[2], i[1]): elecs.append(nr + 1) fid = open('elec.dat', 'w') fid.write('{0}\n'.f...
Read in the electrode positions and return the indices of the electrodes # TODO: Check if you find all electrodes
def load_hooks(): hooks = {} for entrypoint in pkg_resources.iter_entry_points(ENTRYPOINT): name = str(entrypoint).split('=')[0].strip() try: hook = entrypoint.load() except Exception as e: write_message('failed to load entry-point %r (error="%s")' % (name, e), 'y...
Load the exposed hooks. Returns a dict of hooks where the keys are the name of the hook and the values are the actual hook functions.
def translate_filenames(filenames): if is_windows(): return filenames for index, filename in enumerate(filenames): filenames[index] = vboxsf_to_windows(filename)
Convert filenames from Linux to Windows.
def get_timestamp_column(expression, column_name): if expression: return expression elif column_name.lower() != column_name: return f'"{column_name}"' return column_name
Postgres is unable to identify mixed case column names unless they are quoted.
def comment_from_tag(tag): if not tag: return None comment = Comment(name=tag.name, meta={'description': tag.description}, annotations=tag.annotations) return comment
Convenience function to create a full-fledged comment for a given tag, for example it is convenient to assign a Comment to a ReturnValueSymbol.
def fit(self, X, y=None): ttype = type_of_target(y) if ttype.startswith(MULTICLASS): self.target_type_ = MULTICLASS self.estimator = OneVsRestClassifier(self.estimator) self._target_labels = np.unique(y) Y = label_binarize(y, classes=self._target_labels) ...
Fit the classification model; if y is multi-class, then the estimator is adapted with a OneVsRestClassifier strategy, otherwise the estimator is fit directly.
def check_installation(cur_file): cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least two versions of " "cleverhans installed, one at %s and one at" ...
Warn user if running cleverhans from a different directory than tutorial.
def estimate_gaussian(X): mean = np.mean(X,0) variance = np.var(X,0) return Gaussian(mean,variance)
Returns the mean and the variance of a data set of X points assuming that the points come from a gaussian distribution X.
def sound_mode(self): sound_mode_matched = self._parent_avr.match_sound_mode( self._parent_avr.sound_mode_raw) return sound_mode_matched
Return the matched current sound mode as a string.