text
stringlengths
78
104k
score
float64
0
0.18
def mark_log(self, filename='system.log'): """ Returns "a mark" to the current position of this node Cassandra log. This is for use with the from_mark parameter of watch_log_for_* methods, allowing to watch the log from the position when this method was called. """ log_fi...
0.007533
def _smartos_zone_pkgsrc_data(): ''' SmartOS zone pkgsrc information ''' # Provides: # pkgsrcversion # pkgsrcpath grains = { 'pkgsrcversion': 'Unknown', 'pkgsrcpath': 'Unknown', } pkgsrcversion = re.compile('^release:\\s(.+)') if os.path.isfile('/etc/pkgsrc_...
0.001885
def toxml(self): """ Exports this object into a LEMS XML object """ # Probably name should be removed altogether until its usage is decided, see # https://github.com/LEMS/LEMS/issues/4 # '''(' name = "{0}"'.format(self.name) if self.name else '') +\''' return '...
0.008557
def rsolve(A, y): """ Robust solve Ax=y. """ from numpy_sugar.linalg import rsolve as _rsolve try: beta = _rsolve(A, y) except LinAlgError: msg = "Could not converge to solve Ax=y." msg += " Setting x to zero." warnings.warn(msg, RuntimeWarning) beta = ze...
0.002841
def _getState(self, name, default=None): "private wrapper around C{self.db.state.getState}" d = self.getObjectId() @d.addCallback def get(objectid): return self.db.state.getState(objectid, name, default) return d
0.007547
def wait(*coros_or_futures, limit=0, timeout=None, loop=None, return_exceptions=False, return_when='ALL_COMPLETED'): """ Wait for the Futures and coroutine objects given by the sequence futures to complete, with optional concurrency limit. Coroutines will be wrapped in Tasks. ``timeout`` c...
0.000335
def phase_type(self, value): '''compresses the waveform horizontally; one of ``"normal"``, ``"resync"``, ``"resync2"``''' self._params.phase_type = value self._overwrite_lock.disable()
0.009259
def join(cls, splits): """ Join an array of ids into a compound id string """ segments = [] for split in splits: segments.append('"{}",'.format(split)) if len(segments) > 0: segments[-1] = segments[-1][:-1] jsonString = '[{}]'.format(''.joi...
0.005587
def now(years=0, days=0, hours=0, minutes=0, seconds=0): """ :param years: int delta of years from now :param days: int delta of days from now :param hours: int delta of hours from now :param minutes: int delta of minutes from now :param seconds: float delta of seconds from now :retur...
0.001786
def Decompress(self, compressed_data): """Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the zlib compressed stream cannot be decompressed. ...
0.005376
def Page(QLExportable): ''' For multi-page files, e.g. if pdf preview ''' def __init__(self, filename, page_id): self.id = page_id super(Page, self).__init__(filename) def export(self, export_format=ExportFormat.PNG): pass
0.016598
def subdivide(network, pores, shape, labels=[]): r''' It trim the pores and replace them by cubic networks with the sent shape. Parameters ---------- network : OpenPNM Network Object pores : array_like The first group of pores to be replaced shape : array_like The shape of...
0.001038
def do_fish_complete(cli, prog_name): """Do the fish completion Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False...
0.002635
def keyPressEvent(self, event): """ Listens for the left/right keys and the escape key to control the slides. :param event | <QtCore.Qt.QKeyEvent> """ if event.key() == QtCore.Qt.Key_Escape: self.cancel() elif event.key() == QtCo...
0.006768
def str_extract(arr, pat, flags=0, expand=True): r""" Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression `pat`. Parameters ---------- pat : str Regular expression patt...
0.000362
def reacher(): """Configuration for MuJoCo's reacher task.""" locals().update(default()) # Environment env = 'Reacher-v2' max_length = 1000 steps = 5e6 # 5M discount = 0.985 update_every = 60 return locals()
0.044248
def map(cls, x, palette, limits, na_value=None, oob=censor): """ Map values to a continuous palette Parameters ---------- x : array_like Continuous values to scale palette : callable ``f(x)`` palette to use na_value : object Va...
0.002472
def calc_lfp_layer(self): """ Calculate the LFP from concatenated subpopulations residing in a certain layer, e.g all L4E pops are summed, according to the `mapping_Yy` attribute of the `hybridLFPy.Population` objects. """ LFPdict = {} lastY = None for Y,...
0.005722
def is_valid_image_extension(file_path): """is_valid_image_extension.""" valid_extensions = ['.jpeg', '.jpg', '.gif', '.png'] _, extension = os.path.splitext(file_path) return extension.lower() in valid_extensions
0.004367
def uncons_term(params, c): """ Description: Computes an additional value for the objective function value when used in an unconstrained optimization formulation. Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) c: constant multiplie...
0.006652
def load_ds_ids_from_config(self): """Get the dataset ids from the config.""" ids = [] for dataset in self.datasets.values(): # xarray doesn't like concatenating attributes that are lists # https://github.com/pydata/xarray/issues/2060 if 'coordinates' in datas...
0.000837
def newTextLen(content, len): """Creation of a new text node with an extra parameter for the content's length """ ret = libxml2mod.xmlNewTextLen(content, len) if ret is None:raise treeError('xmlNewTextLen() failed') return xmlNode(_obj=ret)
0.011407
def eaSimpleConverge(population, toolbox, cxpb, mutpb, ngen, stats=None, halloffame=None, callback=None, verbose=True): """This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, a...
0.000426
def find_time_base(self, gps): '''work out time basis for the log - PX4 native''' t = gps.GPSTime * 1.0e-6 self.timebase = t - self.px4_timebase
0.011905
def room(self, name, participantIdentity=None, **kwargs): """ Create a <Room> element :param name: Room name :param participantIdentity: Participant identity when connecting to the Room :param kwargs: additional attributes :returns: <Room> element """ re...
0.010076
def write_nowait(self, item): """ Write in the box in a non-blocking manner. If the box is full, an exception is thrown. You should always check for fullness with `full` or `wait_not_full` before calling this method. :param item: An item. """ self._queue.put_now...
0.004695
def _choi_to_chi(data, input_dim, output_dim): """Transform Choi representation to the Chi representation.""" num_qubits = int(np.log2(input_dim)) return _transform_to_pauli(data, num_qubits)
0.004926
def format_line_context(filename, lineno, context=10): ''' Formats the the line context for error rendering. :param filename: the location of the file, within which the error occurred :param lineno: the offending line number :param context: number of lines of code to display before and after the ...
0.003279
def _get_tls_object(self, ssl_params): """ Return a TLS object to establish a secure connection to a server """ if ssl_params is None: return None if not ssl_params["verify"] and ssl_params["ca_certs"]: self.warning( "Incorrect configurati...
0.003859
def print_tables(xmldoc, output, output_format, tableList = [], columnList = [], round_floats = True, decimal_places = 2, format_links = True, title = None, print_table_names = True, unique_rows = False, row_span_columns = [], rspan_break_columns = []): """ Method to print tables in an xml file in o...
0.014594
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] == 'event': name = 'do_'+change['name'] if hasattr(self.proxy, name): handler = getattr(self.proxy, name) handler() e...
0.005277
def request_path(request): """Path component of request-URI, as defined by RFC 2965.""" url = request.get_full_url() parts = urlsplit(url) path = escape_path(parts.path) if not path.startswith("/"): # fix bad RFC 2396 absoluteURI path = "/" + path return path
0.003344
def node(self,port, hub_address=("localhost", 4444)): ''' java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/ @param port: listen port of selenium node @param hub_address: hub address which node will connect to ''' self._ip, self._...
0.014572
def native(self): """ The native Python datatype representation of this value :return: A byte string or None """ if self.contents is None: return None if self._parsed is not None: return self._parsed[0].native else: ...
0.00578
def create_value(cls, prop_name, val, model=None): # @NoSelf """This is used to create a value to be assigned to a property. Depending on the type of the value, different values are created and returned. For example, for a list, a ListWrapper is created to wrap it, and returned for the ...
0.001083
def _transpose(cls, char): """Convert unicode char to something similar to it.""" try: loc = ord(char) - 65 if loc < 0 or loc > 56: return char return cls.UNICODE_MAP[loc] except UnicodeDecodeError: return char
0.006711
def get_nonmatching_blocks(matching_blocks): """Given a list of matching blocks, output the gaps between them. Non-matches have the format (alo, ahi, blo, bhi). This specifies two index ranges, one in the A sequence, and one in the B sequence. """ i = j = 0 for match in matching_blocks: ...
0.002451
def _create_update_expression(): """ Create the grammar for an update expression """ ine = ( Word("if_not_exists") + Suppress("(") + var + Suppress(",") + var_val + Suppress(")") ) list_append = ( Word("list_append") + Suppress("(") ...
0.003213
def _convert_from_pandas(self, pdf, schema, timezone): """ Convert a pandas.DataFrame to list of records that can be used to make a DataFrame :return list of records """ if timezone is not None: from pyspark.sql.types import _check_series_convert_timestamps_tz_local...
0.004247
def create_zone(zone, private=False, vpc_id=None, vpc_region=None, region=None, key=None, keyid=None, profile=None): ''' Create a Route53 hosted zone. .. versionadded:: 2015.8.0 zone DNS zone to create private True/False if the zone will be a private zone vpc_...
0.00084
def websocket_safe_read(self): """Returns data if available, otherwise ''. Newlines indicate multiple messages """ data = '' while True: try: data += '{0}\n'.format(self.websocket.recv()) except WebSocketException as e: if isinstance(e, Web...
0.004896
def send(self, data): """ :param data: :type data: bytearray | bytes :return: :rtype: """ data = bytes(data) if type(data) is not bytes else data self._wa_noiseprotocol.send(data)
0.00823
def to_fastq_apipe_cl(sdf_file, start=None, end=None): """Return a command lines to provide streaming fastq input. For paired end, returns a forward and reverse command line. For single end returns a single command line and None for the pair. """ cmd = ["rtg", "sdf2fastq", "--no-gzip", "-o", "-"] ...
0.002766
def add_or_update(self, app_id, value): ''' Adding or updating the evalution. :param app_id: the ID of the post. :param value: the evaluation :return: in JSON format. ''' MEvaluation.add_or_update(self.userinfo.uid, app_id, value) out_dic = { ...
0.004073
def send(self, command): "Send rcon command to server" if self.secure_rcon == self.RCON_NOSECURE: self.sock.send(rcon_nosecure_packet(self.password, command)) elif self.secure_rcon == self.RCON_SECURE_TIME: self.sock.send(rcon_secure_time_packet(self.password, command)) ...
0.003115
def prune(self, depth=0): """ Removes all nodes with less or equal links than depth. """ for n in list(self.nodes): if len(n.links) <= depth: self.remove_node(n.id)
0.009259
def timing(self, stat, value, tags=None): """Report a timing.""" self._log('timing', stat, value, tags)
0.016807
def unpackb(packed, **kwargs): """ Unpack an object from `packed`. Raises `ExtraData` when `packed` contains extra bytes. See :class:`Unpacker` for options. """ unpacker = Unpacker(None, **kwargs) unpacker.feed(packed) try: ret = unpacker._unpack() except OutOfData: ...
0.002128
def expanded_indexer(key, ndim): """Given a key for indexing an ndarray, return an equivalent key which is a tuple with length equal to the number of dimensions. The expansion is done by replacing all `Ellipsis` items with the right number of full slices and then padding the key with full slices so tha...
0.000878
def parse_dict_strings(code): """Generator of elements of a dict that is given in the code string Parsing is shallow, i.e. all content is yielded as strings Parameters ---------- code: String \tString that contains a dict """ i = 0 level = 0 chunk_start = 0 curr_paren = N...
0.001122
def process(self, batch, device=None): """ Process a list of examples to create a torch.Tensor. Pad, numericalize, and postprocess a batch and create a tensor. Args: batch (list(object)): A list of object from a batch of examples. Returns: torch.autograd.Variabl...
0.003788
def _load_general(data, targets): """Load a list of arrays into a list of arrays specified by slices.""" for d_src, d_targets in zip(data, targets): if isinstance(d_targets, nd.NDArray): d_src.copyto(d_targets) else: assert d_targets[-1][0].stop == d_src.shape[0], \ ...
0.005639
def build_from_token_counts(self, token_counts, min_count, num_iterations=4, reserved_tokens=None, max_subtoken_length=None): """Train a SubwordTextEncoder based on a...
0.008117
def receive_offer(self, pkt): """Receive offer on SELECTING state.""" logger.debug("C2. Received OFFER?, in SELECTING state.") if isoffer(pkt): logger.debug("C2: T, OFFER received") self.offers.append(pkt) if len(self.offers) >= MAX_OFFERS_COLLECTED: ...
0.003745
def _ep_need_close(self): """The remote has closed its end of the endpoint.""" LOG.debug("Connection remotely closed") if self._handler: cond = self._pn_connection.remote_condition with self._callback_lock: self._handler.connection_remote_closed(self, cond...
0.006231
def prompt_yes_or_no(message): """ prompt_yes_or_no: Prompt user to reply with a y/n response Args: None Returns: None """ user_input = input("{} [y/n]:".format(message)).lower() if user_input.startswith("y"): return True elif user_input.startswith("n"): return False ...
0.002703
def stop(self, api=None): """ Stop automation run. :param api: sevenbridges Api instance. :return: AutomationRun object """ api = api or self._API return api.post( url=self._URL['actions'].format( id=self.id, action=AutomationRunAction...
0.005587
def print_table(graph, tails, node_id_map): """Print out a table of nodes and the blocks they have at each block height starting with the common ancestor.""" node_count = len(tails) # Get the width of the table columns num_col_width = max( floor(log(max(get_heights(tails)), 10)) + 1, ...
0.000701
def reward_proximity(self): """ Add a wall proximity reward """ if not 'proximity' in self.mode: return mode = self.mode['proximity'] # Calculate proximity reward reward = 0 for sensor in self.player.sensors: if sensor.sensed_type ...
0.006865
def _extract_next_filename(self): """ changes metadata! """ self.ensure_metadata() metadata, body = self[-1] metadata['section'] = sanitize_section(metadata['section']) metadata['root'] = root path = "{root}/Misc/NEWS.d/next/{section}/{date}.bpo-{bpo}.{non...
0.006536
def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear in the o...
0.00075
def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]: """ Partition a list of integers into a list of partitions """ for part in algorithm_u(range(size), nparts): yield part
0.004739
def enable_device(self): """ re-enable the connected device and allow user activity in device again :return: bool """ cmd_response = self.__send_command(const.CMD_ENABLEDEVICE) if cmd_response.get('status'): self.is_enabled = True return True ...
0.005181
def sigres_path(self): """Absolute path of the SIGRES file. Empty string if file is not present.""" # Lazy property to avoid multiple calls to has_abiext. try: return self._sigres_path except AttributeError: path = self.outdir.has_abiext("SIGRES") if p...
0.010724
def create(self, phone_number, sms_capability, account_sid=values.unset, friendly_name=values.unset, unique_name=values.unset, cc_emails=values.unset, sms_url=values.unset, sms_method=values.unset, sms_fallback_url=values.unset, sms_fallback_method=values.unse...
0.005102
def delete(domain, key, user=None): ''' Delete a default from the system CLI Example: .. code-block:: bash salt '*' macdefaults.delete com.apple.CrashReporter DialogType salt '*' macdefaults.delete NSGlobalDomain ApplePersistence domain The name of the domain to delete f...
0.001727
def clear_to_reset(self, config_vars): """Clear all volatile information across a reset.""" self._logger.info("Config vars in sensor log reset: %s", config_vars) super(SensorLogSubsystem, self).clear_to_reset(config_vars) self.storage.destroy_all_walkers() self.dump_walker = No...
0.002941
def get_tasks(self, state=Task.ANY_MASK): """ Returns a list of Task objects with the given state. :type state: integer :param state: A bitmask of states. :rtype: list[Task] :returns: A list of tasks. """ return [t for t in Task.Iterator(self.task_tree,...
0.006098
def update_history(self, it, j=0, M=None, **kwargs): """Add the current state for all kwargs to the history """ # Create a new entry in the history for new variables (if they don't exist) if not np.any([k in self.history[j] for k in kwargs]): for k in kwargs: ...
0.00556
def reindex(self, kdims=[], force=False): """Reindexes object dropping static or supplied kdims Creates a new object with a reordered or reduced set of key dimensions. By default drops all non-varying key dimensions. Reducing the number of key dimensions will discard information ...
0.001597
def inverse_dynamics(self, angles, start=0, end=1e100, states=None, max_force=100): '''Follow a set of angle data, yielding dynamic joint torques. Parameters ---------- angles : ndarray (num-frames x num-dofs) Follow angle data provided by this array of angle values. ...
0.001121
def try_run(obj, names): """Given a list of possible method names, try to run them with the provided object. Keep going until something works. Used to run setup/teardown methods for module, package, and function tests. """ for name in names: func = getattr(obj, name, None) if func is...
0.002075
def makesubatoffset(self, bitoffset, *, _offsetideal=None): """Create a copy of this PromiseCollection with an offset applied to each contained promise and register each with their parent. If this promise's primitive is being merged with another primitive, a new subpromise may be required to ke...
0.00377
def _get_pretty_exception_message(e): """ Parses some DatabaseError to provide a better error message """ if (hasattr(e, 'message') and 'errorName' in e.message and 'message' in e.message): return ('{name}: {message}'.format( na...
0.004577
def description_of(file, name='stdin'): """Return a string describing the probable encoding of a file.""" u = UniversalDetector() for line in file: u.feed(line) u.close() result = u.result if result['encoding']: return '%s: %s with confidence %s' % (name, ...
0.002096
def select_action_key(self, next_action_arr, next_q_arr): ''' Select action by Q(state, action). Args: next_action_arr: `np.ndarray` of actions. next_q_arr: `np.ndarray` of Q-Values. Retruns: `np.ndarray` of keys. ''' ...
0.005093
def pylint_raw(options): """ Use check_output to run pylint. Because pylint changes the exit code based on the code score, we have to wrap it in a try/except block. :param options: :return: """ command = ['pylint'] command.extend(options) proc = subprocess.Popen(command, stdout...
0.004751
def key_exists(self, key, secret=False): ''' Check is given key exists. :param key: Key ID :param secret: Check secret key :rtype: bool ''' if len(key) < 8: return False key = key.upper() res = self.list_keys(secret) for finger...
0.004662
def lookup_folder(event, filesystem): """Lookup the parent folder in the filesystem content.""" for dirent in filesystem[event.parent_inode]: if dirent.type == 'd' and dirent.allocated: return ntpath.join(dirent.path, event.name)
0.003891
def _root_unhook(self): """Change this root console into a normal Console object and delete the root console from TCOD """ global _rootinitialized, _rootConsoleRef # do we recognise this as the root console? # if not then assume the console has already been taken care of ...
0.002103
def QueryAndOwn(self, queue, lease_seconds=10, limit=1): """Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. Returns: A list of GrrMessage() objects le...
0.003745
def run_with_snapshots(self, tsnapstart=0., tsnapint=432000.): """Run the model forward, yielding to user code at specified intervals. Parameters ---------- tsnapstart : int The timestep at which to begin yielding. tstapint : int The interval at which to...
0.008913
def matching_base_url(self, url): """ Return True if the initial part of `url` matches the base url passed to the initialiser of this object, and False otherwise. """ n = len(self.baseurl) return url[0:n] == self.baseurl
0.007435
async def send_tokens(payment_handle: int, tokens: int, address: str) -> str: """ Sends tokens to an address payment_handle is always 0 :param payment_handle: Integer :param tokens: Integer :param address: String Example: payment_handle = 0 amount ...
0.00318
def _expand_address(addy): ''' Convert the libcloud GCEAddress object into something more serializable. ''' ret = {} ret.update(addy.__dict__) ret['extra']['zone'] = addy.region.name return ret
0.004525
def type_id(self): """ A short string representing the provider implementation id used for serialization of :class:`.Credentials` and to identify the type of provider in JavaScript. The part before hyphen denotes the type of the provider, the part after hyphen denotes th...
0.003257
def stop_all(self): """ Stop all nodes """ pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.stop) yield from pool.join()
0.009615
def start(self, start_loop=True): """Start all the things. :param start_loop bool: whether to start the ioloop. should be False if the IOLoop is managed externally """ self.start_alerts() if self.options.get('pidfile'): with open(self....
0.003817
def _get_reference(document_path, reference_map): """Get a document reference from a dictionary. This just wraps a simple dictionary look-up with a helpful error that is specific to :meth:`~.firestore.client.Client.get_all`, the **public** caller of this function. Args: document_path (str)...
0.001175
def tag(iterable, tags=None, key='@tags'): """ Add tags to each dict or dict-like object in ``iterable``. Tags are added to each dict with a key set by ``key``. If a key already exists under the key given by ``key``, this function will attempt to ``.extend()``` it, but will fall back to replacing it...
0.001992
def _process_human_orthos(self, limit=None): """ This table provides ortholog mappings between zebrafish and humans. ZFIN has their own process of creating orthology mappings, that we take in addition to other orthology-calling sources (like PANTHER). We ignore the omim ids, and ...
0.001508
def get_all(self, attr, value, e=0.000001, sort_by="__name__", reverse=False): """Get all nested Constant class that met ``klass.attr == value``. :param attr: attribute name. :param value: value. :param e: used for float value comparison. :param sort_by: nested c...
0.005755
def write( contents: str, path: Union[str, pathlib.Path], verbose: bool = False, logger_func=None, ) -> bool: """ Writes ``contents`` to ``path``. Checks if ``path`` already exists and only write out new contents if the old contents do not match. Creates any intermediate missing di...
0.00078
def process_readme(): """ Function which will process README.md file and divide it into INTRO.md and INSTALL.md, which will be used in documentation """ with open('../../README.md', 'r') as file: readme = file.read() readme = readme.replace('# eo-learn', '# Introduction').replace('docs/sour...
0.005063
def bam_conversion(job, samfile, sample_type, univ_options): """ This module converts SAMFILE from sam to bam ARGUMENTS 1. samfile: <JSid for a sam file> 2. sample_type: string of 'tumor_dna' or 'normal_dna' 3. univ_options: Dict of universal arguments used by almost all tools univ_opt...
0.002165
def _cnv_prioritize(data): """Perform confidence interval based prioritization for CNVs. """ supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cnvkit_prioritize}} pcall = None priority_files = None for call in data.get("sv", []): if call["variantcaller"] in supported:...
0.004402
def get_dweets_for(thing_name, key=None, session=None): """Read all the dweets for a dweeter """ if key is not None: params = {'key': key} else: params = None return _request('get', '/get/dweets/for/{0}'.format(thing_name), params=params, session=None)
0.006944
def from_phase(self, phase_name): """ Returns the result of a previous phase by its name Parameters ---------- phase_name: str The name of a previous phase Returns ------- result: Result The result of that phase Raises ...
0.004373
def zip_dicts(left, right, prefix=()): """ Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries """ for key, left_value in left.items(): path = prefix + (key, ) right...
0.001887
def __calculate_radius(self, number_neighbors, radius): """! @brief Calculate new connectivity radius. @param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius. @param[in] radius (double): Current connectivity radius. ...
0.01675