Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
4,000
def as_string(self, chars, current_linkable=False, class_current="active_link"): return self.__do_menu("as_string", current_linkable, class_current, chars)
It returns menu as string
4,001
def full_name(self): if self.requested_version is not None: return % (self.name, self.requested_version) return self.name
Return full package/distribution name, w/version
4,002
def get_dash(self): dashes = ffi.new(, cairo.cairo_get_dash_count(self._pointer)) offset = ffi.new() cairo.cairo_get_dash(self._pointer, dashes, offset) self._check_status() return list(dashes), offset[0]
Return the current dash pattern. :returns: A ``(dashes, offset)`` tuple of a list and a float. :obj:`dashes` is a list of floats, empty if no dashing is in effect.
4,003
def get_available_references(self, datas): names = [] for k, v in datas.items(): if k.startswith(RULE_REFERENCE): names.append(k[len(RULE_REFERENCE)+1:]) return names
Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (dict): Data where to search for reference declarations. ...
4,004
def hkdf(self, chaining_key, input_key_material, dhlen=64): if len(chaining_key) != self.HASHLEN: raise HashError("Incorrect chaining key length") if len(input_key_material) not in (0, 32, dhlen): raise HashError("Incorrect input key material length") temp_key =...
Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an ``input_key_material'' byte sequence with length either zero bytes, 32 bytes or dhlen bytes. Returns two byte sequences of length HASHLEN
4,005
def _read_hdf_columns(path_or_buf, columns, num_splits, kwargs): df = pandas.read_hdf(path_or_buf, columns=columns, **kwargs) return _split_result_for_readers(0, num_splits, df) + [len(df.index)]
Use a Ray task to read columns from HDF5 into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path_or_buf: The path of the HDF5 file. columns: The list of column names to read. num_splits: The number of partitions to split the column in...
4,006
def create_weekmatrices(user, split_interval=60): if not float(24 * 60 / split_interval).is_integer(): raise ValueError( "The minute interval set for the week-matrix structure does not evenly divide the day!") contacts_in = partial(bc.individual.number_of_contacts, ...
Computes raw indicators (e.g. number of outgoing calls) for intervals of ~1 hour across each week of user data. These "week-matrices" are returned in a nested list with each sublist containing [user.name, channel, weekday, section, value]. Parameters ---------- user : object The user to...
4,007
def check_install(): if platform.system() == and sys.executable != : print("*" * 79) print(textwrap.fill( "WARNING: You are not using the version of Python included with " "macOS. If you intend to use Voltron with the LLDB included " "with Xcode, or GDB inst...
Try to detect the two most common installation errors: 1. Installing on macOS using a Homebrew version of Python 2. Installing on Linux using Python 2 when GDB is linked with Python 3
4,008
def mv(source, target): if os.path.isfile(target) and len(source) == 1: if click.confirm("Are you sure you want to overwrite %s?" % target): err_msg = cli_syncthing_adapter.mv_edge_case(source, target) if err_msg: click.echo(err_msg) return if len(source) > 1 and not os....
Move synchronized directory.
4,009
def waitForCreation(self, timeout=10, notification=): callback = AXCallbacks.returnElemCallback retelem = None args = (retelem,) return self.waitFor(timeout, notification, callback=callback, args=args)
Convenience method to wait for creation of some UI element. Returns: The element created
4,010
def properties(self): if self._property_manager is None: self._property_manager = PropertyManager(session=self._session) return self._property_manager
Property for accessing :class:`PropertyManager` instance, which is used to manage properties of the jobs. :rtype: yagocd.resources.property.PropertyManager
4,011
def _make_jsmin(python_only=False): if not python_only: try: import _rjsmin except ImportError: pass else: return _rjsmin.jsmin try: xrange except NameError: xrange = range space_chars = r line_comment = r ...
Generate JS minifier based on `jsmin.c by Douglas Crockford`_ .. _jsmin.c by Douglas Crockford: http://www.crockford.com/javascript/jsmin.c :Parameters: `python_only` : ``bool`` Use only the python variant. If true, the c extension is not even tried to be loaded. :Return: Min...
4,012
def print_progress_bar(iteration, total, prefix=, suffix=, decimals=1, length=100, fill=): percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) print(percent) if iteration == total: print()
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
4,013
def QWidget_factory(ui_file=None, *args, **kwargs): file = ui_file or DEFAULT_UI_FILE if not foundations.common.path_exists(file): raise foundations.exceptions.FileExistsError("{0} | ui file doesn{0}(){1}{1}' attribute is not deletable!".format( self.__class__.__name__, "ui_file")...
Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes using given ui file. :param ui_file: Ui file. :type ui_file: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: QWidget class...
4,014
def remove(self, fieldspec): pattern = r match = re.match(pattern, fieldspec) if not match: return None grp = match.groupdict() for field in self.get_fields(grp[]): if grp[]: updated = [] for code, value in pairwi...
Removes fields or subfields according to `fieldspec`. If a non-control field subfield removal leaves no other subfields, delete the field entirely.
4,015
def lockToColumn(self, index): self._lockColumn = index if index is None: self.__destroyLockedView() return else: if not self._lockedView: view = QtGui.QTreeView(self.parent()) view.setModel(self.mode...
Sets the column that the tree view will lock to. If None is supplied, then locking will be removed. :param index | <int> || None
4,016
def server(request): return direct_to_template( request, , {: getViewURL(request, idPage), : getViewURL(request, idpXrds), })
Respond to requests for the server's primary web page.
4,017
def discover(language): debug(%s\ % (language,)) global scrapers, discovered for language in scrapers.iterkeys(): discovered[language] = {} for scraper in scrapers[language]: blacklist = [, , ] methods = [method for method in dir(scraper) if method not in blacklist and not method.startswith() and callab...
Discovers all registered scrapers to be used for the generic scraping interface.
4,018
def check_bidi(data): has_l = False has_ral = False for char in data: if stringprep.in_table_d1(char): has_ral = True elif stringprep.in_table_d2(char): has_l = True if has_l and has_ral: raise StringprepError("...
Checks if sting is valid for bidirectional printing.
4,019
def handle_battery_level(msg): if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].battery_level = msg.payload msg.gateway.alert(msg) return None
Process an internal battery level message.
4,020
def getScans(self, modifications=True, fdr=True): if not self.scans: for i in self: yield i else: for i in self.scans.values(): yield i yield None
get a random scan
4,021
def _vote_disagreement(self, votes): ret = [] for candidate in votes: ret.append(0.0) lab_count = {} for lab in candidate: lab_count[lab] = lab_count.setdefault(lab, 0) + 1 for lab in lab_count.keys(): ...
Return the disagreement measurement of the given number of votes. It uses the vote vote to measure the disagreement. Parameters ---------- votes : list of int, shape==(n_samples, n_students) The predictions that each student gives to each sample. Returns ---...
4,022
def describe(self, **kwargs): api_method = dxpy.api.container_describe if isinstance(self, DXProject): api_method = dxpy.api.project_describe self._desc = api_method(self._dxid, **kwargs) return self._desc
:returns: A hash containing attributes of the project or container. :rtype: dict Returns a hash with key-value pairs as specified by the API specification for the `/project-xxxx/describe <https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fdescrib...
4,023
async def stop(self): for task in self.__tracks.values(): if task is not None: task.cancel() self.__tracks = {}
Stop discarding media.
4,024
def ko_model(model, field_names=None, data=None): try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ if field_names: fields = field_names else: fields = get_fields(model) if hasa...
Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data.
4,025
def _get_cpu_info_from_registry(): try: if not DataSource.is_windows: return {} processor_brand = DataSource.winreg_processor_brand().strip() vendor_id = DataSource.winreg_vendor_id_raw() arch_string_raw = DataSource.winreg_arch_string_raw() arch, bits = _parse_arch(arch_string_raw) ...
FIXME: Is missing many of the newer CPU flags like sse3 Returns the CPU info gathered from the Windows Registry. Returns {} if not on Windows.
4,026
def index(): if current_app.config[] is not None: override = current_app.config[] results = (models.TaskResult.query .join(models.Task) .filter(models.Task.playbook_id.in_(override))) else: results = models.TaskResult.query.all() return ren...
This is not served anywhere in the web application. It is used explicitly in the context of generating static files since flask-frozen requires url_for's to crawl content. url_for's are not used with result.show_result directly and are instead dynamically generated through javascript for performance pur...
4,027
def list_resource_commands(self): resource_path = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir, )) answer = set([]) for _, name, _ in pkgutil.iter_modules([resource_path]): res = tower_cli.get_resource(name) ...
Returns a list of multi-commands for each resource type.
4,028
def patch_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs): kwargs[] = True if kwargs.get(): return self.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, **kwargs) else: (data) = self.patch_...
partially update status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) ...
4,029
def command_max_delay(self, event=None): try: max_delay = self.max_delay_var.get() except ValueError: max_delay = self.runtime_cfg.max_delay if max_delay < 0: max_delay = self.runtime_cfg.max_delay if max_delay > 0.1: max_delay =...
CPU burst max running time - self.runtime_cfg.max_delay
4,030
def _read_to_buffer(self) -> Optional[int]: try: while True: try: if self._user_read_buffer: buf = memoryview(self._read_buffer)[ self._read_buffer_size : ] ...
Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception.
4,031
def upload(ctx, product, git_ref, dirname, aws_id, aws_secret, ci_env, on_travis_push, on_travis_pr, on_travis_api, on_travis_cron, skip_upload): logger = logging.getLogger(__name__) if skip_upload: click.echo() sys.exit(0) logger.debug(, ci_env) logger.debug...
Upload a new site build to LSST the Docs.
4,032
def serial_ports(): if sys.platform.startswith(): ports = [ % (i + 1) for i in range(256)] elif sys.platform.startswith() or sys.platform.startswith(): ports = glob.glob() elif sys.platform.startswith(): ports = glob.glob() else: raise EnvironmentError() ...
Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-ports-with-python )
4,033
def build_asset_array(assets_by_site, tagnames=(), time_event=None): for assets in assets_by_site: if len(assets): first_asset = assets[0] break else: raise ValueError() loss_types = [] occupancy_periods = [] for name in sorted(first_asset.values): ...
:param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol`
4,034
def is_successful(self, retry=False): if not self.is_terminated(retry=retry): return False retry_num = options.retry_times while retry_num > 0: try: statuses = self.get_task_statuses() return all(task.status == Instance.Task.TaskS...
If the instance runs successfully. :return: True if successful else False :rtype: bool
4,035
def add_report(self, specification_name, report): self._reports[specification_name] = report self._total = self._total + report.testsRun self._failures = self._failures + len(report.failures) self._errors = self._errors + len(report.errors) self._success = self._total -...
Adds a given report with the given specification_name as key to the reports list and computes the number of success, failures and errors Args: specification_name: string representing the specification (with ".spec") report: The
4,036
def parse(self): parser = self.subparser.add_parser( "show", help="Show workspace details", description="Show workspace details.") group = parser.add_mutually_exclusive_group(required=True) group.add_argument(, action=, help="All workspaces") ...
Parse show subcommand.
4,037
def squeeze(attrs, inputs, proto_obj): new_attrs = translation_utils._fix_attribute_names(attrs, { : }) return , new_attrs, inputs
Remove single-dimensional entries from the shape of a tensor.
4,038
def get_chart(self, id, **kwargs): resp = self._get_object_by_name(self._CHART_ENDPOINT_SUFFIX, id, **kwargs) return resp
Retrieve a (v2) chart by id.
4,039
def p_multiplicative_expr(self, p): if len(p) == 2: p[0] = p[1] else: p[0] = ast.BinOp(op=p[2], left=p[1], right=p[3])
multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr
4,040
def get_text(self): return u.join(u.format(b) for b in self.text)
Get the text in its current state.
4,041
def just_find_proxy(pacfile, url, host=None): if not os.path.isfile(pacfile): raise IOError(.format(pacfile)) init() parse_pac(pacfile) proxy = find_proxy(url,host) cleanup() return proxy
This function is a wrapper around init, parse_pac, find_proxy and cleanup. This is the function to call if you want to find proxy just for one url.
4,042
def _runcog(options, files, uncog=False): options.order(, , add_rest=True) c = Cog() if uncog: c.options.bNoGenerate = True c.options.bReplace = True c.options.bDeleteCode = options.get("delete_code", False) includedir = options.get(, None) if includedir: include = Inclu...
Common function for the cog and runcog tasks.
4,043
def print_object_results(obj_result): print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_result.errors: print_schema_results(obj_result, 1)
Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance.
4,044
def parse_summary(self, contents): lines = contents.strip().split() data = {} for row in lines[1:]: split = row.strip().split() sample = split[0] data[sample] = { : int(split[1]), : int(split[2]), : ...
Parses summary file into a dictionary of counts.
4,045
def _onError(self, message): self.isOK = False if message.strip() != "": self.errors.append(message)
Memorizies a parser error message
4,046
def _import_lua_dependencies(lua, lua_globals): if sys.platform not in (, ): import ctypes ctypes.CDLL(, mode=ctypes.RTLD_GLOBAL) try: lua_globals.cjson = lua.eval() except RuntimeError: raise RuntimeError("cjson not installed")
Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson lib. Pending: - base lib. - table li...
4,047
def transpose(self, rows): res = OrderedDict() for row, cols in rows.items(): for col, cell in cols.items(): if col not in res: res[col] = OrderedDict() res[col][row] = cell return res
Transposes the grid to allow for cols
4,048
def _example_from_allof(self, prop_spec): example_dict = {} for definition in prop_spec[]: update = self.get_example_from_prop_spec(definition, True) example_dict.update(update) return example_dict
Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict
4,049
def patchURL(self, url, headers, body): return self._load_resource("PATCH", url, headers, body)
Request a URL using the HTTP method PATCH.
4,050
def _get_position(self): portfolio_code = self.account_config["portfolio_code"] portfolio_info = self._get_portfolio_info(portfolio_code) position = portfolio_info["view_rebalancing"] stocks = position["holdings"] return stocks
获取雪球持仓 :return:
4,051
def serialize_filesec(self): if ( self.type.lower() not in ("item", "archival information package") or self.use is None ): return None el = etree.Element(utils.lxmlns("mets") + "file", ID=self.file_id()) if self.group_id(): el.attr...
Return the file Element for this file, appropriate for use in a fileSec. If this is not an Item or has no use, return None. :return: fileSec element for this FSEntry
4,052
def gradient_factory(name): if name == : def gradient(self): return cos(self.domain) elif name == : def gradient(self): return -sin(self.domain) elif name == : def gradient(self): return 1 + square(self....
Create gradient `Functional` for some ufuncs.
4,053
def register_hooks(app): @app.before_request def before_request(): g.user = get_current_user() if g.user and g.user.is_admin: g._before_request_time = time.time() @app.after_request def after_request(response): if hasattr(g, ): delta = time.time() -...
Register hooks.
4,054
def issue_add_comment(self, issue_key, comment, visibility=None): url = .format(issueIdOrKey=issue_key) data = {: comment} if visibility: data[] = visibility return self.post(url, data=data)
Add comment into Jira issue :param issue_key: :param comment: :param visibility: OPTIONAL :return:
4,055
def on_change(self, path, event_type): for result in results: collection_id = result[0] sql = cursor = self._execute(sql, (collection_id,)) self._load_keywords(collection_id, path=path)
Respond to changes in the file system This method will be given the path to a file that has changed on disk. We need to reload the keywords from that file
4,056
def get_full_durable_object(arn, event_time, durable_model): LOG.debug(f) item = list(durable_model.query(arn, durable_model.eventTime == event_time)) if not item: LOG.error(f f) raise DurableItemIsMissingException({"item_arn": arn, "event_time": event_time}) ...
Utility method to fetch items from the Durable table if they are too big for SNS/SQS. :param record: :param durable_model: :return:
4,057
def tz_localize(self, tz, ambiguous=, nonexistent=, errors=None): if errors is not None: warnings.warn("The errors argument is deprecated and will be " "removed in a future release. Use " "nonexistent= or nonexistent= "...
Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index. This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another time zone. Time zone localization helps to switch from time zone awa...
4,058
def to_dict(self): rv = {: self.code} if not self.is_native(): rv[] = self.issuer rv[] = self.type else: rv[] = return rv
Generate a dict for this object's attributes. :return: A dict representing an :class:`Asset`
4,059
def apply_reactions(self, user): if self.global_limit: self._log.info(.format(num=self.global_limit)) self.agentml.set_limit(self, (time() + self.global_limit), self.glimit_blocking) if self.user_limit: self._log.info(.format(num=self.user_limit)) ...
Set active topics and limits after a response has been triggered :param user: The user triggering the response :type user: agentml.User
4,060
def js_extractor(response): matches = rscript.findall(response) for match in matches: match = match[2].replace("JS file', match) bad_scripts.add(match)
Extract js files from the response body
4,061
def unpack_value(format_string, stream): message_bytes = stream.read(struct.calcsize(format_string)) return struct.unpack(format_string, message_bytes)
Helper function to unpack struct data from a stream and update the signature verifier. :param str format_string: Struct format string :param stream: Source data stream :type stream: io.BytesIO :returns: Unpacked values :rtype: tuple
4,062
def prepare_files(self, finder): from pip.index import Link unnamed = list(self.unnamed_requirements) reqs = list(self.requirements.values()) while reqs or unnamed: if unnamed: req_to_install = unnamed.pop(0) else: req_to_...
Prepare process. Create temp directories, download and/or unpack files.
4,063
def make_serializable(data, mutable=True, key_stringifier=lambda x:x, simplify_midnight_datetime=True): r if isinstance(data, (datetime.datetime, datetime.date, datetime.time)): if isinstance(data, datetime.datetime): if not any((data.hour, data.miniute, data.seconds)): ...
r"""Make sure the data structure is json serializable (json.dumps-able), all they way down to scalars in nested structures. If mutable=False then return tuples for all iterables, except basestrings (strs), so that they can be used as keys in a Mapping (dict). >>> from collections import OrderedDict ...
4,064
def build_from_token_counts(self, token_counts, min_count, num_iterations=4): self._init_alphabet_from_tokens(six.iterkeys(token_counts)) self._init_subtokens_from_list(list(self._alphabet)) if min_count < 1: min_count = 1 ...
Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_iterations: an integer; how many iterations of refinement.
4,065
def get(self, buffer_type, offset): if buffer_type == u: chosen_buffer = self.streaming_data else: chosen_buffer = self.storage_data if offset >= len(chosen_buffer): raise StreamEmptyError("Invalid index given in get command", requested=offset, stor...
Get a reading from the buffer at offset. Offset is specified relative to the start of the data buffer. This means that if the buffer rolls over, the offset for a given item will appear to change. Anyone holding an offset outside of this engine object will need to be notified when rollo...
4,066
def update(self, report): self.tp.extend(pack_boxes(report.tp, self.title)) self.fp.extend(pack_boxes(report.fp, self.title)) self.fn.extend(pack_boxes(report.fn, self.title))
Add the items from the given report.
4,067
def plot_hurst_hist(): import matplotlib.pyplot as plt hs = [nolds.hurst_rs(np.random.random(size=10000), corrected=True) for _ in range(100)] plt.hist(hs, bins=20) plt.xlabel("esimated value of hurst exponent") plt.ylabel("number of experiments") plt.show()
Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package ``matplotlib``.
4,068
def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf): starttime = time.time() self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE, (snipp.BODY_VXLAN_STATE % "enabled")) ...
Enable VXLAN on the switch.
4,069
def delete_repository(self, repository, params=None): if repository in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument .") return self.transport.perform_request(, _make_path(, repository), params=params)
Removes a shared file system repository. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_ :arg repository: A comma-separated list of repository names :arg master_timeout: Explicit operation timeout for connection to master node :arg ...
4,070
def example_describe_configs(a, args): resources = [ConfigResource(restype, resname) for restype, resname in zip(args[0::2], args[1::2])] fs = a.describe_configs(resources) for res, f in fs.items(): try: configs = f.result() for config in iter(co...
describe configs
4,071
def get_version(self, paths=None, default="unknown"): if self.attribute is None: try: f, p, i = find_module(self.module, paths) if f: f.close() return default except ImportError: return None ...
Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the value cannot be determined without importing the module. T...
4,072
def calc_stress_tf(self, lin, lout, damped): tf = self.calc_strain_tf(lin, lout) if damped: tf *= lout.layer.comp_shear_mod else: tf *= lout.layer.shear_mod return tf
Compute the stress transfer function. Parameters ---------- lin : :class:`~site.Location` Location of input lout : :class:`~site.Location` Location of output. Note that this would typically be midheight of the layer.
4,073
def _intertext_score(full_text): sentences = sentence_tokenizer(full_text) norm = _normalize(sentences) similarity_matrix = pairwise_kernels(norm, metric=) scores = _textrank(similarity_matrix) scored_sentences = [] for i, s in enumerate(sentences): scored_sentences.append((scores[...
returns tuple of scored sentences in order of appearance Note: Doing an A/B test to compare results, reverting to original algorithm.
4,074
def constrains(self): params = [] for constraint in self.in_constraints: for var in constraint._vars: param = var.get_parameter() if param.component == constraint.component and param.qualifier == constraint.qualifier: if param not ...
returns a list of parameters that are constrained by this parameter
4,075
def check_ns_run_threads(run): assert run[].dtype == int uniq_th = np.unique(run[]) assert np.array_equal( np.asarray(range(run[].shape[0])), uniq_th), \ str(uniq_th) assert np.any(run[][:, 0] == -np.inf), ( + ) for th_lab in uniq_th: inds = np.wher...
Check thread labels and thread_min_max have expected properties. Parameters ---------- run: dict Nested sampling run to check. Raises ------ AssertionError If run does not have expected properties.
4,076
def get_appium_sessionId(self): self._info("Appium Session ID: " + self._current_application().session_id) return self._current_application().session_id
Returns the current session ID as a reference
4,077
def git_pull(repo_dir, remote="origin", ref=None, update_head_ok=False): command = [, ] if update_head_ok: command.append() command.append(pipes.quote(remote)) if ref: command.append(ref) return execute_git_command(command, repo_dir=repo_dir)
Do a git pull of `ref` from `remote`.
4,078
def encode(locations): encoded = ( (_encode_value(lat, prev_lat), _encode_value(lon, prev_lon)) for (prev_lat, prev_lon), (lat, lon) in _iterate_with_previous(locations, first=(0, 0)) ) encoded = chain.from_iterable(encoded) return .join(c for r in encoded for c in r)
:param locations: locations list containig (lat, lon) two-tuples :return: encoded polyline string
4,079
def confd_state_internal_callpoints_typepoint_registration_type_range_range_daemon_error(self, **kwargs): config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.SubElement(confd_state, "internal") ...
Auto Generated Code
4,080
def _get_file_by_alias(part, files): if _is_output(part): return Output.from_string(part.pop()) else: inputs = [[]] if part.magic_or: and_or = else: and_or = for cut in part.asList(): if cut == OR_TOKEN: ...
Given a command part, find the file it represents. If not found, then returns a new token representing that file. :throws ValueError: if the value is not a command file alias.
4,081
def averageConvergencePoint(self, prefix, minOverlap, maxOverlap, settlingTime=1, firstStat=0, lastStat=None): convergenceSum = 0.0 numCorrect = 0.0 inferenceLength = 1000000 for stats in self.statistics[firstStat:lastStat]: convergencePoint = 0.0 ...
For each object, compute the convergence time - the first point when all L2 columns have converged. Return the average convergence time and accuracy across all objects. Using inference statistics for a bunch of runs, locate all traces with the given prefix. For each trace locate the iteration where it...
4,082
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]: colnames = [col.name for col in get_orm_columns(cls)] return sorted(colnames) if sort else colnames
Gets column names (that is, database column names) from an SQLAlchemy ORM class.
4,083
def expr(args): from jcvi.graphics.base import red_purple as default_cm p = OptionParser(expr.__doc__) opts, args, iopts = p.set_image_options(args, figsize="8x5") if len(args) != 4: sys.exit(not p.print_help()) block, exp, layout, napusbed = args fig = plt.figure(1, (iopts.w, i...
%prog expr block exp layout napus.bed Plot a composite figure showing synteny and the expression level between homeologs in two tissues - total 4 lists of values. block file contains the gene pairs between AN and CN.
4,084
def area(self): r if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) edge1, edge2, edge3 = self._get_edges() return _surface_helpers.com...
r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to ...
4,085
def crypto_box_seal_open(ciphertext, pk, sk): ensure(isinstance(ciphertext, bytes), "input ciphertext must be bytes", raising=TypeError) ensure(isinstance(pk, bytes), "public key must be bytes", raising=TypeError) ensure(isinstance(sk, bytes), "s...
Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's public key ``pk`` and the sender's public key. :param ciphertext: bytes :param pk...
4,086
def _get_query(self, order=None, filters=None): order = self._get_order(order) return self.posts.all().order_by(order)
This method is just to evade code duplication in count() and get_content, since they do basically the same thing
4,087
def _value_iterator(self, task_name, param_name): cp_parser = CmdlineParser.get_instance() if cp_parser: dest = self._parser_global_dest(param_name, task_name) found = getattr(cp_parser.known_args, dest, None) yield (self._parse_or_no_value(found), None) ...
Yield the parameter values, with optional deprecation warning as second tuple value. The parameter value will be whatever non-_no_value that is yielded first.
4,088
def enumerate_global_imports(tokens): imported_modules = [] import_line = False from_import = False parent_module = "" function_count = 0 indentation = 0 for index, tok in enumerate(tokens): token_type = tok[0] token_string = tok[1] if token_type == tokenize.INDE...
Returns a list of all globally imported modules (skips modules imported inside of classes, methods, or functions). Example:: >>> enumerate_global_modules(tokens) ['sys', 'os', 'tokenize', 're'] .. note:: Does not enumerate imports using the 'from' or 'as' keywords.
4,089
def chdir(self, path, timeout=shutit_global.shutit_global_object.default_timeout, note=None, loglevel=logging.DEBUG): shutit = self.shutit shutit.handle_note(note, + path) shutit.log( + path + , level=logging.DEBUG) if shutit.build[] in (,): self.send(ShutItSen...
How to change directory will depend on whether we are in delivery mode bash or docker. @param path: Path to send file to. @param timeout: Timeout on response @param note: See send()
4,090
def infomax(data, weights=None, l_rate=None, block=None, w_change=1e-12, anneal_deg=60., anneal_step=0.9, extended=False, n_subgauss=1, kurt_size=6000, ext_blocks=1, max_iter=200, random_state=None, verbose=None): rng = check_random_state(random_state) max_weight =...
Run the (extended) Infomax ICA decomposition on raw data based on the publications of Bell & Sejnowski 1995 (Infomax) and Lee, Girolami & Sejnowski, 1999 (extended Infomax) Parameters ---------- data : np.ndarray, shape (n_samples, n_features) The data to unmix. w_init : np.ndarray, sh...
4,091
def from_iter(cls, data, name=None): if not name: name = if isinstance(data, (list, tuple)): data = {x: y for x, y in enumerate(data)} values = [{: k, : , : v} for k, v in sorted(data.items())] return cls(name, values=values)
Convenience method for loading data from an iterable. Defaults to numerical indexing for x-axis. Parameters ---------- data: iterable An iterable of data (list, tuple, dict of key/val pairs) name: string, default None Name of the data set. If None (defau...
4,092
def astype(self, dtype, undefined_on_failure=False): if (dtype == _Image) and (self.dtype == array.array): raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.") with cython_context(): return SArr...
Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.datetime} The type to cast the elements to in SArray un...
4,093
def convert_svhn(which_format, directory, output_directory, output_filename=None): if which_format not in (1, 2): raise ValueError("SVHN format needs to be either 1 or 2.") if not output_filename: output_filename = .format(which_format) if which_format == 1: ret...
Converts the SVHN dataset to HDF5. Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible with :class:`fuel.datasets.SVHN`. The converted dataset is saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending on the `which_format` argument. .. [SVHN] Yuval Netzer, Tao Wang, Adam Coate...
4,094
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2, min_shortcircuit=4, max_degree=5, verbose=False): W = W.astype(bool) assert np.all(W == W.T), D = pairwise_distances(X, metric=) avg_edge_length = np.empty(X.shape[0]) for i,nbr_mask in enumerate(W): ...
Given a connected graph adj matrix (W), add edges to flesh it out.
4,095
def compare(orderby_item1, orderby_item2): type1_ord = _OrderByHelper.getTypeOrd(orderby_item1) type2_ord = _OrderByHelper.getTypeOrd(orderby_item2) type_ord_diff = type1_ord - type2_ord if type_ord_diff: return type_ord_diff if t...
compares the two orderby item pairs. :param dict orderby_item1: :param dict orderby_item2: :return: Integer comparison result. The comparator acts such that - if the types are different we get: Undefined value < Null < booleans < Numbers < St...
4,096
def local_fehdist(feh): fehdist= 0.8/0.15*np.exp(-0.5*(feh-0.016)**2./0.15**2.)\ +0.2/0.22*np.exp(-0.5*(feh+0.15)**2./0.22**2.) return fehdist
feh PDF based on local SDSS distribution From Jo Bovy: https://github.com/jobovy/apogee/blob/master/apogee/util/__init__.py#L3 2D gaussian fit based on Casagrande (2011)
4,097
def set_status(self, action, target): try: target = unquote(target) except (AttributeError, TypeError): pass status = "%s (%s) %s" % (self.domain, action, target) status = status.strip().replace(, ) if len(status) >= self.MAXWIDTH: t...
Sets query status with format: "{domain} ({action}) {target}"
4,098
def connect_to_ec2(region=, access_key=None, secret_key=None): if access_key: logger.info(.format(region)) connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: metadat...
Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection
4,099
def raise_205(instance): instance.response.status = 205 instance.response.body = instance.response.body_raw = None raise ResponseException(instance.response)
Abort the current request with a 205 (Reset Content) response code. Clears out the body of the response. :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.Resource` :raises: :class:`webob.exceptions.ResponseException` of status 205