Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
1,100
def findall(dir = os.curdir): all_files = [] for base, dirs, files in os.walk(dir, followlinks=True): if base==os.curdir or base.startswith(os.curdir+os.sep): base = base[2:] if base: files = [os.path.join(base, f) for f in files] all_files.extend(filter(os.p...
Find all files under 'dir' and return the list of full filenames (relative to 'dir').
1,101
def unit_vector_game(n, avoid_pure_nash=False, random_state=None): random_state = check_random_state(random_state) payoff_arrays = (np.zeros((n, n)), random_state.random_sample((n, n))) if not avoid_pure_nash: ones_ind = random_state.randint(n, size=n) payoff_arrays[0][ones_ind, np.ara...
Return a NormalFormGame instance of the 2-player game "unit vector game" (Savani and von Stengel, 2016). Payoffs for player 1 are chosen randomly from the [0, 1) range. For player 0, each column contains exactly one 1 payoff and the rest is 0. Parameters ---------- n : scalar(int) Numbe...
1,102
def contains(self, key): if self._jconf is not None: return self._jconf.contains(key) else: return key in self._conf
Does this configuration contain a given key?
1,103
def get_queryset(self): kwargs = {} if self.ends_at: kwargs.update({ % self.date_field: self.ends_at}) return super(BeforeMixin, self).get_queryset().filter(**kwargs)
Implements before date filtering on ``date_field``
1,104
def remove_unreferenced_items(self, stale_cts): stale_ct_ids = list(stale_cts.keys()) parent_types = (ContentItem.objects.order_by() .exclude(polymorphic_ctype__in=stale_ct_ids) .values_list(, flat=True).distinct()) num_unreferenced = 0 ...
See if there are items that no longer point to an existing parent.
1,105
def get_organizer(self, id, **data): return self.get("/organizers/{0}/".format(id), data=data)
GET /organizers/:id/ Gets an :format:`organizer` by ID as ``organizer``.
1,106
def _copy_from(self, node, copy_leaves=True, overwrite=False, with_links=True): def _copy_skeleton(node_in, node_out): new_annotations = node_out.v_annotations node_in._annotations = new_...
Pass a ``node`` to insert the full tree to the trajectory. Considers all links in the given node! Ignored nodes already found in the current trajectory. :param node: The node to insert :param copy_leaves: If leaves should be **shallow** copied or simply referred to by bot...
1,107
def clear_modules(self): for aModule in compat.itervalues(self.__moduleDict): aModule.clear() self.__moduleDict = dict()
Clears the modules snapshot.
1,108
def add(self, name, path): if not (os.path.exists(path)): raise ValueError("Workspace path `%s` doesn't exists." % path) if (self.exists(name)): raise ValueError("Workspace `%s` already exists." % name) self.config["workspaces"][name] = {"path": path, "reposito...
Add a workspace entry in user config file.
1,109
def read_raw_parser_conf(data: str) -> dict: config = configparser.ConfigParser(allow_no_value=True) config.read_string(data) try: _data: dict = dict(config["commitizen"]) if "files" in _data: files = _data["files"] _f = json.loads(files) _data.update...
We expect to have a section like this ``` [commitizen] name = cz_jira files = [ "commitizen/__version__.py", "pyproject.toml" ] # this tab at the end is important ```
1,110
async def close(self): if self._closed: return self._check_init() self._closing = True warning_callback = None try: warning_callback = self._loop.call_later( 60, self._warn_on_long_close) release_coros = [ ...
Attempt to gracefully close all connections in the pool. Wait until all pool connections are released, close them and shut down the pool. If any error (including cancellation) occurs in ``close()`` the pool will terminate by calling :meth:`Pool.terminate() <pool.Pool.terminate>`. ...
1,111
def solvent_per_layer(self): if self._solvent_per_layer: return self._solvent_per_layer assert not (self.solvent_per_lipid is None and self.n_solvent is None) if self.solvent_per_lipid is not None: assert self.n_solvent is None self._solvent_per_laye...
Determine the number of solvent molecules per single layer.
1,112
def bulk_insert(self, rows, return_model=False): if self.conflict_target or self.conflict_action: compiler = self._build_insert_compiler(rows) objs = compiler.execute_sql(return_id=True) if return_model: return [self.model(**dict(r, **k)) for r, k in...
Creates multiple new records in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: rows: An array of dictionaries, where each dictionary ...
1,113
def add(self, iocb): if _debug: IOGroup._debug("add %r", iocb) self.ioMembers.append(iocb) self.ioState = PENDING self.ioComplete.clear() iocb.add_callback(self.group_callback)
Add an IOCB to the group, you can also add other groups.
1,114
def labels(self): return [ name for name in os.listdir(self.root) if os.path.isdir(os.path.join(self.root, name)) ]
Return the unique labels assigned to the documents.
1,115
def add_url(self, url, description=None): url = { : url, } if description: url[] = description self._append_to(, url)
Add a personal website. Args: :param url: url to the person's website. :type url: string :param description: short description of the website. :type description: string
1,116
def encode_all_features(dataset, vocabulary): def my_fn(features): ret = {} for k, v in features.items(): v = vocabulary.encode_tf(v) v = tf.concat([tf.to_int64(v), [1]], 0) ret[k] = v return ret return dataset.map(my_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset
1,117
def create(cls, env, filenames, trim=False): import_graph = cls(env) for filename in filenames: import_graph.add_file_recursive(os.path.abspath(filename), trim) import_graph.build() return import_graph
Create and return a final graph. Args: env: An environment.Environment object filenames: A list of filenames trim: Whether to trim the dependencies of builtin and system files. Returns: An immutable ImportGraph with the recursive dependencies of all the ...
1,118
def check_exists(path, type=): if type == : if not os.path.isfile(path): raise RuntimeError( % path) else: if not os.path.isdir(path): raise RuntimeError( % path) return True
Check if a file or a folder exists
1,119
def api_walk(uri, per_page=100, key="login"): page = 1 result = [] while True: response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page)) if len(response) == 0: break else: page += 1 for r in response: if key == USER...
For a GitHub URI, walk all the pages until there's no more content
1,120
def terminate_ex(self, nodes, threads=False, attempts=3): while nodes and attempts > 0: if threads: nodes = self.terminate_with_threads(nodes) else: nodes = self.terminate(nodes) if nodes: logger.info("Attempt to termin...
Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :param threads: Whether to use the threaded approach or not. ...
1,121
def main(self): while True: while self.ready: task, a = self.ready.popleft() self.run_task(task, *a) if self.scheduled: timeout = self.scheduled.timeout() if timeout < 0: task,...
Scheduler steps: - run ready until exhaustion - if there's something scheduled - run overdue scheduled immediately - or if there's nothing registered, sleep until next scheduled and then go back to ready - if there's nothing registe...
1,122
def page(self, number): number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page page_items = self.object_list[bottom:top] if not page_items: if number == 1 and self.allow_empty_first_page: ...
Returns a Page object for the given 1-based page number.
1,123
async def update_data_status(self, **kwargs): await self._send_manager_command(ExecutorProtocol.UPDATE, extra_fields={ ExecutorProtocol.UPDATE_CHANGESET: kwargs })
Update (PATCH) Data object. :param kwargs: The dictionary of :class:`~resolwe.flow.models.Data` attributes to be changed.
1,124
def get_neighbor_ip(ip_addr, cidr="30"): our_octet = None neighbor_octet = None try: ip_addr_split = ip_addr.split(".") max_counter = 0 if int(cidr) == 30: ranger = 4 elif int(cidr) == 31: ranger = 2 while max_counter < 256: tr...
Function to figure out the IP's between neighbors address Args: ip_addr: Unicast IP address in the following format 192.168.1.1 cidr: CIDR value of 30, or 31 Returns: returns Our IP and the Neighbor IP in a tuple
1,125
def get_state_variable_from_storage( self, address: str, params: Optional[List[str]] = None ) -> str: params = params or [] (position, length, mappings) = (0, 1, []) try: if params[0] == "mapping": if len(params) < 3: raise Cri...
Get variables from the storage :param address: The contract address :param params: The list of parameters param types: [position, length] or ["mapping", position, key1, key2, ... ] or [position, length, array] :return: The corresponding storage sl...
1,126
def parse_argv(self, argv=None, location=): if argv is None: argv = list(sys.argv) argv.pop(0) self._parse_options(argv, location) self._parse_positional_arguments(argv)
Parse command line arguments. args <list str> or None: The argument list to parse. None means use a copy of sys.argv. argv[0] is ignored. location = '' <str>: A user friendly string describing where the parser got this data from. '' means use "Com...
1,127
async def close_authenticator_async(self): _logger.info("Shutting down CBS session on connection: %r.", self._connection.container_id) try: self._cbs_auth.destroy() _logger.info("Auth closed, destroying session on connection: %r.", self._connection.container_id) ...
Close the CBS auth channel and session asynchronously.
1,128
def formula_dual(input_formula: str) -> str: conversion_dictionary = { : , : , : , : } return re.sub( .join(re.escape(key) for key in conversion_dictionary.keys()), lambda k: conversion_dictionary[k.group(0)], input_formula)
Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :math:`false`. :param str input_formula: original s...
1,129
def get_total_contributors(self, repo): repo_contributors = 0 for contributor in repo.iter_contributors(): repo_contributors += 1 self.unique_contributors[contributor.id].append(repo.name) self.contributors_json[repo.name].append(contributor.to_json()) ...
Retrieves the number of contributors to a repo in the organization. Also adds to unique contributor list.
1,130
def wait_until_done(self, timeout=None): start = datetime.now() if not self.__th: raise IndraDBRestResponseError("There is no thread waiting to " "complete.") self.__th.join(timeout) now = datetime.now() dt = now - s...
Wait for the background load to complete.
1,131
def manage_recurring_payments_profile_status(self, profileid, action, note=None): args = self._sanitize_locals(locals()) if not note: del args[] return self._call(, **args)
Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the chang...
1,132
def set_write_bit(fn): fn = fs_encode(fn) if not os.path.exists(fn): return file_stat = os.stat(fn).st_mode os.chmod(fn, file_stat | stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) if not os.path.isdir(fn): for path in [fn, os.path.dirname(fn)]: try: ...
Set read-write permissions for the current user on the target path. Fail silently if the path doesn't exist. :param str fn: The target filename or path :return: None
1,133
def distance_to_interval(self, start, end): if self.start > end: return self.start - end elif self.end < start: return start - self.end else: return 0
Find the distance between intervals [start1, end1] and [start2, end2]. If the intervals overlap then the distance is 0.
1,134
def expanded_counts_map(self): if self.hpx._ipix is None: return self.counts output = np.zeros( (self.counts.shape[0], self.hpx._maxpix), self.counts.dtype) for i in range(self.counts.shape[0]): output[i][self.hpx._ipix] = self.counts[i] retu...
return the full counts map
1,135
def output(self, resource): @wraps(resource) def wrapper(*args, **kwargs): rv = resource(*args, **kwargs) rv = self.responder(rv) return rv return wrapper
Wrap a resource (as a flask view function). This is for cases where the resource does not directly return a response object. Now everything should be a Response object. :param resource: The resource as a flask view function
1,136
def record_launch(self, queue_id): self.launches.append( AttrDict(queue_id=queue_id, mpi_procs=self.mpi_procs, omp_threads=self.omp_threads, mem_per_proc=self.mem_per_proc, timelimit=self.timelimit)) return len(self.launches)
Save submission
1,137
def safe_print(msg): try: print(msg) except UnicodeEncodeError: try: encoded = msg.encode(sys.stdout.encoding, "replace") decoded = encoded.decode(sys.stdout.encoding, "replace") print(decoded) except (UnicodeDecodeError, UnicodeEncod...
Safely print a given Unicode string to stdout, possibly replacing characters non-printable in the current stdout encoding. :param string msg: the message
1,138
def data_size(self, live_data=None): if live_data is not None: warnings.warn("The keyword argument is deprecated.", DeprecationWarning) output = self.nodetool()[0] return _get_load_from_info_output(output)
Uses `nodetool info` to get the size of a node's data in KB.
1,139
def make_simple_equity_info(sids, start_date, end_date, symbols=None, names=None, exchange=): num_assets = len(sids) if symbols is None: symbols = list(ascii_u...
Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`. Parameters ---------- sids : array-like of int start_date : pd.Timestamp, optional end_date : pd.Timestamp, optional symbols : list, optional Symbols to use for the assets. ...
1,140
def set_usage_rights_courses(self, file_ids, course_id, usage_rights_use_justification, folder_ids=None, publish=None, usage_rights_legal_copyright=None, usage_rights_license=None): path = {} data = {} params = {} path["course_id"] = course_id ...
Set usage rights. Sets copyright and license information for one or more files
1,141
def tcounts(self): df = pd.DataFrame([[t.name(), t.size()] for t in self.tables()], columns=["name", "size"]) df.index = df.name return df
:return: a data frame containing the names and sizes for all tables
1,142
def _npy2fits(d, table_type=, write_bitcols=False): npy_dtype = d[1][1:] if npy_dtype[0] == or npy_dtype[0] == : name, form, dim = _npy_string2fits(d, table_type=table_type) else: name, form, dim = _npy_num2fits( d, table_type=table_type, write_bitcols=write_bitcols) r...
d is the full element from the descr
1,143
def delay_on(self): for retry in (True, False): try: self._delay_on, value = self.get_attr_int(self._delay_on, ) return value except OSError: if retry: self._delay_o...
The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` time can be specified via `delay_on` attribute in milliseconds.
1,144
def import_from_api(request): if request.method == : form = ImportFromAPIForm(request.POST) if form.is_valid(): base_url = re.sub(r, , form.cleaned_data[]) import_url = ( base_url + reverse(, args=[form.cleaned_data[]]) ) ...
Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to.
1,145
async def setex(self, name, time, value): if isinstance(time, datetime.timedelta): time = time.seconds + time.days * 24 * 3600 return await self.execute_command(, name, time, value)
Set the value of key ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
1,146
def copy(self): dup = type(self)() dup._indices = OrderedDict( (k, list(v)) for k,v in six.iteritems(self._indices) ) dup._lines = self._lines.copy() return dup
Create a copy of the mapping, including formatting information
1,147
def set_figure(self, figure, handle=None): self.figure = figure self.bkimage = None self._push_handle = handle wd = figure.plot_width ht = figure.plot_height self.configure_window(wd, ht) doc = curdoc() self.logger.info(str(dir(doc))) ...
Call this with the Bokeh figure object.
1,148
def get(key, default=None): val = os.environ.get(key, default) if val == : val = True elif val == : val = False return val
Retrieves env vars and makes Python boolean replacements
1,149
def substitution(self, substitution): if isinstance(substitution, list): for s in substitution: self.add_substitution(s) else: self.add_substitution(substitution)
Add substitutions to the email :param value: Add substitutions to the email :type value: Substitution, list(Substitution)
1,150
def check_requirements(dist, attr, value): try: list(pkg_resources.parse_requirements(value)) except (TypeError, ValueError) as error: tmpl = ( "{attr!r} must be a string or list of strings " "containing valid project/version requirement specifiers; {error}" ...
Verify that install_requires is a valid requirements list
1,151
def _check_algorithm_values(item): problems = [] for k, v in item.get("algorithm", {}).items(): if v is True and k not in ALG_ALLOW_BOOLEANS: problems.append("%s set as true" % k) elif v is False and (k not in ALG_ALLOW_BOOLEANS and k not in ALG_ALLOW_FALSE): problem...
Check for misplaced inputs in the algorithms. - Identify incorrect boolean values where a choice is required.
1,152
def load(self, table_names=None, table_schemas=None, table_rowgens=None): if table_schemas is not None: table_schemas = self._check_case_dict(table_schemas, warn=True) for schema_key, schema_value in table_schemas.items(): table_schemas[schema_key] = se...
Initiates the tables, schemas and record generators for this database. Parameters ---------- table_names : list of str, str or None List of tables to load into this database. If `auto_load` is true, inserting a record into a new table not provided here will automatically...
1,153
def filter_reads(self, input_bam, output_bam, metrics_file, paired=False, cpus=16, Q=30): nodups = re.sub("\.bam$", "", output_bam) + ".nodups.nofilter.bam" cmd1 = self.tools.sambamba + " markdup -t {0} -r --compression-level=0 {1} {2} 2> {3}".format(cpus, input_bam, nodups, metrics_file) ...
Remove duplicates, filter for >Q, remove multiple mapping reads. For paired-end reads, keep only proper pairs.
1,154
def _from_dict(cls, _dict): args = {} if in _dict: args[] = _dict.get() if in _dict: args[] = [ QueryResult._from_dict(x) for x in (_dict.get()) ] return cls(**args)
Initialize a TopHitsResults object from a json dictionary.
1,155
def call_rpc(*inputs, **kwargs): rpc_executor = kwargs[] output = [] try: value = inputs[1].pop() addr = value.value >> 16 rpc_id = value.value & 0xFFFF reading_value = rpc_executor.rpc(addr, rpc_id) output.append(IOTileReading(0, 0, reading_value)) excep...
Call an RPC based on the encoded value read from input b. The response of the RPC must be a 4 byte value that is used as the output of this call. The encoded RPC must be a 32 bit value encoded as "BBH": B: ignored, should be 0 B: the address of the tile that we should call H: The i...
1,156
def init(plugin_manager, _, _2, _3): page_pattern_course = r page_pattern_scoreboard = r plugin_manager.add_page(page_pattern_course, ScoreBoardCourse) plugin_manager.add_page(page_pattern_scoreboard, ScoreBoard) plugin_manager.add_hook(, course_menu) plugin_manager.add_hook(, task_menu)
Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple scoreboards - content: "taskid1" #creat...
1,157
def cite(self, max_authors=5): citation_data = { : self.title, : self.authors_et_al(max_authors), : self.year, : self.journal, : self.volume, : self.issue, : self.pages, } citation = "{authors} ({year})....
Return string with a citation for the record, formatted as: '{authors} ({year}). {title} {journal} {volume}({issue}): {pages}.'
1,158
def news(symbol, count=10, token=, version=): _raiseIfNotStr(symbol) return _getJson( + symbol + + str(count), token, version)
News about company https://iexcloud.io/docs/api/#news Continuous Args: symbol (string); Ticker to request count (int): limit number of results token (string); Access token version (string); API version Returns: dict: result
1,159
def plot(self, flip=False, ax_channels=None, ax=None, *args, **kwargs): if ax == None: ax = pl.gca() kwargs.setdefault(, ) if ax_channels is not None: flip = self._find_orientation(ax_channels) if not flip: a1 = ax.axes.axvline(self.vert[0]...
{_gate_plot_doc}
1,160
def pow(self, other, axis="columns", level=None, fill_value=None): return self._binary_op( "pow", other, axis=axis, level=level, fill_value=fill_value )
Pow this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to apply pow over. fill_value: The value to fill NaNs with. Re...
1,161
def from_string(cls, string): cls.TYPE.setParseAction(cls.make) try: return cls.TYPE.parseString(string, parseAll=True)[0] except ParseException: log.error("Failed to parse ".format(string)) raise
Parse ``string`` into a CPPType instance
1,162
def cublasSger(handle, m, n, alpha, x, incx, y, incy, A, lda): status = _libcublas.cublasSger_v2(handle, m, n, ctypes.byref(ctypes.c_float(alpha)), int(x), incx, ...
Rank-1 operation on real general matrix.
1,163
def set_quota_volume(name, path, size, enable_quota=False): * cmd = .format(name) if path: cmd += .format(path) if size: cmd += .format(size) if enable_quota: if not enable_quota_volume(name): pass if not _gluster(cmd): return False return True
Set quota to glusterfs volume. name Name of the gluster volume path Folder path for restriction in volume ("/") size Hard-limit size of the volume (MB/GB) enable_quota Enable quota before set up restriction CLI Example: .. code-block:: bash salt '*'...
1,164
def follow_bytes(self, s, index): "Follows transitions." for ch in s: index = self.follow_char(int_from_byte(ch), index) if index is None: return None return index
Follows transitions.
1,165
def removeTab(self, index): curr_index = self.currentIndex() items = list(self.items()) item = items[index] item.close() if index <= curr_index: self._currentIndex -= 1
Removes the tab at the inputed index. :param index | <int>
1,166
def simxStart(connectionAddress, connectionPort, waitUntilConnected, doNotReconnectOnceDisconnected, timeOutInMs, commThreadCycleInMs): if (sys.version_info[0] == 3) and (type(connectionAddress) is str): connectionAddress=connectionAddress.encode() return c_Start(connectionAddress, connectionPort,...
Please have a look at the function description/documentation in the V-REP user manual
1,167
def hasReaders(self, ulBuffer): fn = self.function_table.hasReaders result = fn(ulBuffer) return result
inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes.
1,168
def apply_mask(self, x=None): if x is None: return np.delete(np.arange(len(self.time)), self.mask) else: return np.delete(x, self.mask, axis=0)
Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None`
1,169
def command_x(self, x, to=None): if to is None: ActionChains(self.driver) \ .send_keys([Keys.COMMAND, x, Keys.COMMAND]) \ .perform() else: self.send_keys(to, [Keys.COMMAND, x, Keys.COMMAND])
Sends a character to the currently active element with Command pressed. This method takes care of pressing and releasing Command.
1,170
def crop_frequencies(self, low=None, high=None, copy=False): if low is not None: low = units.Quantity(low, self._default_yunit) if high is not None: high = units.Quantity(high, self._default_yunit) if low is not None and low == self.f0: low =...
Crop this `Spectrogram` to the specified frequencies Parameters ---------- low : `float` lower frequency bound for cropped `Spectrogram` high : `float` upper frequency bound for cropped `Spectrogram` copy : `bool` if `False` return a view of t...
1,171
def format_choices(self): ce = enumerate(self.choices) f = lambda i, c: % (c, i+1) toks = [f(i,c) for i, c in ce] + [] return .join(toks)
Return the choices in string form.
1,172
def set_current_thumbnail(self, thumbnail): self.current_thumbnail = thumbnail self.figure_viewer.load_figure( thumbnail.canvas.fig, thumbnail.canvas.fmt) for thumbnail in self._thumbnails: thumbnail.highlight_canvas(thumbnail == self.current_thumbnail)
Set the currently selected thumbnail.
1,173
def text_entry(self): allowed_sequences = set([, , ]) sys.stdout.write() sys.stdout.flush() cur_column -= 1 else: self.roku.literal(val) sys.stdout.write(val) cur_column += 1 ...
Relay literal text entry from user to Roku until <Enter> or <Esc> pressed.
1,174
def get_dict(self): return {: self.get_name(), : self.get_address(), : self.get_protocol(), : self.get_tcp_port()}
Returns a dict containing the host's attributes. The following keys are contained: - hostname - address - protocol - port :rtype: dict :return: The resulting dictionary.
1,175
def clear_graph(identifier=None): graph = get_graph() if identifier: graph.destroy(identifier) try: graph.close() except: warn("Unable to close the Graph")
Clean up a graph by removing it :param identifier: Root identifier of the graph :return:
1,176
def local_global_attention(x, self_attention_bias, hparams, q_padding="LEFT", kv_padding="LEFT"): with tf.variable_scope("self_local_global_att"): [x_global, x_local] = tf.split(x, 2, axis=-1) split_...
Local and global 1d self attention.
1,177
def compute(self, inputs, outputs): if "resetIn" in inputs: assert len(inputs["resetIn"]) == 1 if inputs["resetIn"][0] != 0: self._tm.reset() outputs["activeCells"][:] = 0 outputs["nextPredictedCells"][:] = 0 outputs["predictedActiveCells"][:] = 0 ...
Run one iteration of TM's compute.
1,178
def root_manifest_id(self, root_manifest_id): if root_manifest_id is not None and len(root_manifest_id) > 32: raise ValueError("Invalid value for `root_manifest_id`, length must be less than or equal to `32`") self._root_manifest_id = root_manifest_id
Sets the root_manifest_id of this UpdateCampaignPutRequest. :param root_manifest_id: The root_manifest_id of this UpdateCampaignPutRequest. :type: str
1,179
def list_namespaced_stateful_set(self, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs) else: (data) = self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs) ...
list_namespaced_stateful_set # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_stateful_set(namespace, async_req...
1,180
def create_wsgi_request(event, server_name=): path = urllib.url2pathname(event[]) script_name = ( event[][].endswith() and event[][] or ).encode() query = event[] query_string = query and urllib.urlencode(query) or "" body = event[] and event[].encode() or environ = { ...
Create a wsgi environment from an apigw request.
1,181
def flatten(text): lines = text.split("\n") tokens = [] for l in lines: if len(l) == 0: continue l = l.replace("\t", " ") tokens += filter(lambda x: len(x) > 0, l.split(" ")) + [] capturing = False captured = [] flattened = [] while len...
Flatten the text: * make sure each record is on one line. * remove parenthesis
1,182
def wishart_pairwise_pvals(self, axis=0): if axis != 0: raise NotImplementedError("Pairwise comparison only implemented for colums") return WishartPairwiseSignificance.pvals(self, axis=axis)
Return square symmetric matrix of pairwise column-comparison p-values. Square, symmetric matrix along *axis* of pairwise p-values for the null hypothesis that col[i] = col[j] for each pair of columns. *axis* (int): axis along which to perform comparison. Only columns (0) are implemente...
1,183
def parse_binary_descriptor(bindata): func_names = {0: , 1: , 2: , 3: , 4: , 5: , 6: , 7: } if len(bindata) != 20: raise ArgumentError("Invalid binary node descriptor with incorrect size", size=len(bindata), expected=20, bindata=bindata) ...
Convert a binary node descriptor into a string descriptor. Binary node descriptor are 20-byte binary structures that encode all information needed to create a graph node. They are used to communicate that information to an embedded device in an efficent format. This function exists to turn such a com...
1,184
def split_header(fp): body_start, header_ended = 0, False lines = [] for line in fp: if line.startswith() and not header_ended: body_start += 1 else: header_ended = True lines.append(line) retur...
Read file pointer and return pair of lines lists: first - header, second - the rest.
1,185
def moment_sequence(self): r A, C, G, H = self.A, self.C, self.G, self.H mu_x, Sigma_x = self.mu_0, self.Sigma_0 while 1: mu_y = G.dot(mu_x) if H is None: Sigma_y = G.dot(Sigma_x).dot(G.T) else: Sigma_...
r""" Create a generator to calculate the population mean and variance-convariance matrix for both :math:`x_t` and :math:`y_t` starting at the initial condition (self.mu_0, self.Sigma_0). Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x, Sigma_y) for the next period...
1,186
def example_yaml(cls, skip=()): return cls.example_instance(skip=skip).to_yaml(skip=skip)
Generate an example yaml string for a Serializable subclass. If traits have been tagged with an `example` value, then we use that value. Otherwise we fall back the default_value for the instance.
1,187
def get_available_tokens(self, count=10, token_length=15, **kwargs): token_buffer = int(math.ceil(count * .05)) if token_buffer < 5: token_buffer = 5 available = set([]) while True: tokens = [random_alphanum(length=token_length) ...
Gets a list of available tokens. :param count: the number of tokens to return. :param token_length: the length of the tokens. The higher the number the easier it will be to return a list. If token_length == 1 there's a strong probability that the enough tokens will exist in ...
1,188
def _bulk_to_linear(M, N, L, qubits): "Converts a list of chimera coordinates to linear indices." return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits]
Converts a list of chimera coordinates to linear indices.
1,189
def _get_user_agent(): client = "{0}/{1}".format(__name__.split(".")[0], ver.__version__) python_version = "Python/{v.major}.{v.minor}.{v.micro}".format( v=sys.version_info ) system_info = "{0}/{1}".format(platform.system(), platform.release()) user_...
Construct the user-agent header with the package info, Python version and OS version. Returns: The user agent string. e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0'
1,190
def channels_set_topic(self, room_id, topic, **kwargs): return self.__call_api_post(, roomId=room_id, topic=topic, kwargs=kwargs)
Sets the topic for the channel.
1,191
def dateindex(self, col: str): df = self._dateindex(col) if df is None: self.err("Can not create date index") return self.df = df self.ok("Added a datetime index from column", col)
Set a datetime index from a column :param col: column name where to index the date from :type col: str :example: ``ds.dateindex("mycol")``
1,192
def _parse_textgroup_wrapper(self, cts_file): try: return self._parse_textgroup(cts_file) except Exception as E: self.logger.error("Error parsing %s ", cts_file) if self.RAISE_ON_GENERIC_PARSING_ERROR: raise E
Wraps with a Try/Except the textgroup parsing from a cts file :param cts_file: Path to the CTS File :type cts_file: str :return: CtsTextgroupMetadata
1,193
def _gradient_penalty(self, real_samples, fake_samples, kwargs): import torch from torch.autograd import Variable, grad real_samples = real_samples.view(fake_samples.shape) subset_size = real_samples.shape[0] real_samples = real_samples[:subset_size] fake_samp...
Compute the norm of the gradients for each sample in a batch, and penalize anything on either side of unit norm
1,194
def min(self): res = self._qexec("min(%s)" % self._name) if len(res) > 0: self._min = res[0][0] return self._min
:returns the minimum of the column
1,195
def unit(w, sparsity): w_shape = common_layers.shape_list(w) count = tf.to_int32(w_shape[-1] * sparsity) mask = common_layers.unit_targeting(w, count) return (1 - mask) * w
Unit-level magnitude pruning.
1,196
def new(image): pointer = vips_lib.vips_region_new(image.pointer) if pointer == ffi.NULL: raise Error() return pyvips.Region(pointer)
Make a region on an image. Returns: A new :class:`.Region`. Raises: :class:`.Error`
1,197
def pipeline_launchpad(job, fastqs, univ_options, tool_options): univ_options[] = fastqs[] ncpu = cpu_count() tool_options[][] = tool_options[][] = tool_options[][] = \ tool_options[][] = ncpu / 3 sample_prep = job.wrapJobFn(prepare_samples, fastqs, univ_options, di...
The precision immuno pipeline begins at this module. The DAG can be viewed in Flowchart.txt This module corresponds to node 0 on the tree
1,198
def todict(self, exclude_cache=False): odict = {} for field, value in self.fieldvalue_pairs(exclude_cache=exclude_cache): value = field.serialise(value) if value: odict[field.name] = value if self._dbdata and in self._dbdata: odict[] ...
Return a dictionary of serialised scalar field for pickling. If the *exclude_cache* flag is ``True``, fields with :attr:`Field.as_cache` attribute set to ``True`` will be excluded.
1,199
def parse_xmlsec_output(output): for line in output.splitlines(): if line == : return True elif line == : raise XmlsecError(output) raise XmlsecError(output)
Parse the output from xmlsec to try to find out if the command was successfull or not. :param output: The output from Popen :return: A boolean; True if the command was a success otherwise False