Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,000
def _expand_dataset_packages(dataset_label_dict): new_dataset_label_dict = [] for label in dataset_label_dict: dataset_metadata = data_urls[label] if type(dataset_metadata) == dict and "package" in dataset_metadata: new_dataset_label_dict.extend(dataset_metadata["package"]) ...
Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'. In case the param is not pointing to multidataset returns only that label in a list. :param str dataset_label_dict: label of multi dataset :return: list of labels
349,001
def fast_scan(self, M, verbose=True): from tqdm import tqdm if M.ndim != 2: raise ValueError("`M` array must be bidimensional.") p = M.shape[1] lmls = empty(p) effsizes0 = empty((p, self._XTQ[0].shape[0])) effsizes0_se = empty((p, self._XTQ[0].shape...
LMLs, fixed-effect sizes, and scales for single-marker scan. Parameters ---------- M : array_like Matrix of fixed-effects across columns. verbose : bool, optional ``True`` for progress information; ``False`` otherwise. Defaults to ``True``. R...
349,002
def create_graph_from_data(self, data): self.arguments[] = self.score self.arguments[] = str(self.verbose).upper() self.arguments[] = str(self.beta) self.arguments[] = str(self.optim).upper() self.arguments[] = str(self.alpha) results = self._run_bnlear...
Run the algorithm on data. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the algorithm.
349,003
def p_string_list(self, t): if len(t) == 4: t[0] = t[1] t[0].append(t[3]) elif t[1]: t[0] = [t[1]] else: t[0] = []
string_list : string_list COMMA STRING | STRING | empty
349,004
def open_remote_file(self, dataset_key, file_name, mode=, **kwargs): try: return RemoteFile(self._config, dataset_key, file_name, mode=mode, **kwargs) except Exception as e: raise RestApiError(cause=e)
Open a remote file object that can be used to write to or read from a file in a data.world dataset :param dataset_key: Dataset identifier, in the form of owner/id :type dataset_key: str :param file_name: The name of the file to open :type file_name: str :param mode: the ...
349,005
def bss_eval_sources(reference_sources, estimated_sources, compute_permutation=True): (sdr, isr, sir, sar, perm) = \ bss_eval( reference_sources, estimated_sources, window=np.inf, hop=np.inf, compute_permutation=compute_permutation, filters_len=5...
BSS Eval v3 bss_eval_sources Wrapper to ``bss_eval`` with the right parameters. The call to this function is not recommended. See the description for the ``bsseval_sources`` parameter of ``bss_eval``.
349,006
def _append_base_arguments(self): if self.exc and self.only: raise PackerException() elif self.exc: self._add_opt(.format(self._join_comma(self.exc))) elif self.only: self._add_opt(.format(self._join_comma(self.only))) for var, value in self.v...
Appends base arguments to packer commands. -except, -only, -var and -var-file are appeneded to almost all subcommands in packer. As such this can be called to add these flags to the subcommand.
349,007
def onlasso(self, verts): p = path.Path(verts) ind = p.contains_points(self.pix, radius=1) self.history.append(self.selection_array.copy()) self.selection_array = self.updateArray(self.selection_array, ind, ...
Main function to control the action of the lasso, allows user to draw on data image and adjust thematic map :param verts: the vertices selected by the lasso :return: nothin, but update the selection array so lassoed region now has the selected theme, redraws canvas
349,008
def injectable_repr(inj_name): i = orca.get_injectable(inj_name) return jsonify(type=str(type(i)), repr=repr(i))
Returns the type and repr of an injectable. JSON response has "type" and "repr" keys.
349,009
def displaceAbs(x, y, sourcePos_x, sourcePos_y): x_mapped = x - sourcePos_x y_mapped = y - sourcePos_y absmapped = np.sqrt(x_mapped**2+y_mapped**2) return absmapped
calculates a grid of distances to the observer in angel :param mapped_cartcoord: mapped cartesian coordinates :type mapped_cartcoord: numpy array (n,2) :param sourcePos: source position :type sourcePos: numpy vector [x0,y0] :returns: array of displacement :raises: AttributeError, KeyError
349,010
def clear(self): super(Router, self).clear() for name in self.todo: filename = os.path.join(self.migrate_dir, name + ) os.remove(filename)
Remove migrations from fs.
349,011
def from_lasio(cls, l, remap=None, funcs=None): params = {} funcs = funcs or {} funcs[] = str for field, (sect, code) in las_fields[].items(): params[field] = utils.lasio_get(l, sect, ...
Make a Location object from a lasio object. Assumes we're starting with a lasio object, l. Args: l (lasio). remap (dict): Optional. A dict of 'old': 'new' LAS field names. funcs (dict): Optional. A dict of 'las field': function() for implementing a tr...
349,012
def _complete_current(self): self._current_text_cursor().insertText(self.currentItem().text()) self.hide()
Perform the completion with the currently selected item.
349,013
def _on_edges(self, object, name, old, new): if name == "edges_items": edges = new.added elif name == "edges": edges = new else: edges = [] all_nodes = [n for g in self.all_graphs for n in g.nodes] for each_edge in edges: ...
Handles the list of edges for any graph changing.
349,014
def approve_assignment(self, assignment_id): try: return self._is_ok( self.mturk.approve_assignment(AssignmentId=assignment_id) ) except ClientError as ex: assignment = self.get_assignment(assignment_id) raise MTurkServiceException...
Approving an assignment initiates two payments from the Requester's Amazon.com account: 1. The Worker who submitted the results is paid the reward specified in the HIT. 2. Amazon Mechanical Turk fees are debited.
349,015
def search_webhook_for_facets(self, **kwargs): kwargs[] = True if kwargs.get(): return self.search_webhook_for_facets_with_http_info(**kwargs) else: (data) = self.search_webhook_for_facets_with_http_info(**kwargs) return data
Lists the values of one or more facets over the customer's webhooks # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_webhook_for_facets(async_req=True) >...
349,016
def quote(symbol, token=, version=): _raiseIfNotStr(symbol) return _getJson( + symbol + , token, version)
Get quote for ticker https://iexcloud.io/docs/api/#quote 4:30am-8pm ET Mon-Fri Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: dict: result
349,017
def ordered_union(l1, l2): out = [] for e in l1 + l2: if e not in out: out.append(e) return out
Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2
349,018
def mulpyplex(self, *stashes): return mulpyplexer.MP(list(itertools.chain.from_iterable(self._stashes[s] for s in stashes)))
Mulpyplex across several stashes. :param stashes: the stashes to mulpyplex :return: a mulpyplexed list of states from the stashes in question, in the specified order
349,019
def edit_group(self, group_id, avatar_id=None, description=None, is_public=None, join_level=None, members=None, name=None, storage_quota_mb=None): path = {} data = {} params = {} path["group_id"] = group_id if name is not N...
Edit a group. Modifies an existing group. Note that to set an avatar image for the group, you must first upload the image file to the group, and the use the id in the response as the argument to this function. See the {file:file_uploads.html File Upload Documentation} for details...
349,020
def general_node_label(self, node): G = self.G if G.node[node][]: return + G.node[node][] else: return + G.node[node][]
Used for debugging - gives a short text description of a graph node.
349,021
def _close_received(self, error): if error: condition = error.condition description = error.description info = error.info else: condition = b"amqp:unknown-error" description = None info = None _logger.info("Received...
Callback called when a connection CLOSE frame is received. This callback will process the received CLOSE error to determine if the connection is recoverable or whether it should be shutdown. :param error: The error information from the close frame. :type error: ~uamqp.errors.Err...
349,022
def orders(self): return [order_cmd for order_cmd in dir(self.handler) if getattr(getattr(self.handler, order_cmd), "bot_order", False)]
Return method tagged "order" in the handler.
349,023
def _rectify(settings): for key, rectifier in _settings_rectifiers.items(): try: new_value = rectifier[](settings[key]) if new_value is False: raise AuthzConfigurationError( .format( _settings_key, key, rectifier[])) ...
Rectify (and validate) the given settings using the functions in :data:`_settings_rectifiers`.
349,024
def replace_webhook(self, scaling_group, policy, webhook, name, metadata=None): return self._manager.replace_webhook(scaling_group, policy, webhook, name, metadata=metadata)
Replace an existing webhook. All of the attributes must be specified. If you wish to delete any of the optional attributes, pass them in as None.
349,025
def permission_set(self, name, func=None): if func is None: return functools.partial(self.predicate, name) self.permission_sets[name] = func return func
Define a new permission set (directly, or as a decorator). E.g.:: @authz.permission_set('HTTP') def is_http_perm(perm): return perm.startswith('http.')
349,026
def _plt_pydot(self, fout_img): dag = self._get_pydot_graph() img_fmt = os.path.splitext(fout_img)[1][1:] dag.write(fout_img, format=img_fmt) self.log.write(" {GO_USR:>3} usr {GO_ALL:>3} GOs WROTE: {F}\n".format( F=fout_img, GO_USR=len(self.godag.go_sou...
Plot using the pydot graphics engine.
349,027
def _refresh(self): while not self._stopevent.isSet(): line = self._serial.readline() try: line = line.encode().decode() except AttributeError: line = line.decode() if LaCrosseSensor.re_reading.match(line): ...
Background refreshing thread.
349,028
def signing_keys(self): if self._signing_keys is None: self._signing_keys = SigningKeyList(self._version, account_sid=self._solution[], ) return self._signing_keys
Access the signing_keys :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyList :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyList
349,029
def _find_remote_bundle(self, ref, remote_service_type=): for r in self.remotes: if remote_service_type and r.service != remote_service_type: continue if not in r.data: continue for k, v in r.data[].items(): if ref...
Locate a bundle, by any reference, among the configured remotes. The routine will only look in the cache directory lists stored in the remotes, which must be updated to be current. :param ref: :return: (remote,vname) or (None,None) if the ref is not found
349,030
def ignore_comments(lines_enum): for line_number, line in lines_enum: line = COMMENT_RE.sub(, line) line = line.strip() if line: yield line_number, line
Strips comments and filter empty lines.
349,031
def extract_context_data(self): data = {} for k, v in { "functionName": "function_name", "functionVersion": "function_version", "memoryLimitInMB": "memory_limit_in_mb", "invokedFunctionArn": "invoked_function_arn", "awsReq...
Returns the contents of a AWS Lambda context. :returns: A dict of relevant context data. :rtype: dict
349,032
def change_size_for_pane(self, pane, up=0, right=0, down=0, left=0): assert isinstance(pane, Pane) def find_split_and_child(split_cls, is_before): " Find the split for which we will have to update the weights. " child = pane split = self._get_parent(child) ...
Increase the size of the current pane in any of the four directions. Positive values indicate an increase, negative values a decrease.
349,033
def _get_all_forecast_from_api(api_result: dict) -> OrderedDict: total_hours_last_forecast = 1.0 last_time = None forecasts_ordered = OrderedDict() for forecast in api_result[]: valid_time = datetime.strptime( forecast[], "%Y-%m-%dT%H:%M:%...
Converts results fråm API to SmhiForeCast list
349,034
def to_int(value=None, hexstr=None, text=None): assert_one_val(value, hexstr=hexstr, text=text) if hexstr is not None: return int(hexstr, 16) elif text is not None: return int(text) elif isinstance(value, bytes): return big_endian_to_int(value) elif isinstance(value, st...
Converts value to it's integer representation. Values are converted this way: * value: * bytes: big-endian integer * bool: True => 1, False => 0 * hexstr: interpret hex as integer * text: interpret as string of digits, like '12' => 12
349,035
def reader(stream, dialect=DIALECT, encoding=False, **fmtparams): r if encoding is False: return UnicodeTextReader(stream, dialect, **fmtparams) if encoding is None: encoding = none_encoding() if not is_8bit_clean(encoding): raise NotImplementedError return UnicodeBytesReader...
r"""CSV reader yielding lists of ``unicode`` strings (PY3: ``str``). Args: stream: Iterable of text (``unicode``, PY3: ``str``) lines. If an ``encoding`` is given, iterable of encoded (``str``, PY3: ``bytes``) lines in the given (8-bit clean) ``encoding``. dialect: Dialect a...
349,036
def get_feature_variable_integer(self, feature_key, variable_key, user_id, attributes=None): variable_type = entities.Variable.Type.INTEGER return self._get_feature_variable_for_type(feature_key, variable_key, variable_type, user_id, attributes)
Returns value for a certain integer variable attached to a feature flag. Args: feature_key: Key of the feature whose variable's value is being accessed. variable_key: Key of the variable whose value is to be accessed. user_id: ID for user. attributes: Dict representing user attributes. ...
349,037
def application(self, environ, start_response): context = environ[] = self.RequestContext(environ=environ) signals = context.extension.signal for ext in signals.pre: ext(context) is_endpoint, handler = context.dispatch(context, context.root, context.environ[]) if is_endpoint: try: res...
Process a single WSGI request/response cycle. This is the WSGI handler for WebCore. Depending on the presence of extensions providing WSGI middleware, the `__call__` attribute of the Application instance will either become this, or become the outermost middleware callable. Most apps won't utilize middlew...
349,038
def get_protein_group_content(pgmap, master): pg_content = [[0, master, protein, len(peptides), len([psm for pgpsms in peptides.values() for psm in pgpsms]), s...
For each master protein, we generate the protein group proteins complete with sequences, psm_ids and scores. Master proteins are included in this group. Returns a list of [protein, master, pep_hits, psm_hits, protein_score], which is ready to enter the DB table.
349,039
def update(self, other, **kwargs): from itertools import chain if hasattr(other, ): other = other.items() for (k, v) in chain(other, kwargs.items()): if ( k not in self or self[k] != v ): self[k]...
Version of ``update`` that doesn't clobber the database so much
349,040
def _collect_unrecognized_values(self, scheme, data, ancestors): if not isinstance(ancestors, OrderedDict): raise TypeError("ancestors must be an OrderedDict. type: {0} was passed.".format(type(ancestors))) if not isinstance(scheme, dict): raise TypeError(.format(type(s...
Looks for values that aren't defined in the scheme and returns a dict with any unrecognized values found. :param scheme: A :dict:, The scheme defining the validations. :param data: A :dict: user supplied for this specific property. :param ancestors: A :OrderedDict: that provides a history of it...
349,041
def run(): obj = CompareGOsCli() obj.write(obj.kws.get(), obj.kws.get(), obj.kws.get(, False))
Compare two or more sets of GO IDs. Best done using sections.
349,042
def diff_with_target(self, binary_im): red = np.array([BINARY_IM_MAX_VAL, 0, 0]) yellow = np.array([BINARY_IM_MAX_VAL, BINARY_IM_MAX_VAL, 0]) green = np.array([0, BINARY_IM_MAX_VAL, 0]) overlap_data = np.zeros([self.height, self.width, 3]) unfilled_px = np.where((self.da...
Creates a color image to visualize the overlap between two images. Nonzero pixels that match in both images are green. Nonzero pixels of this image that aren't in the other image are yellow Nonzero pixels of the other image that aren't in this image are red Parameters ----------...
349,043
def doIt(rh): rh.printSysLog("Enter cmdVM.doIt") if in rh.parms and rh.parms[] is True: rh.printLn("N", "Invocation parameters: ") rh.printLn("N", " Routine: cmdVM." + str(subfuncHandler[rh.subfunction][0]) + "(reqHandle)") rh.printLn("N", " function: " + rh.fu...
Perform the requested function by invoking the subfunction handler. Input: Request Handle Output: Request Handle updated with parsed input. Return code - 0: ok, non-zero: error
349,044
def _concat_same_dtype(self, to_concat, name): attribs = self._get_attributes_dict() attribs[] = name if len({str(x.dtype) for x in to_concat}) != 1: raise ValueError() new_data = type(self._values)._concat_same_type(to_concat).asi8 ...
Concatenate to_concat which has the same class.
349,045
def _open(self, path, skip_to_end = True, offset = None): fh = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK)) if offset is None: if skip_to_end: fh.seek(0, 2) self._offset = fh.tell() else: self._offset = 0 else...
Open `path`, optionally seeking to the end if `skip_to_end` is True.
349,046
def logging_remove_filter(filter_id, **kwargs): ctx = Context(**kwargs) ctx.execute_action(, **{ : ctx.repo.create_secure_service(), : filter_id, })
Remove filter by filter id.
349,047
def select(self, key=None, val=None, log=, out=bool): assert out in [bool, int], "Arg out is not valid (int or bool) !" C0 = key is None or val is None if C0: if out is bool: ind = np.ones((self._nch,), dtype=bool) else: ind = np.a...
The the indices of all channels matching the (key,val) pairs
349,048
def add_child(self, frame, after=None): frame.remove_from_parent() frame.parent = self if after is None: self._children.append(frame) else: index = self._children.index(after) + 1 self._children.insert(index, frame) self._invalidate_t...
Adds a child frame, updating the parent link. Optionally, insert the frame in a specific position by passing the frame to insert this one after.
349,049
def get_result(db, result_id): job = db( , result_id, one=True) return (job.id, job.status, job.user_name, os.path.dirname(job.ds_calc_dir), job.ds_key)
:param db: a :class:`openquake.server.dbapi.Db` instance :param result_id: a result ID :returns: (job_id, job_status, datadir, datastore_key)
349,050
def load_architecture(self, name, arch_info, disassembler, translator): self.name = name self.arch_info = arch_info self.disassembler = disassembler self.ir_translator = translator self._setup_analysis_modules()
Translate to REIL instructions. Args: name (str): Architecture's name. arch_info (ArchitectureInformation): Architecture information object. disassembler (Disassembler): Disassembler for the architecture. translator (Translator): Translator for the architecture.
349,051
def define_buckets(max_seq_len: int, step=10) -> List[int]: buckets = [bucket_len for bucket_len in range(step, max_seq_len + step, step)] buckets[-1] = max_seq_len return buckets
Returns a list of integers defining bucket boundaries. Bucket boundaries are created according to the following policy: We generate buckets with a step size of step until the final bucket fits max_seq_len. We then limit that bucket to max_seq_len (difference between semi-final and final bucket may be less t...
349,052
def make_movie(phenotypes, **kwargs): denom, palette = get_kwargs(phenotypes, kwargs) fig = plt.figure(figsize=(20, 20)) def animate(n): phen_grid = slice_3d_grid(phenotypes, n) grid = color_grid(phen_grid, palette, denom, False) plt.tick_params(lab...
Makes an animation overlaying colored circles representing phenotypes over an imshow() plot indicating the resources present in each cell. By default, color is determined using the palettes in the EnvironmentFile object passed as the first parameter. The easiest way to change color palettes is to assign...
349,053
def julian_day(t: date) -> int: dt = t - julian_base_date return julian_base_number + dt.days
Convert a Python datetime to a Julian day
349,054
def generate_tsid(size=8): chars = string.ascii_uppercase + string.digits _gen = "".join(random.choice(chars) for _ in range(size)) return "PYT" + str(_gen)
Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters ex: PYT9AG234GS :return str: TSid
349,055
def _to_rfc822(date): months = [, , , , , , , , , , , ] days = [, , , , , , ] fmt = return fmt.format( day=days[date.weekday()], d=date.day, month=months[date.month - 1], y=date.year, h=date.hour, m=date.minute, s=date.second, ...
_to_rfc822(datetime.datetime) -> str The datetime `strftime` method is subject to locale-specific day and month names, so this function hardcodes the conversion.
349,056
def update_firewall(self, firewall, body=None): return self.put(self.firewall_path % (firewall), body=body)
Updates a firewall.
349,057
def qteEmulateKeypresses(self, keysequence): keysequence = QtmacsKeysequence(keysequence) key_list = keysequence.toQKeyEventList() if len(key_list) > 0: for event in key_list: self._qteKeyEmulationQueue.ap...
Emulate the Qt key presses that define ``keysequence``. The method will put the keys into a queue and process them one by one once the event loop is idle, ie. the event loop executes all signals and macros associated with the emulated key press first before the next one is emulated. ...
349,058
def _set_status(self, status, ex=None): self._status = status logger.debug("Set status(%s) for %s" % (self._status, self.session_id)) self.set_done() if ex: self._exception = ex
set session status - eg failed, success -- valid values contained in enumAsperaControllerStatus class
349,059
def handle_offchain_secretreveal( target_state: TargetTransferState, state_change: ReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[TargetTransferState]: valid_secret = is_va...
Validates and handles a ReceiveSecretReveal state change.
349,060
def _parse_info(self, info_field): info = dict() for item in info_field.split(): info_item_data = item.split() if len(info_item_data) == 1: info[info_item_data[0]] = True elif len(info_item_d...
Parse the VCF info field
349,061
def cmd(send, msg, args): parser = arguments.ArgParser(args[]) parser.add_argument(, nargs=) parser.add_argument() try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return if cmdargs.section: html = get( % (cmdargs.se...
Gets a man page. Syntax: {command} [section] <command>
349,062
def find_ge(self, item): k = self._key(item) i = bisect_left(self._keys, k) if i != len(self): return self._items[i] raise ValueError( % (k,))
Return first item with a key >= equal to item. Raise ValueError if not found
349,063
def publish_event(self, data, suffix=): try: event_type = data.pop() except KeyError: return {: , : } return self.publish_event_from_dict(event_type, data)
AJAX handler to allow client-side code to publish a server-side event
349,064
def roster(self, year): doc = self.get_year_doc(.format(year)) roster_table = doc() df = sportsref.utils.parse_table(roster_table) starter_table = doc() if not starter_table.empty: start_df = sportsref.utils.parse_table(starter_table) start_df = s...
Returns the roster table for the given year. :year: The year for which we want the roster; defaults to current year. :returns: A DataFrame containing roster information for that year.
349,065
def recorded(self): if self.tune and self.tune.get(): return True if self.tune.get().startswith() else False else: raise PyMediaroomError("No information in <node> about @src")
Return if the stream is a recording.
349,066
def scfmt(sc, ticks, lenout=_default_len_out): sc = ctypes.c_int(sc) ticks = ctypes.c_double(ticks) clkstr = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) libspice.scfmt_c(sc, ticks, lenout, clkstr) return stypes.toPythonString(clkstr)
Convert encoded spacecraft clock ticks to character clock format. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scfmt_c.html :param sc: NAIF spacecraft identification code. :type sc: int :param ticks: Encoded representation of a spacecraft clock count. :type ticks: float :param lenou...
349,067
def getandstrip_varintdata(data): s say you are parsing a transaction from beginning to end, and you know the next byte is a varint byte. Here004830...53aeffffffff...00000000 data = strlify(data) numbytes = numvarintbytes(data[:2]) varint = data[:2*numbytes] data = data[2*numbytes:] to...
Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can do it in one function. This function will...
349,068
def _homogenize_dict(self, frames, intersect=True, dtype=None): result = dict() if isinstance(frames, OrderedDict): result = OrderedDict() adj_frames = OrderedDict() for k, v in frames.items(): if isinstance(v, dict): adj_frames...
Conform set of _constructor_sliced-like objects to either an intersection of indices / columns or a union. Parameters ---------- frames : dict intersect : boolean, default True Returns ------- dict of aligned results & indices
349,069
def fetch(self, start=None, stop=None): if not start: start = 0 if not stop: stop = len(self.log) if start < 0: start = 0 if stop > len(self.log): stop = len(self.log) self.waitForFetc...
Fetch log records and return them as a list. |Args| * ``start`` (**int**): non-negative index of the first log record to return. * ``stop`` (**int**): non-negative index of the last log record to return. |Returns| * **list**: list of log records (see ``lo...
349,070
def create_scene(): scene = trimesh.Scene() geom = trimesh.creation.box((0.5, 0.5, 0.01)) geom.apply_translation((0, 0, -0.005)) geom.visual.face_colors = (.6, .6, .6) scene.add_geometry(geom) geom = trimesh.creation.axis(0.02) scene.add_geometry(geom) box_size = 0.1 ...
Create a scene with a Fuze bottle, some cubes, and an axis. Returns ---------- scene : trimesh.Scene Object with geometry
349,071
def get_setupcfg_version(): try: import configparser except ImportError: import ConfigParser as configparser import re cfg = "setup.cfg" autover_section = config = configparser.ConfigParser() config.read(cfg) pkgname = config.get(,) reponame = config.get(autove...
As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: autover.version.get_setup_version2 ...
349,072
def move(self, fromp, to): frompp = get_pcs_path(fromp) top = get_pcs_path(to) pars = { : , : frompp, : top } self.pd("Remote moving: =mm=> ".format(fromp, to)) return self.__post(pcsurl + , pars, self.__move_act)
Usage: move/mv/rename/ren <from> <to> - \ move a file / dir remotely at Baidu Yun from - source path (file / dir) to - destination path (file / dir)
349,073
def get(self, x, y): x = normalize(x) y = normalize(y) dot_index = pixel_map[y % 4][x % 2] col, row = get_pos(x, y) char = self.chars.get(row, {}).get(col) if not char: return False if type(char) != int: return True retu...
Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel
349,074
def p_GlobalVaribleList(p): if len(p) > 2: p[0] = GlobalVaribleList(p[1], p[3]) else: p[0] = GlobalVaribleList(None, p[1])
GlobalVaribleList : Varible | GlobalVaribleList COMMA Varible
349,075
def data_struct_array(sample, **vectors): if not len(sample): sample = np.zeros((0, 0), dtype=np.int8) else: sample = np.asarray(sample, dtype=np.int8) if sample.ndim < 2: sample = np.expand_dims(sample, 0) num_samples, num_variables = sample.shape ...
Combine samples and per-sample data into a numpy structured array. Args: sample (array_like): Samples, in any form that can be converted into a numpy array. energy (array_like, required): Required keyword argument. Energies, in any form that can be converted into a numpy ...
349,076
def get_blockchain_events_token_network( self, token_address: TokenAddress, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = , ): if not is_binary_address(token_address): raise InvalidAddress( ...
Returns a list of blockchain events coresponding to the token_address.
349,077
def __create_dict(self, si: StoreItem) -> Dict: non_magic_attr = ([attr for attr in dir(si) if not attr.startswith() or attr.__eq__()]) return ({attr: getattr(si, attr) for attr in non_magic_attr})
Return the dict of a StoreItem. This eliminates non_magic attributes and the e_tag. :param si: :return dict:
349,078
def _send_request_safe_mode(self, method, url, **kwargs): try: msg = "processed request:\n" msg += "> {method} {url}\n".format(method=method, url=url) msg += "> kwargs: {kwargs}".format(kwargs=kwargs) logger.log_debug(msg) return requests.Sess...
Send a HTTP request, and catch any exception that might occur due to connection problems. Safe mode has been removed from requests 1.x.
349,079
def expire_filter(lte_time, conn=None): if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): return (r.row[EXPIRE_FIELD] <= lte_time) else: return ( ( (r.row[STATUS_FIELD] == WAITING) | (r.row[STATUS_FIELD] == READY) ) & ...
generates a filter for status==waiting and time older than lte_time
349,080
def xml_import(self, xml_fname=None, xml_content=None, ns_mapping=None, embedded_predicate=None, id_and_revision_extractor=None, extract_empty_embedded=False, keep_attrs_in_created_refere...
This is the generic XML import function for dingos. Its parameters are as follows: - xml_fname: Filename of the XML file to be read - xml_content: Alternatively, the xml_content can be provided as string or as XMLNode (i.e., a piece of XML that has already been parsed) - ns_ma...
349,081
def methods(self): p = lambda o: (isinstance(o, Function) and o.method and self.module._docfilter(o)) return filter(p, self.doc.values())
Returns all documented methods as `pydoc.Function` objects in the class, sorted alphabetically with `__init__` always coming first. Unfortunately, this also includes class methods.
349,082
def query_certificate(self, cert_hash): try: cquery = self.pssl.query_cert(cert_hash) except Exception: self.error( ) try: cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False) e...
Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found. :param cert_hash: hash to query for :type cert_hash: str :return: python dict of results :rtype: dict
349,083
def _master(self): logger.info( , MPI.COMM_WORLD.Get_rank() ) results = [] comm = MPI.COMM_WORLD size = comm.Get_size() sending_voxels = self.voxel_unit if self.voxel_unit < self.num_voxels \ else self.num_voxels curren...
Master node's operation. Assigning tasks to workers and collecting results from them Parameters ---------- None Returns ------- results: list of tuple (voxel_id, accuracy) the accuracy numbers of all voxels, in accuracy descending order ...
349,084
def get(self, request, format=None): tokens = Token.objects.filter(user=request.user) for token in tokens: token.delete() content = {: _()} return Response(content, status=status.HTTP_200_OK)
Remove all auth tokens owned by request.user.
349,085
def run(self, timeout = 0): ptimeout = float( timeout.microseconds/1000000+timeout.seconds if timeout else (self.resolution if timeout is None else 0) ) if self.tokens: events = self.kcontrol(None, self.default_size, ptimeout) len_...
Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. kqueue timeout param is a integer number of nanoseconds (seconds/10**9).
349,086
def _dict_diff(d1, d2): d = {} for key in set(d1).intersection(set(d2)): if d2[key] != d1[key]: d[key] = d2[key] for key in set(d2).difference(set(d1)): d[key] = d2[key] return d
Produce a dict that includes all the keys in d2 that represent different values in d1, as well as values that aren't in d1. :param dict d1: First dict :param dict d2: Dict to compare with :rtype: dict
349,087
def serial_disconnect(self): if self._serial_connected: try: self.serial_connection.close() except c1218.errors.C1218IOError as error: self.logger.error( + str(error)) except serial.serialutil.SerialException as error: self.logger.error( + str(error)) self._serial_connected = False self....
Closes the serial connection to the meter and disconnects from the device.
349,088
def extractSubsetFromWatershed(subset_network_file, subset_network_river_id_field, watershed_file, watershed_network_river_id_field, out_watershed_subset_file): su...
Extract catchment by using subset network file. Use this after using either :func:`~RAPIDpy.gis.taudem.TauDEM.extractSubNetwork()` or :func:`~RAPIDpy.gis.taudem.TauDEM.extractLargestSubNetwork()`. Parameters ---------- subset_network_file: str Path to the pre...
349,089
def P2(self, value): if value > self.P1: self._P2 = value else: raise InvalidSecondDisparityChangePenaltyError("P2 must be greater " "than P1.") self._replace_bm()
Set private ``_P2`` and reset ``_block_matcher``.
349,090
def req2frame(req, N: int=0): if req is None: frame = np.arange(N, dtype=np.int64) elif isinstance(req, int): frame = np.arange(0, N, req, dtype=np.int64) elif len(req) == 1: frame = np.arange(0, N, req[0], dtype=np.int64) elif len(req) == 2: frame = np.arange(req[...
output has to be numpy.arange for > comparison
349,091
def query(self, *args): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT) request_params = dict(self.request_params) if args: request_params[] = .join([str(i) for i in args]) return self.__class__(request_url, request_params, conte...
This method retrieve an iterable object that implements the method __iter__. The arguments given will compose the parameters in the request url. args: strings (String) return: iterable object of Members metadata Example: >>> from crossref.restful import Members ...
349,092
def log10(self, floor=None): def f(dataset, s, floor): arr = dataset[s] arr = np.log10(arr) if floor is not None: arr[arr < floor] = floor dataset[s] = arr self.chunkwise(f, floor=floor)
Take the log base 10 of the entire dataset. Parameters ---------- floor : number (optional) Clip values below floor after log. Default is None.
349,093
def update_ssh_config(self, path="~/.ssh/config"): import sshconf config = sshconf.read_ssh_config(os.path.expanduser(path)) if not config.host(self.instance_name): config.add(self.instance_name) config.set(self.instance_name, Hostname=self.dns) ...
Put the DNS into the ssh config file.
349,094
def parse_redir(self, redir_cmd): redir_cmd_str = redir_cmd[] matched = re.match(r, redir_cmd_str) if matched: redir_cmd_op = matched.group(1) redir_cmd_body = matched.group(2) arg_pos = redir_cmd[][] start_pos = { ...
Parse a command :redir content.
349,095
def QA_get_realtime(code, market): res = None if market == MARKET_TYPE.STOCK_CN: res = QATdx.QA_fetch_get_stock_realtime(code) elif market == MARKET_TYPE.FUTURE_CN: res = QATdx.QA_fetch_get_future_realtime(code) return res
统一的获取期货/股票实时行情的接口
349,096
def _combine(self, original, loc, tokens): combined_tokens = super(CombineNode, self).postParse(original, loc, tokens) internal_assert(len(combined_tokens) == 1, "Combine produced multiple tokens", combined_tokens) return combined_tokens[0]
Implement the parse action for Combine.
349,097
def set_area_geometry(w, src): assert "areaSource" in src.tag geometry_node = src.nodes[get_taglist(src).index("areaGeometry")] area_attrs = parse_area_geometry(geometry_node) w.poly(parts=[area_attrs["polygon"].tolist()])
Set area polygon as shapefile geometry
349,098
def frame(self, min_x=None, min_y=None, max_x=None, max_y=None): ret = self.line_ending.join(self.rows(min_x, min_y, max_x, max_y)) if IS_PY3: return ret return ret.encode()
String representation of the current :class:`Canvas` object pixels. :param min_x: (optional) minimum x coordinate of the canvas :param min_y: (optional) minimum y coordinate of the canvas :param max_x: (optional) maximum x coordinate of the canvas :param max_y: (optional) maximum y coor...
349,099
def state_scope(self, state_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]: return dict(zip(self.rddl.domain.state_fluent_ordering, state_fluents))
Returns a partial scope with current state-fluents. Args: state_fluents (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from state fluent names to :obj:`rddl2tf.fluent.TensorFluent`.