text
stringlengths
78
104k
score
float64
0
0.18
def inserir(self, name): """Insert new network type and return its identifier. :param name: Network type name. :return: Following dictionary: {'net_type': {'id': < id >}} :raise InvalidParameterError: Network type is none or invalid. :raise NomeTipoRedeDuplicadoError: A networ...
0.004184
def save(self, commit=True): ''' If the staff member is an instructor, also update the availableForPrivates field on the Instructor record. ''' if getattr(self.instance,'instructor',None): self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.insta...
0.01992
def print_tree(task, indent='', last=True): ''' Return a string representation of the tasks, their statuses/parameters in a dependency tree format ''' # dont bother printing out warnings about tasks with no output with warnings.catch_warnings(): warnings.filterwarnings(action='ignore', messa...
0.00391
def perform_permissions_check(self, user, obj, perms): """ Performs the permission check. """ return self.request.forum_permission_handler.can_vote_in_poll(obj, user)
0.016484
def reply(self): """ Captures reply message within email """ reply = [] for f in self.fragments: if not (f.hidden or f.quoted): reply.append(f.content) return '\n'.join(reply)
0.00823
def img2img_transformer_base(): """Base params for local1d attention.""" hparams = image_transformer2d_base() # learning related flags hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" # This version seems to benefit from a higher learning rate. hparams.learning_rate = 0.2 ...
0.026786
def from_file(cls, path, fields=None, encoding='utf-8'): """ Instantiate a Table from a database file. This method instantiates a table attached to the file at *path*. The file will be opened and traversed to determine the number of records, but the contents will not be stored i...
0.002242
def _sample(rng, arr, k): """ Equivalent to: random.sample(arr, k) except it uses our random number generator. """ selected = numpy.empty(k, dtype="uint32") rng.sample(numpy.asarray(arr, dtype="uint32"), selected) return selected
0.019231
def assign_issue(self, issue, assignee): """Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. :param issue: the issue ID or key to assign :type issue: int or str :param assignee: the user to assign the issue to :type assignee: str :...
0.004942
def document_to_text(filename: str = None, blob: bytes = None, extension: str = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: """ Converts a document to text. This function selects a processor based on the file extension (either...
0.000527
def remove_escalation_policy(self, escalation_policy, **kwargs): """Remove an escalation policy from this team.""" if isinstance(escalation_policy, Entity): escalation_policy = escalation_policy['id'] assert isinstance(escalation_policy, six.string_types) endpoint = '{0}/{1...
0.00381
def set_args(self, **kwargs): """ Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value """ try: kwargs_items = kwargs.iteritems() except AttributeError: kwargs_items = kwargs...
0.005013
def parse_safari (url_data): """Parse a Safari bookmark file.""" from ..bookmarks.safari import parse_bookmark_data for url, name in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, name=name)
0.008696
def get_git_branch(git_path='git'): """Returns the name of the current git branch """ branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD')) if branch_match == "HEAD": return None else: return os.path.basename(branch_match)
0.007117
def get_config(jid): """Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS. If the JID does not match any rule, ``False`` is returned. """ acls = getattr(settings, 'XMPP_HTTP_UPLOAD_ACCESS', (('.*', False), )) for regex, config in acls: if isinstance(regex, six.strin...
0.004237
def get_keys(self, keymap): """Extract keys pressed from transformed keymap""" keys = dict(modifiers=[], regular=[]) # loop on keymap bytes for keymap_index, keymap_byte in enumerate(keymap): try: keymap_values = self._keymap_values_dict[keymap_index] ...
0.002632
def _convert_option(self): ''' Determines which symbol to use for numpy conversions > : a little endian system to big endian ordering < : a big endian system to little endian ordering = : No conversion ''' data_endian = 'little' if (self._encoding == 1 or ...
0.004662
def wait_for_zone_op(access_token, project, zone, name, interval=1.0): """Wait until a zone operation is finished. TODO: docstring""" assert isinstance(interval, (int, float)) assert interval >= 0.1 status = 'RUNNING' progress = 0 LOGGER.info('Waiting for zone operation "%s" to finis...
0.003175
def serve(application, host='127.0.0.1', port=8080): """CherryPy-based WSGI-HTTP server.""" # Instantiate the server with our configuration and application. server = CherryPyWSGIServer((host, int(port)), application, server_name=host) # Try to be handy as many terminals allow clicking links. print("serving on ...
0.035124
def on_click(self, button, **kwargs): """ Maps a click event with its associated callback. Currently implemented events are: ============ ================ ========= Event Callback setting Button ID ============ ================ ========= Left click ...
0.000808
def edit_multireddit(self, *args, **kwargs): """Edit a multireddit, or create one if it doesn't already exist. See :meth:`create_multireddit` for accepted parameters. """ return self.create_multireddit(*args, overwrite=True, **kwargs)
0.007463
def SetGeoTransform(self, affine): """Sets the affine transformation. Intercepts the gdal.Dataset call to ensure use as a property setter. Arguments: affine -- AffineTransform or six-tuple of geotransformation values """ if isinstance(affine, collections.Sequence): ...
0.00464
def set_secondary_channel(self, source, channel_list): """ General purpose method for setting a secondary channel This method allows a given source channel to be forked into one or more channels and sets those forks in the :py:attr:`Process.forks` attribute. Both the source and the chan...
0.000873
def brozzler_list_captures(argv=None): ''' Handy utility for looking up entries in the rethinkdb "captures" table by url or sha1. ''' import urlcanon argv = argv or sys.argv arg_parser = argparse.ArgumentParser( prog=os.path.basename(argv[0]), formatter_class=BetterA...
0.000699
def sendConnect(self, data): """Send a CONNECT command to the broker :param data: List of other broker main socket URL""" # Imported dynamically - Not used if only one broker if self.backend == 'ZMQ': import zmq self.context = zmq.Context() self.so...
0.002448
def load_state_machine_from_path(base_path, state_machine_id=None): """Loads a state machine from the given path :param base_path: An optional base path for the state machine. :return: a tuple of the loaded container state, the version of the state and the creation time :raises ValueError: if the provi...
0.005168
def parse(self, sentence): """Parse the sentence Param: sentence (str) Return: result (list of dict) """ self.asa.stdin.write(sentence.encode(self.encoding) + b'\n') self.asa.stdin.flush() result = [] while not result: w...
0.002967
def handle(self, path, method='GET'): """ (deprecated) Execute the first matching route callback and return the result. :exc:`HTTPResponse` exceptions are catched and returned. If :attr:`Bottle.catchall` is true, other exceptions are catched as well and returned as :exc:`HTTP...
0.006814
def flush_pending(function): """Attempt to acquire any pending locks. """ s = boto3.Session() client = s.client('lambda') results = client.invoke( FunctionName=function, Payload=json.dumps({'detail-type': 'Scheduled Event'}) ) content = results.pop('Payload').read() pprin...
0.00266
def publish(self): ''' Perform HTTP session to transmit defined weather values. ''' return self._publish( self.args, self.server, self.URI)
0.030675
def secondaries(self): """return list of secondaries members""" return [ { "_id": self.host2id(member), "host": member, "server_id": self._servers.host_to_server_id(member) } for member in self.get_members_in_state(2) ...
0.006116
def is_valid_categorical_partition_object(partition_object): """Tests whether a given object is a valid categorical partition object. :param partition_object: The partition_object to evaluate :return: Boolean """ if partition_object is None or ("weights" not in partition_object) or ("values" not in ...
0.004847
def raw_partlist(input, timeout=20, showgui=False): '''export partlist by eagle, then return it :param input: .sch or .brd file name :param timeout: int :param showgui: Bool, True -> do not hide eagle GUI :rtype: string ''' output = tempfile.NamedTemporaryFile( prefix='eagexp_', su...
0.001883
def add_style_opts(cls, component, new_options, backend=None): """ Given a component such as an Element (e.g. Image, Curve) or a container (e.g Layout) specify new style options to be accepted by the corresponding plotting class. Note: This is supplied for advanced users who kno...
0.005542
def fetch_items(self, category, **kwargs): """Fetch the issues :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Fetching issues of '%s' distribution ...
0.003431
def assemble( iterable, patterns=None, minimum_items=2, case_sensitive=True, assume_padded_when_ambiguous=False ): '''Assemble items in *iterable* into discreet collections. *patterns* may be specified as a list of regular expressions to limit the returned collection possibilities. Use this when in...
0.000442
def write(self, oprot): ''' Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail.OnlineDatabaseObjectDetail ''' oprot.write_str...
0.002297
def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar): """ Returns the incremental rate of earthquakes with M = mag_value """ delta_m = mmax - mag_value dirac_term = np.zeros_like(mag_value) dirac_term[np.fabs(delta_m) < 1.0E-12] = 1.0 a_1 = self._...
0.004348
def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid,...
0.0013
def tokenize_conf_stream(conf_handle): """ convert the key=val pairs in a LSF config stream to tuples of tokens """ for line in conf_handle: if line.startswith("#"): continue tokens = line.split("=") if len(tokens) != 2: continue yield (tokens[0].s...
0.00289
def Nu_vertical_cylinder_Griffiths_Davis_Morgan(Pr, Gr, turbulent=None): r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < R...
0.001985
def validate_config_json(pjson): """Takes the parsed JSON (output from json.load) from a configuration file and checks it for common errors.""" # Make sure that the root json is a dict if type(pjson) is not dict: raise ParseError("Configuration file should contain a single J...
0.008286
def download_file(url, local_filename): """ Simple wrapper around urlretrieve that uses tqdm to display a progress bar of download progress """ local_filename = os.path.abspath(local_filename) path = os.path.dirname(local_filename) if not os.path.isdir(path): os.makedirs(path) with tqdm...
0.001832
def needs_high_priority(self, priority): """ :return: None """ assert isinstance(priority, int) if priority != velbus.HIGH_PRIORITY: self.parser_error("needs high priority set")
0.008511
def _verify_install(desired, new_pkgs, ignore_epoch=False, new_caps=None): ''' Determine whether or not the installed packages match what was requested in the SLS file. ''' ok = [] failed = [] if not new_caps: new_caps = dict() for pkgname, pkgver in desired.items(): # Fr...
0.001124
def client_setname(self, name): """Set the current connection name.""" fut = self.execute(b'CLIENT', b'SETNAME', name) return wait_ok(fut)
0.012346
def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice): """Return the number of orifices.""" #Inputs do not need to be checked here because they are checked by #functions this function calls. return np.ceil(area_orifice(HeadLossOrifice, RatioVCOrifice, ...
0.012531
def format(self): """Handles the actual behaviour involved with formatting. To change the behaviour, this method should be overridden. Returns -------- list A paginated output of the help command. """ values = {} title = "Description" ...
0.003763
def get_ordered_feature_list(info_object, feature_list): """ Orders the passed feature list by the given, json-formatted feature dependency file using feaquencer's topsort algorithm. :param feature_list: :param info_object: :return: """ feature_dependencies = json.load(open(info_object.f...
0.005952
def RunValidationOutputToConsole(feed, options): """Validate feed, print reports and return an exit code.""" accumulator = CountingConsoleProblemAccumulator( options.error_types_ignore_list) problems = transitfeed.ProblemReporter(accumulator) _, exit_code = RunValidation(feed, options, problems) return ...
0.018237
def modify_postquery_parts(self, postquery_parts): """ Make the comparison recipe a subquery that is left joined to the base recipe using dimensions that are shared between the recipes. Hoist the metric from the comparison recipe up to the base query while adding the suffix. ...
0.000578
def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: T...
0.000775
def abort_job(self, job_id): """ Abort an existing job. When a job is aborted, no more records are processed. Changes to data may already have been committed and aren't rolled back. :param job_id: job_id as returned by 'create_operation_job(...)' :return: abort response as xml ...
0.005051
def _validate_ip_address(family, address): """Check if `address` is valid IP address and return it, in a normalized form. :Parameters: - `family`: ``socket.AF_INET`` or ``socket.AF_INET6`` - `address`: the IP address to validate """ try: info = socket.getaddrinfo(address, 0,...
0.002045
def find_hal(self, atoms): """Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S)""" data = namedtuple('hal_acceptor', 'o o_orig_idx y y_orig_idx') a_set = [] # All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur for a in [at for at in ato...
0.008353
def getSpec(cls): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`. """ ns = dict( description=KNNAnomalyClassifierRegion.__doc__, singleNodeOnly=True, inputs=dict( spBottomUpOut=dict( description="""The output signal generated from the...
0.004058
def activation_key_expired(self): """ Determine whether this ``RegistrationProfile``'s activation key has expired, returning a boolean -- ``True`` if the key has expired. Key expiration is determined by a two-step process: 1. If the user has already activated, the key wil...
0.002392
def split_first(s, delims): """ Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', '...
0.002361
def log_entry_generator(log_instance): """ :yield: The next LogEntry from the REST API :raise: StopIteration when there are no more log entries to show, please note that if you call this again at a later time the REST API could have different results and more data could be returned ...
0.001667
def _delete_record(self, identifier=None, rtype=None, name=None, content=None): """ Delete record(s) matching the provided params. If there is no match, do nothing. """ ids = [] if identifier: ids.append(identifier) elif not identifier and rtype and n...
0.003663
def source_table(self): """Source table (`~astropy.table.Table`). Columns: GLON, GLAT, COUNTS """ url = 'https://github.com/gammapy/gammapy-extra/raw/master/datasets/fermi_2fhl/gll_psch_v08.fit.gz' table = Table.read(url, hdu='2FHL Source Catalog') table.rename_column('...
0.006818
def slip_list(nodes): """ :param nodes: a slipList node with N slip nodes :returns: a numpy array of shape (N, 2) with slip angle and weight """ check_weights(nodes) data = [] for node in nodes: data.append([slip_range(~node), node['weight']]) return numpy.array(data, float)
0.003175
def create(self): """ creates an empty configuration file """ if not self.exists(): # create new empyt config file based on template self.config.add_section("lametric") self.config.set("lametric", "client_id", "") self.config.set("lametric"...
0.002928
def changelog(**kwargs): """ Generates the changelog since the last release. :raises ImproperConfigurationError: if there is no current version """ current_version = get_current_version() debug('changelog got current_version', current_version) if current_version is None: raise Impro...
0.001505
def add_reader( self, fd: IFileLike, callback: typing.Callable[[IFileLike], typing.Any], ) -> None: """Add a file descriptor to the processor and wait for READ. Args: fd (IFileLike): Any obect that exposes a 'fileno' method that return...
0.005181
def loghandler_members(): """iterate through the attributes of every logger's handler this is used to switch out stderr and stdout in tests when buffer is True :returns: generator of tuples, each tuple has (name, handler, member_name, member_val) """ Members = namedtuple("Members", ["name", "handl...
0.00454
async def get_hassio_version(self): """Get version published for hassio.""" if self.image not in IMAGES: _LOGGER.warning("%s is not a valid image using default", self.image) self.image = "default" board = BOARDS.get(self.image, BOARDS["default"]) self._version_d...
0.00462
def hwvtep_add_rbridgeid(self, **kwargs): """ Add a range of rbridge-ids Args: name (str): gateway-name vlan (str): rbridge-ids range callback (function): A function executed upon completion of the method. Returns: Return...
0.002621
def get_value(self, series, key): """ we always want to get an index value, never a value """ if not is_scalar(key): raise InvalidIndexError k = com.values_from_object(key) loc = self.get_loc(k) new_values = com.values_from_object(series)[loc] return new_val...
0.006192
def update_group_name(self, group_id, body, **kwargs): # noqa: E501 """Update the group name. # noqa: E501 An endpoint for updating a group name. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -d '{\"name\": \"TestGroup2\"}' -H 'content-type: applica...
0.001546
def save_policy(self, path): """Pickles the current policy for later inspection. """ with open(path, 'wb') as f: pickle.dump(self.policy, f)
0.011364
def optimize(exp_rets, covs): """ Return parameters for portfolio optimization. Parameters ---------- exp_rets : ndarray Vector of expected returns for each investment.. covs : ndarray Covariance matrix for the given investments. Returns --------- a : ndarray ...
0.001509
def _extract_values(values_list): """extract values from either file or list :param values_list: list or file name (str) with list of values """ values = [] # check if file or list of values to iterate if isinstance(values_list, str): with open(values_list) a...
0.003257
def pipeline_absent(name): ''' Ensure that the named pipeline is absent name Name of the pipeline to remove ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} try: pipeline = __salt__['elasticsearch.pipeline_get'](id=name) if pipeline and name in pi...
0.003506
def edit(id: int, parent: int, alloc: Decimal): """ Edit asset class """ saved = False # load app = AppAggregate() item = app.get(id) if not item: raise KeyError("Asset Class with id %s not found.", id) if parent: assert parent != id, "Parent can not be set to self." ...
0.001406
def get_template_name(self, template_name_suffix=None): """ Generates a template path name based on model and app. :param template_name_suffix: pass a custom suffix or leave empty for default :return: template path """ if isinstance(self.object, models.Model): ...
0.007585
def _update_repo(repo_config, store, tags_only): """Updates a repository to the tip of `master`. If the repository cannot be updated because a hook that is configured does not exist in `master`, this raises a RepositoryCannotBeUpdatedError Args: repo_config - A config for a repository """ ...
0.000588
def plot(self): """ Plots reaction energy as a function of mixing ratio x in self.c1 - self.c2 tie line using pylab. Returns: Pylab object that plots reaction energy as a function of mixing ratio x. """ plt.rcParams['xtick.major.pad'] = '6' ...
0.001086
def count(self, *criterion, **kwargs): """ Count the number of models matching some criterion. """ query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
0.008403
def digest(self): """Terminate the message-digest computation and return digest. Return the digest of the strings passed to the update() method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes. """ A = self.A ...
0.006494
def delete_page_full(id): """Delete a page from Confluence, along with its children. Parameters: - id: id of a Confluence page. Notes: - Getting a 204 error is expected! It means the page can no longer be found. """ children = _json.loads(get_page_children(id)) for i in children["resul...
0.005168
def get_cytoBand_hg19(self): """ Get UCSC cytoBand table for Build 37. Returns ------- pandas.DataFrame cytoBand table if loading was successful, else None """ if self._cytoBand_hg19 is None: self._cytoBand_hg19 = self._load_cytoBand(self._get_pat...
0.008021
def from_api_repr(cls, resource): """Factory: construct a table given its API representation Args: resource (Dict[str, object]): Table resource representation from the API Returns: google.cloud.bigquery.table.Table: Table parsed from ``resource``. ...
0.001552
def background_mean(self): """ The mean of ``background`` values within the source segment. Pixel values that are masked in the input ``data``, including any non-finite pixel values (i.e. NaN, infs) that are automatically masked, are also masked in the background array. ...
0.003378
def _list(api_list_class, arg_namespace, **extra): """ A common function for building methods of the "list showing". """ if arg_namespace.starting_point: ordering_field = (arg_namespace.ordering or '').lstrip('-') if ordering_field in ('', 'datetime_uploaded', 'datetime_created'): ...
0.001312
def _captcha_form(self): """ captcha form :return: """ try: last_attempt = FailedAccessAttempt.objects.get( ip_address=self._ip, is_locked=True, captcha_enabled=True, is_expired=False ) ...
0.003927
def get_options(): """Collect all the options info from the other modules.""" options = collections.defaultdict(list) for opt_class in config_factory.get_options(): if not issubclass(opt_class, config_base.Options): continue config_options = opt_class(None) options[config...
0.002326
def __geometryListToGeomTemplate(self, geometries): """ converts a list of common.Geometry objects to the geometry template value Input: geometries - list of common.Geometry objects Output: Dictionary in geometry service template ...
0.002301
def run_python_module(modulename, args): """Run a python module, as though with ``python -m name args...``. `modulename` is the name of the module, possibly a dot-separated name. `args` is the argument array to present as sys.argv, including the first element naming the module being executed. """ ...
0.000499
def value(dtype, arg): """Validates that the given argument is a Value with a particular datatype Parameters ---------- dtype : DataType subclass or DataType instance arg : python literal or an ibis expression If a python literal is given the validator tries to coerce it to an ibis lite...
0.000699
def _invariant(self, rank, n): """Computes the delta value for the sample.""" minimum = n + 1 for i in self._invariants: delta = i._delta(rank, n) if delta < minimum: minimum = delta return math.floor(minimum)
0.007067
def gen_files(path, prefix="_"): " Return file generator " if op.isdir(path): for name in listdir(path): fpath = op.join(path, name) if is_parsed_file(fpath): yield op.abspath(fpath) elif is_parsed_file(path): yield op.abspath(path)
0.003311
def getfirstmatchingheader(self, name): """Get the first header line matching name. This is similar to getallmatchingheaders, but it returns only the first matching header (and its continuation lines). """ name = name.lower() + ':' n = len(name) lst = [] ...
0.003396
def submit_order(id_or_ins, amount, side, price=None, position_effect=None): """ 通用下单函数,策略可以通过该函数自由选择参数下单。 :param id_or_ins: 下单标的物 :type id_or_ins: :class:`~Instrument` object | `str` :param float amount: 下单量,需为正数 :param side: 多空方向,多(SIDE.BUY)或空(SIDE.SELL) :type side: :class:`~SIDE` enum ...
0.002783
def _set_session_cookie(self): """Set the session data cookie.""" LOGGER.debug('Setting session cookie for %s', self.session.id) self.set_secure_cookie(name=self._session_cookie_name, value=self.session.id, expires=self._cookie_expira...
0.006154
def round_geom(geom, precision=None): """Round coordinates of a geometric object to given precision.""" if geom['type'] == 'Point': x, y = geom['coordinates'] xp, yp = [x], [y] if precision is not None: xp = [round(v, precision) for v in xp] yp = [round(v, precisi...
0.000645
def _submarine_2d_nonsmooth(space): """Return a 2d nonsmooth 'submarine' phantom.""" def ellipse(x): """Characteristic function of an ellipse. If ``space.domain`` is a rectangle ``[0, 1] x [0, 1]``, the ellipse is centered at ``(0.6, 0.3)`` and has half-axes ``(0.4, 0.14)``. Fo...
0.000664
def _read_string(self, cpu, buf): """ Reads a null terminated concrete buffer form memory :todo: FIX. move to cpu or memory """ filename = "" for i in range(0, 1024): c = Operators.CHR(cpu.read_int(buf + i, 8)) if c == '\x00': break...
0.005405
def isstrallowed(s,form): """ Checks is input string conforms to input regex (`form`). :param s: input string. :param form: eg. for hdf5: `"^[a-zA-Z_][a-zA-Z0-9_]*$"` """ import re match = re.match(form,s) return match is not None
0.011407
def path(self): """ Absolute path to the directory on the camera's filesystem. """ if self.parent is None: return "/" else: return os.path.join(self.parent.path, self.name)
0.009091