Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
345,100
def _move_file_to_dest_dir(self, filename): assert self._params.move_to if os.path.isdir(self._params.move_to): _logger.debug(, self._warc_filename, self._params.move_to) shutil.move(filename, self._params.move_to) else: _lo...
Move the file to the ``move_to`` directory.
345,101
def get_cands_uri(field, ccd, version=, ext=, prefix=None, block=None): if prefix is None: prefix = "" if len(prefix) > 0: prefix += "_" if len(field) > 0: field += "_" if ext is None: ext = "" if len(ext) > 0 and ext[0] != ".": ext = ...
return the nominal URI for a candidate file. @param field: the OSSOS field name @param ccd: which CCD are the candidates on @param version: either the 'p', or 's' (scrambled) candidates. @param ext: Perhaps we'll change this one day. @param prefix: if this is a 'fake' dataset then add 'fk' @par...
345,102
def search_user_for_facet(self, facet, **kwargs): kwargs[] = True if kwargs.get(): return self.search_user_for_facet_with_http_info(facet, **kwargs) else: (data) = self.search_user_for_facet_with_http_info(facet, **kwargs) return data
Lists the values of a specific facet over the customer's users # 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_user_for_facet(facet, async_req=True) >>>...
345,103
def get_port_channel_detail_output_lacp_partner_oper_priority(self, **kwargs): config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_detail, "output") lacp = ...
Auto Generated Code
345,104
async def trigger_event(self, event, *args): handler_name = + event if hasattr(self, handler_name): handler = getattr(self, handler_name) if asyncio.iscoroutinefunction(handler) is True: try: ret = await handler(*args) ...
Dispatch an event to the proper handler method. In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catche...
345,105
def members(self): if self._members is None: self._members = MemberList( self._version, account_sid=self._solution[], queue_sid=self._solution[], ) return self._members
Access the members :returns: twilio.rest.api.v2010.account.queue.member.MemberList :rtype: twilio.rest.api.v2010.account.queue.member.MemberList
345,106
def size(self, time): if self.start_time <= time <= self.end_time: return self.masks[time - self.start_time].sum() else: return 0
Gets the size of the object at a given time. Args: time: Time value being queried. Returns: size of the object in pixels
345,107
def snapshots_delete(container, name, remote_addr=None, cert=None, key=None, verify_cert=True): certkeyremote_addr* cont = container_get( container, remote_addr, cert, key, verify_cert, _raw=True ) try: for s in cont.snapshots.all(): if s.name == name: ...
Delete a snapshot for a container container : The name of the container to get. name : The name of the snapshot. remote_addr : An URL to a remote server. The 'cert' and 'key' fields must also be provided if 'remote_addr' is defined. Examples: https://m...
345,108
def write_all_series_channel_values(self, read_f, write_f, channel, values): values = copy.deepcopy(values) original_values = self.read_all_series_channel_values(read_f, channel) ...
Return all values for the specified channel of the type corresponding to the function `f`, where `f` is either `self.series_resistance` or `self.series_capacitance`.
345,109
def to_int(self): coord = [int(round(x)) for x in self.xy_coord()] return self.from_xy(coord[0], coord[1], coord[2], coord[3])
Rounds off and converts (x,y,w,h) to int :return: a Box object with all integer values
345,110
def dyndoc_insert(src): import json import re def mkblock(d, flag=0): v = json.dumps(d, indent=2) if flag == 1: nw = re.findall(, v, flags=re.S) v = nw[0] return "\n{}".format("".join(["{0:>16}{1}\n"....
docstring_insert - a decorator to insert API-docparts dynamically.
345,111
def run(command=None, *arguments): if command is None: sys.exit() if command in ALIASES: command = ALIASES[command] if command == : return call( % .join(arguments), shell=True) script_path = os.getcwd() while not os.path.exists(os.path.join(script_path, )): b...
Run the given command. Parameters: :param command: A string describing a command. :param arguments: A list of strings describing arguments to the command.
345,112
def draw_route(self, df_route, cr, color=None, line_width=None): df_route_centers = (self.canvas.df_shape_centers .ix[df_route.electrode_i][[, ]]) df_endpoint_marker = (.6 * self.get_endpoint_marker(df_route_cent...
Draw a line between electrodes listed in a route. Arguments --------- - `df_route`: * A `pandas.DataFrame` containing a column named `electrode_i`. * For each row, `electrode_i` corresponds to the integer index of the corresponding electrode. ...
345,113
def spawn(self): self._process = subprocess.Popen( [self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self.addCleanup(self._process_kill)
Spawn the fake executable using subprocess.Popen.
345,114
def split_by_value( total, nodes, headdivisor=2.0 ): head_sum,tail_sum = 0,0 divider = 0 for node in nodes[::-1]: if head_sum < total/headdivisor: head_sum += node[0] divider -= 1 else: break return (head_sum,nodes[divider:]),(total-head_sum,nodes...
Produce, (sum,head),(sum,tail) for nodes to attempt binary partition
345,115
def getVariants(self, referenceName, startPosition, endPosition, callSetIds=[]): if callSetIds is None: callSetIds = self._callSetIds else: for callSetId in callSetIds: if callSetId not in self._callSetIds: raise ex...
Returns an iterator over the specified variants. The parameters correspond to the attributes of a GASearchVariantsRequest object.
345,116
def cleanup(self): task = self.task job_ids = [ d["job_id"] for d in self.submission_data.jobs.values() if d["job_id"] not in (self.submission_data.dummy_job_id, None) ] if not job_ids: return task.publish_message("...
Cleans up jobs on the remote run location. The job ids are read from the submission file which has to exist for obvious reasons.
345,117
def parse (cls, line, lineno, log, cmddict): delay = SeqDelay .parse(line, lineno, log, cmddict) attrs = SeqCmdAttrs.parse(line, lineno, log, cmddict) comment = SeqComment .parse(line, lineno, log, cmddict) stop = len(line) if comment: stop = comment.pos.col.start - 1 if at...
Parses the sequence command from a line of text, according to the given command dictionary, and returns a new SeqCmd.
345,118
def _GetShowID(self, stringSearch, origStringSearch = None): showInfo = tvfile.ShowInfo() if origStringSearch is None: goodlogging.Log.Info("RENAMER", "Looking up show ID for: {0}".format(stringSearch)) origStringSearch = stringSearch goodlogging.Log.IncreaseIndent() showInfo.showID ...
Search for given string as an existing entry in the database file name table or, if no match is found, as a show name from the TV guide. If an exact match is not found in the database the user can accept or decline the best match from the TV guide or can provide an alternate match to lookup. Param...
345,119
def index(self, fields, name=None, **kwargs): field_name return self.proxy.index(fields=fields, name=name, table=self.name, **kwargs)
Build a new index on a cube. Examples: + index('field_name') :param fields: A single field or a list of (key, direction) pairs :param name: (optional) Custom name to use for this index :param collection: cube name :param owner: username of cube owner
345,120
def awsS3Credentials(self, *args, **kwargs): return self._makeApiCall(self.funcinfo["awsS3Credentials"], *args, **kwargs)
Get Temporary Read/Write Credentials S3 Get temporary AWS credentials for `read-write` or `read-only` access to a given `bucket` and `prefix` within that bucket. The `level` parameter can be `read-write` or `read-only` and determines which type of credentials are returned. Please note t...
345,121
def _status_code_check(self, response: Dict[str, Any]): code = response.get("CODE") if self.debug: print("resv:{}".format(response)) print(code) if code >= 500: if self.debug: print("server error") return self._server_erro...
检查响应码并进行对不同的响应进行处理. 主要包括: + 编码在500~599段为服务异常,直接抛出对应异常 + 编码在400~499段为调用异常,为对应ID的future设置异常 + 编码在300~399段为警告,会抛出对应警告 + 编码在200~399段为执行成功响应,将结果设置给对应ID的future. + 编码在100~199段为服务器响应,主要是处理验证响应和心跳响应 Parameters: response (Dict[str, Any]): - 响应的python字典形式数据 ...
345,122
def _writer(func): name = func.__name__ return property(fget=lambda self: getattr(self, % name), fset=func)
Decorator for a custom writer, but a default reader
345,123
def ensure_flat_galactic(f): @wraps(f) def _wrapper_func(self, coords, **kwargs): if coords.frame.name != : gal = coords.transform_to() else: gal = coords is_array = not coords.isscalar if is_array: orig_shape = coord...
A decorator for class methods of the form .. code-block:: python Class.method(self, coords, **kwargs) where ``coords`` is an :obj:`astropy.coordinates.SkyCoord` object. The decorator ensures that the ``coords`` that gets passed to ``Class.method`` is a flat array of Galactic coordinates. It ...
345,124
def replica_set_link(rel, repl_id=None, member_id=None, self_rel=False): repls_href = link = _REPLICA_SET_LINKS[rel].copy() link[] = link[].format(**locals()) link[] = if self_rel else rel return link
Helper for getting a ReplicaSet link document, given a rel.
345,125
def save_target_classes(self, filename): with open(filename, ) as f: for k, v in self._target_classes.items(): f.write(.format(k, v))
Saves target classed for all dataset images into given file.
345,126
def arg_match(m_arg, arg, comparator=eq, default=False): if m_arg is None: return default if isinstance(m_arg, dict): for name, value in m_arg.items(): name, _comparator = arg_comparitor(name) subarg = getattr(arg, name, InvalidArg) if subarg is InvalidAr...
:param m_arg: value to match against or callable :param arg: arg to match :param comparator: function that returns True if m_arg and arg match :param default: will be returned if m_arg is None if m_arg is a callable it will be called with arg >>> arg_match(1, 1) True >>> arg_match(1, 2) ...
345,127
def get_player(first_name, last_name=None, season=constants.CURRENT_SEASON, only_current=0, just_id=True): if last_name is None: name = first_name.lower() else: name = .format(last_name, first_name).lower() pl = PlayerList(seas...
Calls our PlayerList class to get a full list of players and then returns just an id if specified or the full row of player information Args: :first_name: First name of the player :last_name: Last name of the player (this is None if the player only has first name [Nene]) :only_c...
345,128
def run(self): self.output( % .join(map(str, self.bands)), normal=True, arrow=True) bands = self._read_bands() image_data = self._get_image_data() new_bands = self._generate_new_bands(image_data[]) self._warp(image_data, bands, new_bands) del bands ...
Executes the image processing. :returns: (String) the path to the processed image
345,129
def draw(self): if not self.visible: return self.window.blit(self.textImage, self.loc)
Draws the current text in the window
345,130
def find_egg(self, egg_dist): site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.project_name) try: user_site = site.getusersitepackages() except AttributeError: user_site = site.USER_SITE search_locations = [site_pack...
Find an egg by name in the given environment
345,131
def _coupling_matrix(self, lmax, nwin=None, weights=None): if nwin is None: nwin = self.nwin if weights is None: weights = self.weights if weights is None: return _shtools.SHMTCouplingMatrix(lmax, self.tapers**2, k=nwin) else: re...
Return the coupling matrix of the first nwin tapers.
345,132
def labels(self): if type(self.object_list) == type([]): model = self.formset.model else: model = self.object_list.model for field in self.visible_fields: name = None if self.formset: f = self.formset.empty_form.fields.ge...
Get field label for fields
345,133
def get_dataset(self, key, info): logger.debug(, key.name) if key.name in chans_dict: m_data = self.read_dataset(key, info) else: m_data = self.read_geo(key, info) m_data.attrs.update(info) return m_data
Load a dataset
345,134
def meth_acl(args): r = fapi.get_repository_method_acl(args.namespace, args.method, args.snapshot_id) fapi._check_response_code(r, 200) acls = sorted(r.json(), key=lambda k: k[]) return map(lambda acl: .format(acl[], acl[]), acls)
Retrieve access control list for given version of a repository method
345,135
def from_storage(cls, storage): args = dict(storage.settings.get(, {})) args[] = storage return cls(**args)
Load from storage. Parameters ---------- storage : `markovchain.storage.Storage` Returns ------- `markovchain.Markov`
345,136
def ConvGRUCell(units, kernel_size=(3, 3)): def BuildConv(): return core.Conv(filters=units, kernel_size=kernel_size, padding=) return GeneralGRUCell( candidate_transform=BuildConv, memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Ta...
Builds a convolutional GRU. Paper: https://arxiv.org/abs/1511.06432. Args: units: Number of hidden units kernel_size: Kernel size for convolution Returns: A Stax model representing a GRU cell with convolution transforms.
345,137
def space_clone(args): if not args.to_workspace: args.to_workspace = args.workspace if not args.to_project: args.to_project = args.project if (args.project == args.to_project and args.workspace == args.to_workspace): eprint("Error: destination project and names...
Replicate a workspace
345,138
def create_for_data(cls, data, format, width, height, stride=None): return cls(format, width, height, data, stride)
Same as ``ImageSurface(format, width, height, data, stride)``. Exists for compatibility with pycairo.
345,139
def getCmd(snmpDispatcher, authData, transportTarget, *varBinds, **options): def cbFun(*args, **kwargs): response[:] = args options[] = cbFun errorIndication, errorStatus, errorIndex = None, 0, 0 response = [] while True: if varBinds: cmdgen.getCmd(snm...
Creates a generator to perform one or more SNMP GET queries. On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatc...
345,140
def _get_rev(self, fpath): rev = None try: cmd = ["git", "log", "-n1", "--pretty=format:\"%h\"", fpath] rev = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()[0] except: pass if not rev: try: cmd...
Get an SCM version number. Try svn and git.
345,141
def request_homescreen(blink): url = "{}/api/v3/accounts/{}/homescreen".format(blink.urls.base_url, blink.account_id) return http_get(blink, url)
Request homescreen info.
345,142
def _parse_keyvals(self, line_iter): out = None line = None for line in line_iter: if len(line) == 1 and line[0].upper() == line[0]: break else: if out is None: while not line[-1]: ...
Generate dictionary from key/value pairs.
345,143
def get_content_json(request): result = _get_content_json() resp = request.response resp.status = "200 OK" resp.content_type = resp.body = json.dumps(result) return result, resp
Retrieve content as JSON using the ident-hash (uuid@version).
345,144
def normalized_tokens(s, string_options=DEFAULT_STRING_OPTIONS, token_options=DEFAULT_TOKEN_OPTIONS, strip_parentheticals=True, whitespace=False, languages=None): s deterministic normalizations i.e. methods with a single output. The string tree v...
Normalizes a string, tokenizes, and normalizes each token with string and token-level options. This version only uses libpostal's deterministic normalizations i.e. methods with a single output. The string tree version will return multiple normalized strings, each with tokens. Usage: normal...
345,145
def ticket_form_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/ticket_forms api_path = "/api/v2/ticket_forms.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/ticket_forms#create-ticket-forms
345,146
def addAggShkDstn(self,AggShkDstn): if len(self.IncomeDstn[0]) > 3: self.IncomeDstn = self.IncomeDstnWithoutAggShocks else: self.IncomeDstnWithoutAggShocks = self.IncomeDstn self.IncomeDstn = [combineIndepDstns(self.IncomeDstn[t],AggShkDstn) for t in range(self.T...
Updates attribute IncomeDstn by combining idiosyncratic shocks with aggregate shocks. Parameters ---------- AggShkDstn : [np.array] Aggregate productivity shock distribution. First element is proba- bilities, second element is agg permanent shocks, third element is ...
345,147
def _after_indentation(res, options=None, fpath=): fname = os.path.basename(fpath) opts = parse_options(options) for msg in res[]: if opts.warning: if opts.files: msg[] = fname sys.stderr.write(.format(**msg)) else: ...
_after_indentation(res : dict): Called after the string has been indented appropriately. It takes care of writing the file and checking for unclosed strings or comments.
345,148
def print_projects(projects=None): grouped_by = {} if not projects: print( "Your selection didnversions'): version_str = ", ".join(prj_cls.versions()) project_id = "{0}/{1}".format(prj_cls.NAME, prj_cls.GROUP) project_str = \ " ...
Print a list of projects registered for that experiment. Args: exp: The experiment to print all projects for.
345,149
def GetUnclaimedCoins(self): unclaimed = [] neo = Blockchain.SystemShare().Hash for coin in self.GetCoins(): if coin.Output.AssetId == neo and \ coin.State & CoinState.Confirmed > 0 and \ coin.State & CoinState.Spent > 0 and \ ...
Gets coins in the wallet that have not been 'claimed', or redeemed for their gas value on the blockchain. Returns: list: a list of ``neo.Wallet.Coin`` that have 'claimable' value
345,150
def visitMembersDef(self, ctx: jsgParser.MembersDefContext): if not self._name: self._name = self._context.anon_id() if ctx.COMMA(): self._strict = False if not ctx.BAR(): self.visitChildren(ctx)...
membersDef: COMMA | member+ (BAR altMemberDef)* (BAR lastComma)? ; altMemberDef: member* ; member: pairDef COMMA? lastComma: COMMA ;
345,151
def open_jar(self, path, overwrite=False, compressed=True, jar_rules=None): jar = Jar(path) try: yield jar except jar.Error as e: raise TaskError(.format(path, e)) with jar._render_jar_tool_args(self.get_options()) as args: if args:
Yields a Jar that will be written when the context exits. :API: public :param string path: the path to the jar file :param bool overwrite: overwrite the file at ``path`` if it exists; ``False`` by default; ie: update the pre-existing jar at ``path`` :param bool compressed: entries added to the j...
345,152
def check_status(self): log = logging.getLogger("%s.%s" % (self.log_name, inspect.stack()[0][3])) log.setLevel(self.log_level) if self.url: return True try: result = requests.get(self.ext_url) self.u...
tests both the ext_url and local_url to see if the database is running returns: True if a connection can be made False if the connection cannot me made
345,153
def _send(self, message): params = { : self.get_username(), : self.get_password(), : self.get_account(), : message.from_phone, : ",".join(message.to), : message.body, : } if ESENDEX_SANDBOX: ...
Private method to send one message. :param SmsMessage message: SmsMessage class instance. :returns: True if message is sent else False :rtype: bool
345,154
def rm(path, isdir=False): if isdir: deleted = os.path.isdir(path) shutil.rmtree(path, ignore_errors=True) elif os.path.isfile(path) or os.path.islink(path): deleted = True os.remove(path) else: deleted = False return deleted
delete file or dir returns True if deleted, if file/dir not exists, return False :param path: path to delete :param isdir: set True if you want to delete dir
345,155
def tordd(self, sc, axis=0): from bolt import array return array(self.toarray(), sc, axis=axis).tordd()
Converts a BoltArrayLocal into an RDD Parameters ---------- sc : SparkContext The SparkContext which will be used to create the BoltArraySpark axis : tuple or int, optional, default=0 The axis (or axes) across which this array will be parallelized Retur...
345,156
def indent(self, node, dirty=True): if node.subitems: return self._subitems[node.id] = node node.super_list_item_id = self.id node.parent_item = self if dirty: node.touch(True)
Indent an item. Does nothing if the target has subitems. Args: node (gkeepapi.node.ListItem): Item to indent. dirty (bool): Whether this node should be marked dirty.
345,157
def _callback(self, handle, event, channel, arg): log.debug("Handle: %s, Event: %s, Channel: %s" % (handle, event, channel)) if event == CbEvent.EVENT_INITHW: self.init_hw_event() elif event == CbEvent.EVENT_init_can: self.init_can_event(channel) elif ev...
Is called if a working event occurred. :param int handle: USB-CAN-Handle returned by the function :meth:`init_hardware`. :param int event: Event type. :param int channel: CAN channel (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ANY`). :...
345,158
def format(): argparser = argparse.ArgumentParser(description=) argparser.add_argument(, metavar=, help=, nargs=) arguments = argparser.parse_args() service_style = "{address:15} {port:7} {protocol:5} {service:15} {state:10} {banner} {tags}" host_style = "{address:15} {tags}" ranges_style =...
Formats the output of another tool in the given way. Has default styles for ranges, hosts and services.
345,159
def read(self, dispatcher): try: if not self.is_header_read: to_read = HeronProtocol.HEADER_SIZE - len(self.header) self.header += dispatcher.recv(to_read) if len(self.header) == HeronProtocol.HEADER_SIZE: self.is_header_read = True else: Log.d...
Reads incoming data from asyncore.dispatcher
345,160
def dump(self): r = {} def _dump_(obj): if isinstance(obj, dict): ret = {} for k, v in six.iteritems(obj): ret[k] = _dump_(v) return None if ret == {} else ret elif isinstance(obj, list): ...
dump Swagger Spec in dict(which can be convert to JSON)
345,161
def authenticationResponse(): a = TpPd(pd=0x5) b = MessageType(mesType=0x14) c = AuthenticationParameterSRES() packet = a / b / c return packet
AUTHENTICATION RESPONSE Section 9.2.3
345,162
def annotate(abf): msg="SWHLab %s "%str(swhlab.VERSION) msg+="ID:%s "%abf.ID msg+="CH:%d "%abf.channel msg+="PROTOCOL:%s "%abf.protoComment msg+="COMMAND: %d%s "%(abf.holding,abf.units) msg+="GENERATED:%s "%.format(datetime.datetime.now()) pylab.annotate(msg,(.001,.001),xycoords=,ha=, ...
stamp the bottom with file info.
345,163
def show(self, filter=None): for command in self._commands: if command[0] is None: continue if filter and command[0] != filter: continue t = [] for e in command: if isinstance(e, np.ndarray): ...
Print the list of commands currently in the queue. If filter is given, print only commands that match the filter.
345,164
def setter_generator(field_name): def set_translation_field(cls, value, language_code=None): setattr(cls.get_translation(language_code, True), field_name, value) set_translation_field.short_description = "set " + field_name return set_translation_field
Generate set_'field name' method for field field_name.
345,165
def get_domain_list(list_name): * payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_domain_names", "params": [list_name, 0, 256]} response = __proxy__[](payload, False) return _convert_to_list(response, )
Retrieves a specific policy domain name list. list_name(str): The name of the specific policy domain name list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_domain_list MyDomainNameList
345,166
def mkdir(path, owner=None, grant_perms=None, deny_perms=None, inheritance=True, reset=False): userpermsbasic_permissionuserpermsfull_controlapplies_tothis_folderuserpermsread_attributesread_eaapplies_tothis_folderUsersread & execute*Userspermsread_executeUsersperms...
Ensure that the directory is available and permissions are set. Args: path (str): The full path to the directory. owner (str): The owner of the directory. If not passed, it will be the account that created the directory, likely SYSTEM grant_perms (dict...
345,167
def doPointsExperiment(cellDimensions, cellCoordinateOffsets): if not os.path.exists("traces"): os.makedirs("traces") locationConfigs = [] for i in xrange(5): scale = 10.0 * (math.sqrt(2) ** i) for _ in xrange(4): orientation = np.radians(random.gauss(7.5, 7.5)) orientation = random.c...
Learn a set of objects. Then try to recognize each object. Output an interactive visualization. @param cellDimensions (pair) The cell dimensions of each module @param cellCoordinateOffsets (sequence) The "cellCoordinateOffsets" parameter for each module
345,168
def define_log_processors(): return [ structlog.processors.TimeStamper(fmt="iso"), _structlog_default_keys_processor, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, ]
log processors that structlog executes before final rendering
345,169
def _load_from_file(path): config = [] try: with open(path, ) as config_file: config = yaml.load(config_file)[] except EnvironmentError as e: raise ConfigError( % e.args[1] if len(e.args) > 1 else e) except (...
Load a config file from the given path. Load all normalizations from the config file received as argument. It expects to find a YAML file with a list of normalizations and arguments under the key 'normalizations'. Args: path: Path to YAML file.
345,170
def muscle_chunker(data, sample): LOGGER.info("inside muscle_chunker") if data.paramsdict["assembly_method"] != "reference": clustfile = os.path.join(data.dirs.clusts, sample.name+".clust.gz") with iter(gzip.open(clustfile, )) as clustio: nloci = sum(1 f...
Splits the muscle alignment into chunks. Each chunk is run on a separate computing core. Because the largest clusters are at the beginning of the clusters file, assigning equal clusters to each file would put all of the large cluster, that take longer to align, near the top. So instead we randomly di...
345,171
def add_classdiff_optgroup(parser): g = parser.add_argument_group("Class Checking Options") g.add_argument("--ignore-version-up", action="store_true", default=False) g.add_argument("--ignore-version-down", action="store_true", default=False) g.add_argument("--ignore-platform-up...
option group specific to class checking
345,172
def blit_rect( self, console: tcod.console.Console, x: int, y: int, width: int, height: int, bg_blend: int, ) -> None: lib.TCOD_image_blit_rect( self.image_c, _console(console), x, y, width, height, bg_blend )
Blit onto a Console without scaling or rotation. Args: console (Console): Blit destination Console. x (int): Console tile X position starting from the left at 0. y (int): Console tile Y position starting from the top at 0. width (int): Use -1 for Image width. ...
345,173
def is_child(child_path, parent_path): parent_dir = os.path.join(parent_path, ) child_dir = os.path.join(child_path, ) return child_dir.startswith(parent_dir)
Is parent_path a parent(or grandparent) directory of child_path. :param child_path: str: remote file path :param parent_path: str: remote file path :return: bool: True when parent_path is child_path's parent
345,174
async def send_mail( self, sender, recipients, message, mail_options=None, rcpt_options=None ): return await self.sendmail( sender, recipients, message, mail_options, rcpt_options )
Alias for :meth:`SMTP.sendmail`.
345,175
def set_name(self, name, create_dir=False): exists = os.path.exists(os.path.join(self._path, name)) self.filepath = os.path.join(self._path, name) if exists is False and create_dir is True: os.makedirs(self.filepath) self.name = name return self.n...
Sets the name of the file to be saved. @params name - the name to the file increment - whether or not to increment the filename if there is an existing file ie test.txt => test1.txt overwrite - whether or not to overwrite existing local file, renders increment redundant
345,176
def intersectingInterval(self, start, end): l = [] for x in self.data.starts: xStartsAfterInterval = (x.start > end and not self.openEnded) or \ (x.start >= end and self.openEnded) xEndsBeforeInterval = (x.end < start and not self.openEnded) or \ ...
given an interval, get intervals in the tree that are intersected. :param start: start of the intersecting interval :param end: end of the intersecting interval :return: the list of intersected intervals
345,177
def _load_nucmer_hits(self, infile): hits = {} lengths = {} file_reader = pymummer.coords_file.reader(infile) for al in file_reader: if al.qry_name == al.ref_name: continue elif al.qry_name not in hits: hits[al.qry_name] = ...
Returns two dictionaries: 1) name=>contig length. 2) Second is dictionary of nucmer hits (ignoring self matches). contig name => list of hits
345,178
def confd_state_smp_number_of_threads(self, **kwargs): config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") smp = ET.SubElement(confd_state, "smp") number_of_threads = ET.SubElement(smp, "number-of-thre...
Auto Generated Code
345,179
def get_source_class(self, _class): if not _class.get_name() in self.classes: return "" return self.classes[_class.get_name()]
Return the Java source code of a whole class :param _class: `ClassDefItem` object, to get the source from :return:
345,180
def addcert(self, cert): if libcrypto.CMS_add1_cert(self.ptr, cert.cert) <= 0: raise CMSError("Cannot add cert")
Adds a certificate (probably intermediate CA) to the SignedData structure
345,181
def _basename(fname): if not isinstance(fname, Path): fname = Path(fname) path, name, ext = fname.parent, fname.stem, fname.suffix return path, name, ext
Return file name without path.
345,182
def call(self, this, args=()): if not hasattr(args, ): args = (args, ) args = tuple(Js(e) for e in args) arguments = PyJsArguments( args, self) arglen = self.argcount if len(args) > arglen: args = args[0:arglen] elif l...
Calls this function and returns a result (converted to PyJs type so func can return python types) this must be a PyJs object and args must be a python tuple of PyJs objects. arguments object is passed automatically and will be equal to Js(args) (tuple converted to arguments object).You...
345,183
def cli(env, sortby): manager = SoftLayer.CDNManager(env.client) accounts = manager.list_accounts() table = formatting.Table([, , , , ]) for account in accounts: table.a...
List all CDN accounts.
345,184
def get_common_secret(self, server_public, client_public): return self.hash(self.pad(client_public), self.pad(server_public))
u = H(PAD(A) | PAD(B)) :param int server_public: :param int client_public: :rtype: int
345,185
def _parse_fields_dns(self, *args, **kwargs): from warnings import warn warn( ) return self.parse_fields_dns(*args, **kwargs)
Deprecated. This will be removed in a future release.
345,186
def check_executables(): print("\033[1mCheck executables\033[0m") required_executables = [utils.get_nntoolkit()] for executable in required_executables: path = which(executable) if path is None: print("%s ... %sNOT%s found" % (executable, Bcolors.WARNING, ...
Check if all necessary / recommended executables are installed.
345,187
def save_file(f, full_path): make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, ) as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) ...
Saves file f to full_path and set rules.
345,188
def configure_swagger(graph): ns = Namespace( subject=graph.config.swagger_convention.name, version=graph.config.swagger_convention.version, ) convention = SwaggerConvention(graph) convention.configure(ns, discover=tuple()) return ns.subject
Build a singleton endpoint that provides swagger definitions for all operations.
345,189
def parse_bulk_create(prs, conn): prs_create = prs.add_parser( , help=) set_option(prs_create, ) conn_options(prs_create, conn) prs_create.add_argument(, action=, help=) prs_create.set_defaults(func=create)
Create bulk_records. Arguments: prs: parser object of argparse conn: dictionary of connection information
345,190
def stats(self, filter, limit, start=None): return links, stats
Get stats about links. Parameters: filter: 'top', 'bottom', 'rand', or 'last'. limit: Number of links to return from filter. start: Optional start number. Returns: Tuple containing list of ShortenedURLs and DBStats. Example: .. code...
345,191
def outgoing_edges(self, node): edges = self.edges() out_edges = [] for out_node, in_node in edges: if node is out_node: out_edges.append((out_node, in_node)) return tuple(out_edges)
Returns a ``tuple`` of outgoing edges for a **node object**. Arguments: - node(``object``) **node object** present in the graph to be queried for outgoing edges.
345,192
def open(path, vcs=None): import os assert os.path.isdir(path), path + vcs = vcs or probe(path) cls = _get_repo_class(vcs) return cls(path)
Open an existing repository :param str path: The path of the repository :param vcs: If specified, assume the given repository type to avoid auto-detection. Either ``git``, ``hg``, or ``svn``. :raises UnknownVCSType: if the repository type couldn't be inferred If ``vcs`` is not specifie...
345,193
def parse_url(self): url = urlparse(self.url).path url = url.split()[0] if in url: url = url.split()[1] try: project, repo = url.split()[-2:] except ValueError: raise ParserError(.format(self.url)) return...
Parse a git/ssh/http(s) url.
345,194
def EnumerateInterfacesFromClient(args): del args libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) ifa = Ifaddrs() p_ifa = ctypes.pointer(ifa) libc.getifaddrs(ctypes.pointer(p_ifa)) addresses = {} macs = {} ifs = set() m = p_ifa while m: ifname = ctypes.string_at(m.contents....
Enumerate all interfaces and collect their MAC addresses.
345,195
def diff(path_from, path_to, ignore_empty = False): fh_from = open(path_from, ) fh_to = open(path_to, ) diffs = file_diff(fh_from, fh_to, ignore_empty) fh_to.close() fh_from.close() return diffs
Compare two whisper databases. Each file must have the same archive configuration
345,196
def parse_docstring(docstring): fulldeps ret = {: docstring} regex = r match = re.search(regex, docstring, re.M) if match: deps = [] regex = r for line in match.group(0).strip().splitlines(): deps.append(re.search(regex, line).group(1)) ret[] = deps ...
Parse a docstring into its parts. Currently only parses dependencies, can be extended to parse whatever is needed. Parses into a dictionary: { 'full': full docstring, 'deps': list of dependencies (empty list if none) }
345,197
def close(self, force=False) -> None: self.fp.close = self._close if self._manual_opened or force: self.fp.close()
Closes the file if the file was opened by :class:`File`, if not, this does nothing. Parameters ---------- force: bool If set to :class:`True`, force close every file.
345,198
def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile: def ConfigFileGenerator(filename, safe_load: bool=True): cfg = ConfigFile(fd=filename, load_hook=load_hook, dump_hook=dump_hook, safe_load=safe_load, **kwargs) return cfg return ConfigFileGenerator
Generates a ConfigFile object using the specified hooks. These hooks should be functions, and have one argument. When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or request, or whatever. This returns a ConfigFile object.
345,199
def splinefit2d(x, y, z, px, py, mask=None): if mask is None: V = np.array(spline_matrix2d(x, y, px, py)) a = np.array(z.T.flatten()) pz = np.linalg.lstsq(V.T, a.T)[0].T else: V = np.array(spline_matrix2d(x,y,px,py,mask)) indices = np.nonzero(np.array(mask).T.fl...
Make a least squares fit of the spline (px,py,pz) to the surface (x,y,z). If mask is given, only masked points are used for the regression.