code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def read_rels(archive): xml_source = archive.read(ARC_WORKBOOK_RELS) tree = fromstring(xml_source) for element in safe_iterator(tree, '{%s}Relationship' % PKG_REL_NS): rId = element.get('Id') pth = element.get("Target") typ = element.get('Type') if pth.startswith("/xl"): ...
Read relationships for a workbook
def _read_services(self, services): for service in services: parser = FritzSCDPParser(self.address, self.port, service) actions = parser.get_actions() service.actions = {action.name: action for action in actions} self.services[service.name] = service
Get actions from services.
def stmt_lambdef_handle(self, original, loc, tokens): if len(tokens) == 2: params, stmts = tokens elif len(tokens) == 3: params, stmts, last = tokens if "tests" in tokens: stmts = stmts.asList() + ["return " + last] else: st...
Process multi-line lambdef statements.
def X(self, value): if isinstance(value, (int, float, long, types.NoneType)): self._x = value
sets the X coordinate
def before(self): user = self.request.user() if user and user.verified_at is None: self.request.redirect('/email/verify')
Run This Middleware Before The Route Executes.
def validate(self, _portfolio, _account, _algo_datetime, _algo_current_data): if _account.leverage > self.max_leverage: self.fail()
Fail if the leverage is greater than the allowed leverage.
async def load_saved_device_info(self): _LOGGER.debug("Loading saved device info.") deviceinfo = [] if self._workdir: _LOGGER.debug("Really Loading saved device info.") try: device_file = '{}/{}'.format(self._workdir, DEVICE_INFO_FILE) with...
Load device information from the device info file.
def _get_hosts_from_ports(self, ports): hosts = map(lambda x: 'localhost:%d' % int(x.strip()), ports.split(',')) return list(set(hosts))
validate hostnames from a list of ports
def _linear_constraints(self, om): A, l, u = om.linear_constraints() return A, l, u
Returns the linear problem constraints.
def clean_requires_python(candidates): all_candidates = [] sys_version = ".".join(map(str, sys.version_info[:3])) from packaging.version import parse as parse_version py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version)) for c in candidates: from_location = attrgetter...
Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes.
def pymatgen_mol(self): sp = [] coords = [] for atom in ob.OBMolAtomIter(self._obmol): sp.append(atom.GetAtomicNum()) coords.append([atom.GetX(), atom.GetY(), atom.GetZ()]) return Molecule(sp, coords)
Returns pymatgen Molecule object.
def show_image(kwargs, call=None): if call != 'function': raise SaltCloudSystemExit( 'The show_image action must be called with -f or --function.' ) params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'} result = aws.query(params, ...
Show the details from EC2 concerning an AMI
def page_title(self, title): if world.browser.title != title: raise AssertionError( "Page title expected to be {!r}, got {!r}.".format( title, world.browser.title))
Assert the page title matches the given text.
def __open(self, url, headers=None, data=None, baseurl=""): headers = headers or {} if not baseurl: baseurl = self.baseurl req = Request("%s%s" % (baseurl, url), headers=headers) _LOGGER.debug(url) try: req.data = urlencode(data).encode('utf-8') ex...
Use raw urlopen command.
def stop(self): if self.original_handler is not None: signal.signal(signal.SIGWINCH, self.original_handler)
Stop trapping WINCH signals and restore the previous WINCH handler.
def save(self, t, base=0, heap=False): c, k = _keytuple(t) if k and k not in _typedefs: _typedefs[k] = self if c and c not in _typedefs: if t.__module__ in _builtin_modules: k = _kind_ignored else: k = self.k...
Save this typedef plus its class typedef.
def __get_host(node, vm_): if __get_ssh_interface(vm_) == 'private_ips' or vm_['external_ip'] is None: ip_address = node.private_ips[0] log.info('Salt node data. Private_ip: %s', ip_address) else: ip_address = node.public_ips[0] log.info('Salt node data. Public_ip: %s', ip_addres...
Return public IP, private IP, or hostname for the libcloud 'node' object
def update_devices(self, devices): for qspacket in devices: try: qsid = qspacket[QS_ID] except KeyError: _LOGGER.debug("Device without ID: %s", qspacket) continue if qsid not in self: self[qsid] = QSDev(data=qspa...
Update values from response of URL_DEVICES, callback if changed.
def check_initialized(method): def _decorator(self, *args, **kwargs): if self._arguments is None or self._options is None: raise RuntimeError('using an uninitialized configuration') return method(self, *args, **kwargs) return _decorator
Check that the configuration object was initialized.
def __add_import(self, original_token): sid = self.__new_sid() token = SymbolToken(original_token.text, sid, original_token.location) self.__add(token) return token
Adds a token, normalizing only the SID
def create_ca_bundle_for_names(self, bundle_name, names): records = [rec for name, rec in self.store.store.items() if name in names] return self.create_bundle( bundle_name, names=[r['parent_ca'] for r in records])
Create a CA bundle to trust only certs defined in names
def output_service(gandi, service, status, justify=10): output_line(gandi, service, status, justify)
Helper to output a status service information.
def parse(self, buf): self._tokenizer = tokenize_asdl(buf) self._advance() return self._parse_module()
Parse the ASDL in the buffer and return an AST with a Module root.
def parse_line(self, text, fh=None): match = self.ok.match(text) if match: return self._parse_result(True, match, fh) match = self.not_ok.match(text) if match: return self._parse_result(False, match, fh) if self.diagnostic.match(text): return D...
Parse a line into whatever TAP category it belongs.
def send_msg_to_clients(client_ids, msg, error=False): if error: stream = "stderr" else: stream = "stdout" response = [{"message": None, "type": "console", "payload": msg, "stream": stream}] for client_id in client_ids: logger.info("emiting message to websocket client id " + clie...
Send message to all clients
def array_sha256(a): dtype = str(a.dtype).encode() shape = numpy.array(a.shape) sha = hashlib.sha256() sha.update(dtype) sha.update(shape) sha.update(a.tobytes()) return sha.hexdigest()
Create a SHA256 hash from a Numpy array.
def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer, indices: List[int]) -> None: probs, unitaries = zip(*protocols.mixture(op)) index = np.random.choice(range(len(unitaries)), p=probs) shape = (2,) * (2 * len(indices)) unitary = unitaries[index].astype(self....
Simulate an op that is a mixtures of unitaries.
def _call_pip(self, name=None, prefix=None, extra_args=None, callback=None): cmd_list = self._pip_cmd(name=name, prefix=prefix) cmd_list.extend(extra_args) process_worker = ProcessWorker(cmd_list, pip=True, callback=callback) process_worker.sig_finished.connect(self._st...
Call pip in QProcess worker.
def cli(obj): for k, v in obj.items(): if isinstance(v, list): v = ', '.join(v) click.echo('{:20}: {}'.format(k, v))
Display client config downloaded from API server.
def _bowtie_args_from_config(data): config = data['config'] qual_format = config["algorithm"].get("quality_format", "") if qual_format.lower() == "illumina": qual_flags = ["--phred64-quals"] else: qual_flags = [] multi_mappers = config["algorithm"].get("multiple_mappers", True) m...
Configurable high level options for bowtie.
def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False): "Start to send response" if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.status = status self.disabledeflate = di...
Start to send response
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""): tweets = tweet_list_builder(request.access_token()) print (len(tweets), 'tweets found') if tweets: twitter_cache.initialize_user_queue(user_id=request.access_token(), queue=tweets) ...
This is a generic function to handle any intent that reads out a list of tweets
def map_azure_exceptions(key=None, exc_pass=()): from azure.common import AzureMissingResourceHttpError, AzureHttpError,\ AzureException try: yield except AzureMissingResourceHttpError as ex: if ex.__class__.__name__ not in exc_pass: s = str(ex) if s.startswit...
Map Azure-specific exceptions to the simplekv-API.
def clone(self, repo, ref, deps=()): if os.path.isdir(repo): repo = os.path.abspath(repo) def clone_strategy(directory): env = git.no_git_env() def _git_cmd(*args): cmd_output('git', *args, cwd=directory, env=env) _git_cmd('init', '.') ...
Clone the given url and checkout the specific ref.
def highlightBlock(self, text): if self._allow_highlight: start = self.previousBlockState() + 1 end = start + len(text) for i, (fmt, letter) in enumerate(self._charlist[start:end]): self.setFormat(i, 1, fmt) self.setCurrentBlockState(end) ...
Actually highlight the block
def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0): return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
Compute the time-derivative of a Lorentz system.
def reloc_var(var_name, reloc_delta, pointer, var_type): template = '{0} {3}{1} = RELOC_VAR(_{1}, {2}, {0});\n' return template.format( var_type, var_name, reloc_delta, '*' if pointer else '' )
Build C source code to relocate a variable.
def interface_by_name(self, name): if name in self._devinfo: return self._devinfo[name] raise KeyError("No device named {}".format(name))
Given a device name, return the corresponding interface object
def update(context, resource, **kwargs): etag = kwargs.pop('etag') id = kwargs.pop('id') data = utils.sanitize_kwargs(**kwargs) uri = '%s/%s/%s' % (context.dci_cs_api, resource, id) r = context.session.put(uri, timeout=HTTP_TIMEOUT, headers={'If-match': etag}, ...
Update a specific resource
def _translate_struct(inner_dict): try: optional = inner_dict['optional'].items() required = inner_dict['required'].items() except KeyError as ex: raise DeserializationError("Missing key: {}".format(ex)) except AttributeError as ex: raise DeserializationError( "In...
Translate a teleport Struct into a val subschema.
def stop_recording(self): if not self._recording: raise Exception("Cannot stop a video recording when it's not recording!") self._cmd_q.put(('stop',)) self._recording = False
Stops writing video to file.
def _add_modifiers(self, sql, blueprint, column): for modifier in self._modifiers: method = '_modify_%s' % modifier if hasattr(self, method): sql += getattr(self, method)(blueprint, column) return sql
Add the column modifiers to the deifinition
def max_values(args): return Interval(max(x.low for x in args), max(x.high for x in args))
Return possible range for max function.
def load_adjustment_values(self, c): for mast in self: c.execute( ' SELECT name, val\n' ' FROM adjustment_values\n' ' WHERE prst = ?\n' 'ORDER BY seq_nmbr', (mast.prst,) ) for name, val in c: ...
load adjustment values for auto shape types in self
def mmap_key(metric_name, name, labelnames, labelvalues): labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
Format a key for use in the mmap file.
def broadcast(self): log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port) request = '\r\n'.join(("M-SEARCH * HTTP/1.1", "HOST:{mcast_ip}:{mcast_port}", "ST:upnp:rootdevice", "MX:2", ...
Send a multicast M-SEARCH request asking for devices to report in.
def app_to_object(self): if self.tagClass != Tag.applicationTagClass: raise ValueError("application tag required") klass = self._app_tag_class[self.tagNumber] if not klass: return None return klass(self)
Return the application object encoded by the tag.
def to_eng(num_in): x = decimal.Decimal(str(num_in)) eng_not = x.normalize().to_eng_string() return(eng_not)
Return number in engineering notation.
def create(prefix, params, hint): current = getattr(_BlockScope._current, "value", None) if current is None: if prefix is None: if not hasattr(_name.NameManager._current, "value"): _name.NameManager._current.value = _name.NameManager() pref...
Creates prefix and params for new `Block`.
def on_mouse_release(self, x: int, y: int, button, mods): if button in [1, 4]: self.example.mouse_release_event( x, self.buffer_height - y, 1 if button == 1 else 2, )
Handle mouse release events and forward to example window
def compute_result_enum(self) -> RobotScanResultEnum: for payload_enum, server_responses in self._payload_responses.items(): if server_responses[0] != server_responses[1]: return RobotScanResultEnum.UNKNOWN_INCONSISTENT_RESULTS if len(set([server_responses[0] for server_respo...
Look at the server's response to each ROBOT payload and return the conclusion of the analysis.
def create_tab(self, location=None): eb = self._get_or_create_editor_buffer(location) self.tab_pages.insert(self.active_tab_index + 1, TabPage(Window(eb))) self.active_tab_index += 1
Create a new tab page.
def pull_parent(collector, image, **kwargs): log.warning("DEPRECATED - use pull_dependencies instead") pull_dependencies(collector, image, **kwargs)
DEPRECATED - use pull_dependencies instead
def execute(self, query): c = self.conn.cursor() result = c.execute(query) for i in result: yield i
Execute a query directly on the database.
def update(self, **kwargs): data = kwargs.get('data') if data is not None: if (util.pd and isinstance(data, util.pd.DataFrame) and list(data.columns) != list(self.data.columns) and self._index): data = data.reset_index() self.verify(data) ...
Overrides update to concatenate streamed data up to defined length.
def load_segment(self, f, is_irom_segment=False): file_offs = f.tell() (offset, size) = struct.unpack('<II', f.read(8)) self.warn_if_unusual_segment(offset, size, is_irom_segment) segment_data = f.read(size) if len(segment_data) < size: raise FatalError('End of file r...
Load the next segment from the image file
def validate(self): if self.validation_state != ValidationState.UNKNOWN: return self.validation_state == ValidationState.VALID if self.validator: try: self.validator.validate(self.document) except ValidationError as e: cursor_position =...
Returns `True` if valid.
def setup_options(opts): if opts.quiet: logger.log.setLevel(logging.WARNING) logger.GLOBAL_LOG_LEVEL = logging.WARNING if opts.verbose: logger.log.setLevel(logging.DEBUG) logger.GLOBAL_LOG_LEVEL = logging.DEBUG
Takes any actions necessary based on command line options
def match_date(self, value, strict=False): value = stringify(value) try: parse(value) except Exception: self.shout('Value %r is not a valid date', strict, value)
if value is a date
def ls(types, as_json): sensors = W1ThermSensor.get_available_sensors(types) if as_json: data = [ {"id": i, "hwid": s.id, "type": s.type_name} for i, s in enumerate(sensors, 1) ] click.echo(json.dumps(data, indent=4, sort_keys=True)) else: click.echo( ...
List all available sensors
def ssh_user(self, cluster='main'): if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) try: return self.config.get(cluster, 'ssh_user') except NoOptionError: re...
Return the ssh user for a cluster or current user if undefined.
def _button_plus_clicked(self, n): self._button_save.setEnabled(True) self.insert_colorpoint(self._colorpoint_list[n][0], self._colorpoint_list[n][1], self._colorpoint_list[n][2]) self._build_gui()
Create a new colorpoint.
def cli(conf): if conf: if not os.path.isfile(conf): raise click.exceptions.BadParameter("{} is not a file".format(conf)) try: config.conf.load_config(config_path=conf) except exceptions.ConfigurationException as e: raise click.exceptions.BadParameter(str(...
The fedora-messaging command line interface.
def do_imports(self): self.do_import('worker_class', Worker) self.do_import('queue_model', self.options.worker_class.queue_model) self.do_import('error_model', self.options.worker_class.error_model) self.do_import('callback', self.options.worker_class.callback)
Import all importable options
def _render_html(self, libraries): title = self.options.get("title", "Keyword Documentation") date = time.strftime("%A %B %d, %I:%M %p") cci_version = cumulusci.__version__ stylesheet_path = os.path.join(os.path.dirname(__file__), "stylesheet.css") with open(stylesheet_path) as f...
Generate the html. `libraries` is a list of LibraryDocumentation objects
def list_features(self): response, status_code = self.__pod__.System.get_v1_admin_system_features_list( sessionToken=self.__session__ ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
list features the pod supports
def people(self): if self.cache['people']: return self.cache['people'] people_xml = self.bc.people_within_project(self.id) for person_node in ET.fromstring(people_xml).findall('person'): p = Person(person_node) self.cache['people'][p.id] = p return self.cache['peo...
Dictionary of people on the project, keyed by id
def upload_prev(ver, doc_root='./'): 'push a copy of older release to appropriate version directory' local_dir = doc_root + 'build/html' remote_dir = '/usr/share/nginx/pandas/pandas-docs/version/%s/' % ver cmd = 'cd %s; rsync -avz . pandas@pandas.pydata.org:%s -essh' cmd = cmd % (local_dir, remote_d...
push a copy of older release to appropriate version directory
def collect(self): for root, dirname, files in walk(self.migration_home): for file_name in file_filter(files, "*.py"): file_name = file_name.replace('.py', '') file = None try: if file_name == '__init__': con...
Walks self.migration_home and load all potential migration modules
def can_subscribe_to_topic(self, topic, user): return ( user.is_authenticated and not topic.has_subscriber(user) and self._perform_basic_permission_check(topic.forum, user, 'can_read_forum') )
Given a topic, checks whether the user can add it to their subscription list.
def config(self, configlet, plane, **attributes): try: config_text = configlet.format(**attributes) except KeyError as exp: raise CommandSyntaxError("Configuration template error: {}".format(str(exp))) return self.driver.config(config_text, plane)
Apply config to the device.
def _stringify_number(v): if isinstance(v, (float, Decimal)): if math.isinf(v) and v > 0: v = 'Infinity' elif math.isinf(v) and v < 0: v = '-Infinity' else: v = '{:f}'.format(v) elif isinstance(v, BinarySize): v = '{:d}'.format(int(v)) elif...
Stringify a number, preventing unwanted scientific notations.
def check_options(options, parser): if not options.get('release_environment', None): print("release environment is required") parser.print_help() return os.EX_USAGE return 0
check options requirements, print and return exit value
def _list2array(lst): if lst and isinstance(lst[0], cp.ndarray): return cp.hstack(lst) else: return cp.asarray(lst)
Convert a list to a numpy array.
def open(self, path, mode='r', *args, **kwargs): return open(os.path.join(os.path.dirname(self.path), path), mode=mode, *args, **kwargs)
Proxy to function `open` with path to the current file.
def to_pickle(self, filename): with open(filename, 'wb') as f: pickle.dump(self, f)
Save Camera to a pickle file, given a filename.
def printParams(paramDictionary, all=False, log=None): if log is not None: def output(msg): log.info(msg) else: def output(msg): print(msg) if not paramDictionary: output('No parameters were supplied') else: for key in sorted(paramDictionary): ...
Print nicely the parameters from the dictionary.
def set(*args, **kw): if len(args) == 0: if len(kw) != 0: for keyword, value in kw.items(): keyword = untranslateName(keyword) svalue = str(value) _varDict[keyword] = svalue else: listVars(prefix=" ", equals="=") else: ...
Set IRAF environment variables.
def update_line(self, trace, xdata, ydata, side='left', draw=False, update_limits=True): x = self.conf.get_mpl_line(trace) x.set_data(xdata, ydata) datarange = [xdata.min(), xdata.max(), ydata.min(), ydata.max()] self.conf.set_trace_datarange(datarange, trace=trace) ...
update a single trace, for faster redraw
def devectorize_utterance(self, utterance): utterance = self.swap_pad_and_zero(utterance) return self.ie.inverse_transform(utterance).tolist()
Take in a sequence of indices and transform it back into a tokenized utterance
def fourier(x, N): term = 0. for n in range(1, N, 2): term += (1. / n) * math.sin(n * math.pi * x / L) return (4. / (math.pi)) * term
Fourier approximation with N terms
def ask_for_input_with_prompt(cls, ui, prompt='', **options): return cls.get_appropriate_helper(ui).ask_for_input_with_prompt(prompt=prompt, **options)
Ask user for written input with prompt
def all_matches(grammar, text): for tokens, start, stop in grammar.parseWithTabs().scanString(text): yield unpack(tokens), start, stop
Find all matches for grammar in text.
def GetPattern(self): stoptimes = self.GetStopTimes() return tuple(st.stop for st in stoptimes)
Return a tuple of Stop objects, in the order visited
def _validate_cmdfinalization_callable(cls, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: cls._validate_callable_param_count(func, 1) signature = inspect.signature(func) _, param = list(si...
Check parameter and return types for command finalization hooks.
def decorator(target): def decorate(fn): spec = inspect.getargspec(fn) names = tuple(spec[0]) + spec[1:3] + (fn.__name__,) targ_name, fn_name = unique_symbols(names, 'target', 'fn') metadata = dict(target=targ_name, fn=fn_name) metadata.update(format_argspec_plus(spec, groupe...
A signature-matching decorator factory.
def at_line(self, line: FileLine) -> Iterator[Statement]: num = line.num for stmt in self.in_file(line.filename): if stmt.location.start.line == num: yield stmt
Returns an iterator over all of the statements located at a given line.
def _get_baremetal_switch_info(self, link_info): try: switch_info = link_info['switch_info'] if not isinstance(switch_info, dict): switch_info = jsonutils.loads(switch_info) except Exception as e: LOG.error("switch_info can't be decoded: %(exp)s", ...
Get switch_info dictionary from context.
def namespace_inclusion_builder(namespace: Strings) -> NodePredicate: if isinstance(namespace, str): def namespace_filter(_: BELGraph, node: BaseEntity) -> bool: return NAMESPACE in node and node[NAMESPACE] == namespace elif isinstance(namespace, Iterable): namespaces = set(namespace...
Build a predicate for namespace inclusion.
def randomString(length, chrs=None): if chrs is None: return getBytes(length) else: n = len(chrs) return ''.join([chrs[randrange(n)] for _ in xrange(length)])
Produce a string of length random bytes, chosen from chrs.
def _check_app_is_valid(client): try: if 'refresh_token' in client.creds: client.exchange_refresh_token() else: existing.get_token_info() return True except TokenEndpointError as e: return False
Check to see if the app has valid creds.
def _translate_src_register_oprnd(self, operand): reg_info = self._arch_alias_mapper.get(operand.name, None) if reg_info: var_base_name, offset = reg_info var_size = self._arch_regs_size[var_base_name] else: var_base_name = operand.name var_size = ...
Translate source register operand to SMT expr.
def objects_to_record(self): o = self.get_object() o.about = self._bundle.metadata.about o.identity = self._dataset.identity.ident_dict o.names = self._dataset.identity.names_dict o.contacts = self._bundle.metadata.contacts self.set_object(o)
Write from object metadata to the record. Note that we don't write everything
def add(self, labels, value): if type(value) not in (float, int): raise TypeError("Summary only works with digits (int, float)") with mutex: try: e = self.get_value(labels) except KeyError: e = quantile.Estimator(*self.__class__.DEFAULT...
Add adds a single observation to the summary.
def _get_post_data_to_create_dns_entry(self, rtype, name, content, identifier=None): is_update = identifier is not None if is_update: records = self._list_records_internal(identifier=identifier) assert len(records) == 1, 'ID is not unique or does not exist' record = r...
Build and return the post date that is needed to create a DNS entry.
def descape(self, string, defs=None): if defs is None: defs = html_entities.entitydefs f = lambda m: defs[m.group(1)] if len(m.groups()) > 0 else m.group(0) return self.html_entity_re.sub(f, string)
Decodes html entities from a given string
def from_url(cls, url, **kwargs): url = urllib3.util.parse_url(url) if url.host: kwargs.setdefault('host', url.host) if url.port: kwargs.setdefault('port', url.port) if url.scheme == 'https': kwargs.setdefault('connection_class', urllib3.HTTPSConnectio...
Create a client from a url.
def _backward_delete_char(text, pos): if pos == 0: return text, pos return text[:pos - 1] + text[pos:], pos - 1
Delete the character behind pos.
def inject_context(self): navbar = filter(lambda entry: entry.visible, self.navbar_entries) return {'navbar': navbar}
Return a dict used for a template context.
def user_agent(self): components = ["/".join(x) for x in self.user_agent_components.items()] return " ".join(components)
Return the formatted user agent string.