code
stringlengths
1
18.2k
def getEdge(self, _id): """Retrieves an existing edge from the graph @params _id: Edge unique identifier @returns The requested Edge or None""" try: edge = self.neograph.relationships.get(_id) except client.NotFoundError: return None return Edge(edge)
def getOutEdges(self, label=None): """Gets all the outgoing edges of the node. If label parameter is provided, it only returns the edges of the given label @params label: Optional parameter to filter the edges @returns A generator function with the outgoing edges""" if label: for edge in self.neoelement.relationships.o...
def getInEdges(self, label=None): """Gets all the incoming edges of the node. If label parameter is provided, it only returns the edges of the given label @params label: Optional parameter to filter the edges @returns A generator function with the incoming edges""" if label: for edge in self.neoelement.relationships.in...
def getBothEdges(self, label=None): """Gets all the edges of the node. If label parameter is provided, it only returns the edges of the given label @params label: Optional parameter to filter the edges @returns A generator function with the incoming edges""" if label: for edge in self.neoelement.relationships.all(types...
def put(self, key, value, element): """Puts an element in an index under a given key-value pair @params key: Index key string @params value: Index value string @params element: Vertex or Edge element to be indexed""" self.neoindex[key][value] = element.neoelement
def get(self, key, value): """Gets an element from an index under a given key-value pair @params key: Index key string @params value: Index value string @returns A generator of Vertex or Edge objects""" for element in self.neoindex[key][value]: if self.indexClass == "vertex": yield Vertex(element) elif self.indexClass ...
def remove(self, key, value, element): """Removes an element from an index under a given key-value pair @params key: Index key string @params value: Index value string @params element: Vertex or Edge element to be removed""" self.neoindex.delete(key, value, element.neoelement)
def createManualIndex(self, indexName, indexClass): """Creates an index manually managed @params name: The index name @params indexClass: vertex or edge @returns The created Index""" indexClass = str(indexClass).lower() if indexClass == "vertex": index = self.neograph.nodes.indexes.create(indexName) elif indexClass == ...
def getIndex(self, indexName, indexClass): """Retrieves an index with a given index name and class @params indexName: The index name @params indexClass: vertex or edge @return The Index object or None""" if indexClass == "vertex": try: return Index(indexName, indexClass, "manual", self.neograph.nodes.indexes.get(indexN...
def getIndices(self): """Returns a generator function over all the existing indexes @returns A generator function over all rhe Index objects""" for indexName in self.neograph.nodes.indexes.keys(): indexObject = self.neograph.nodes.indexes.get(indexName) yield Index(indexName, "vertex", "manual", indexObject) for indexN...
def get_info(self, location): """Returns (url, revision), where both are strings""" assert not location.rstrip('/').endswith(self.dirname), 'Bad directory: %s' % location output = call_subprocess( [self.cmd, 'info', location], show_stdout=False, extra_environ={'LANG': 'C'}) match = _svn_url_re.search(output) if not mat...
def export(self, location): """Export the svn repository at the url to the destination location""" url, rev = self.get_url_rev() logger.notify('Exporting svn repository %s to %s' % (url, location)) logger.indent += 2 try: if os.path.exists(location): # Subversion doesn't like to check out over an existing directory # -...
def get_revision(self, location): """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, files in os.walk(location): if self.dirname not in dirs: dirs[:] = [] continue # no sense walking uncontrolled subdirs dirs.remove(self.d...
max(revs) else: localrev = 0 else: logger.warn("Unrecognized .svn/entries format; skipping %s", base) dirs[:] = [] continue if base == location: base_url = dirurl+'/' # save the root url elif not dirurl.startswith(base_url): dirs[:] = [] continue # not part of the same svn tree, skip it revision = max(revision, localre...
async def main(): """ Main code (asynchronous requests) You can send one millions request with aiohttp : https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html But don't do that on one server, it's DDOS ! """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT...
def word(self): """Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or string representations) of DigitModel. The property is called during instantiation as the property validates the value passed and ensures that all digits are valid.""" if self.wordtype == DigitWord.DIGIT: return ...
def word(self, value): """Property of the DigitWord returning (or setting) the DigitWord as a list of integers (or string representations) of DigitModel. The property is called during instantiation as the property validates the value passed and ensures that all digits are valid. The values can be passed as ANY iterable...
we need to convert unicode to string, otherwise # we leave it as is. if sys.version_info[0] == 2 and isinstance(a, unicode): _a = str(a) else: _a = a # Create the correct type of Digit based on the wordtype of the DigitWord if self.wordtype == DigitWord.DIGIT: _digit = Digit(_a) elif self.wordtype == DigitWord.HEXDIGIT...
def load(self, value): """Load the value of the DigitWord from a JSON representation of a list. The representation is validated to be a string and the encoded data a list. The list is then validated to ensure each digit is a valid digit""" if not isinstance(value, str): raise TypeError('Expected JSON string') _value = ...
def random(self, length=4): """Method to randomize the DigitWord to a given length; for example obj.random(length=4) would produce a DigitWord containing of four random Digits or HexDigits. The type of digit created is set by the wordtype.""" if not isinstance(length, int): raise TypeError('DigitWord can only be random...
def compare(self, other): """Compare the DigitWord with another DigitWord (other) and provided iterated analysis of the matches (none or loose) and the occurrence (one or more) of each DigitEntry in both DigitWords. The method returns a list of Comparison objects.""" self._validate_compare_parameters(other=other) retur...
def _build_package_finder(self, options, index_urls): """ Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly. """ return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_mirrors=options.use_mirrors, mirrors=options...
def sort(amend: bool = False, stage: bool = False): """ Runs iSort (https://pypi.python.org/pypi/isort) Args: amend: whether or not to commit results stage: whether or not to stage changes """ _sort(amend, stage)
def get(self, *args, **kwargs): """Sends a GET request to a reddit path determined by ``args``. Basically ``.get('foo', 'bar', 'baz')`` will GET http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to :meth:`requests.get` after having ``user_agent`` and ``cookies`` injected. Injection only occurs...
def post(self, *args, **kwargs): """Sends a POST request to a reddit path determined by ``args``. Basically ``.post('foo', 'bar', 'baz')`` will POST http://www.reddit.com/foo/bar/baz/.json. ``kwargs`` supplied will be passed to ``requests.post`` after having ``modhash`` and ``cookies`` injected, and after having modhas...
try: errors = j['json']['errors'] except Exception: errors = None if errors: raise PostError(errors) else: return j else: raise BadResponse(r)
def login(self, username, password): """Logs into reddit with supplied credentials using SSL. Returns :class:`requests.Response` object, or raises :class:`exceptions.LoginFail` or :class:`exceptions.BadResponse` if not a 200 response. URL: ``https://ssl.reddit.com/api/login`` :param username: reddit username :param pas...
def info(self, url, limit=None): """GETs "info" about ``url``. See https://github.com/reddit/reddit/wiki/API%3A-info.json. URL: ``http://www.reddit.com/api/info/?url=<url>`` :param url: url :param limit: max number of links to get """ return self._limit_get('api', 'info', params=dict(url=url), limit=limit)
def search(self, query, limit=None): """Use reddit's search function. Returns :class:`things.Listing` object. URL: ``http://www.reddit.com/search/?q=<query>&limit=<limit>`` :param query: query string :param limit: max number of results to get """ return self._limit_get('search', params=dict(q=query), limit=limit)
def moderators(self, sr, limit=None): """GETs moderators of subreddit ``sr``. Returns :class:`things.ListBlob` object. **NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info on each moderator, you must ...
def vote(self, id_, dir_): """Login required. POSTs a vote. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. See https://github.com/reddit/reddit/wiki/API%3A-vote. URL: ``http://www.reddit.com/api/vote/`` :param id\_: full id of object voting on :param dir\_: direction of...
def comment(self, parent, text): """Login required. POSTs a comment in response to ``parent``. Returns :class:`things.Comment` object. See https://github.com/reddit/reddit/wiki/API%3A-comment. URL: ``http://www.reddit.com/api/comment/`` :param parent: full id of thing commenting on :param text: comment text """ data = ...
def edit(self, id_, text): """Login required. Sends POST to change selftext or comment text to ``text``. Returns :class:`things.Comment` or :class:`things.Link` object depending on what's being edited. Raises :class:`UnexpectedResponse` if neither is returned. URL: ``http://www.reddit.com/api/editusertext/`` :param id\...
def submit_link(self, sr, title, url, follow=True): """Login required. POSTs a link submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In o...
def submit_text(self, sr, title, text, follow=True): """Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In ...
def message(self, to, subject, text): """Alias for :meth:`compose`.""" return self.compose(to, subject, text)
def compose(self, to, subject, text): """Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/compose/`` :param to: username or :class`things.Account` of user to send to :param subject: s...
def read_message(self, id_): """Login required. Send POST to mark a message as read. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/read_message/`` :param id\_: full id of message to mark """ data = dict(id=id_) j = self.post('api', 'rea...
def subscribe(self, sr): """Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response...
def distinguish(self, id_, how=True): """Login required. Sends POST to distinguish a submission or comment. Returns :class:`things.Link` or :class:`things.Comment`, or raises :class:`exceptions.UnexpectedResponse` otherwise. URL: ``http://www.reddit.com/api/distinguish/`` :param id\_: full id of object to distinguish :...
def flairlist(self, r, limit=1000, after=None, before=None): """Login required. Gets flairlist for subreddit `r`. See https://github.com/reddit/reddit/wiki/API%3A-flairlist. However, the wiki docs are wrong (as of 2012/5/4). Returns :class:`things.ListBlob` of :class:`things.Blob` objects, each object being a mapping w...
def flair(self, r, name, text, css_class): """Login required. Sets flair for a user. See https://github.com/reddit/reddit/wiki/API%3A-flair. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/flair`` :param r: name of subreddit :param name: ...
def flaircsv(self, r, flair_csv): """Login required. Bulk sets flair for users. See https://github.com/reddit/reddit/wiki/API%3A-flaircsv/. Returns response JSON content as dict. URL: ``http://www.reddit.com/api/flaircsv`` :param r: name of subreddit :param flair_csv: csv string """ # TODO: handle the response better t...
def contributors(self, sr, limit=None): """Login required. GETs list of contributors to subreddit ``sr``. Returns :class:`things.ListBlob` object. **NOTE**: The :class:`things.Account` objects in the returned ListBlob *only* have ``id`` and ``name`` set. This is because that's all reddit returns. If you need full info ...
def etree_to_dict(source): """ Recursively load dict/list representation of an XML tree into an etree representation. Args: source -- An etree Element or ElementTree. Returns: A dictionary representing sorce's xml structure where tags with multiple identical childrens contain list of all their children dictionaries.. >...
TypeError("Requires an Element or an ElementTree.")
def dict_to_etree(source, root_tag=None): """ Recursively load dict/list representation of an XML tree into an etree representation. Args: source -- A dictionary representing an XML document where identical children tags are countained in a list. Keyword args: root_tag -- A parent tag in which to wrap the xml tree. If ...
dict_to_etree_recursive(source, parent): if hasattr(source, 'keys'): for key, value in source.iteritems(): sub = ET.SubElement(parent, key) dict_to_etree_recursive(value, sub) elif isinstance(source, list): for element in source: dict_to_etree_recursive(element, parent) else: # TODO: Add feature to include xml literals...
def to_etree(source, root_tag=None): """ Convert various representations of an XML structure to a etree Element Args: source -- The source object to be converted - ET.Element\ElementTree, dict or string. Keyword args: root_tag -- A optional parent tag in which to wrap the xml tree if no root in dict representation. See...
def to_raw_xml(source): """ Convert various representations of an XML structure to a normal XML string. Args: source -- The source object to be converted - ET.Element, dict or string. Returns: A rew xml string matching the source object. >>> to_raw_xml("<content/>") '<content/>' >>> to_raw_xml({'document': {'title': 'f...
def main(): """ Check args """ configure_obj = None parser = argparse.ArgumentParser(description='自动化安装') parser.add_argument( '-s', '--server', help='服务器代替名', ) parser.add_argument( '-ba', '--bigdata-app', help='大数据服务应用替代名', ) parser.add_argument( '-add-slave', '--add-slave', help='添加一个子节点服务器', ) parser.add_argument( ...
) args = parser.parse_args() # if config file and host both not provide, throw a error if args.config is None and args.host is None: raise ValueError('缺少配置文件-C(--config)或客户机地址-H(--host)') # check user and passwd if args.host is not None: if (args.user and (args.passwd or args.keyfile)) is None: raise ValueError('缺少登录必要...
def parse_arguments(filters, arguments, modern=False): """ Return a dict of parameters. Take a list of filters and for each try to get the corresponding value in arguments or a default value. Then check that value's type. The @modern parameter indicates how the arguments should be interpreted. The old way is that you a...
"value1", "unknown": 12345 } => { "param1": ["value1"], "param2": 0, "param3": ["list", "of", "4", "values"] } And an example for the old way: filters = [ ("param1", "default", ["list", "str"]), ("param2", None, "int"), ("param3", ["list", "of", 4, "values"], ["list", "str"]) ] arguments = { "param1": "value1", "unknow...
isinstance(types, list) and param is not None: assert len(types) == 1 if not isinstance(param, list): param = [param] param = [check_type(x, types[0]) for x in param] else: param = check_type(param, types) else: if not isinstance(types, list): types = [types] for t in reversed(types): if t == "list" and not isinstance(...
def check_type(param, datatype): """ Make sure that param is of type datatype and return it. If param is None, return it. If param is an instance of datatype, return it. If param is not an instance of datatype and is not None, cast it as datatype and return it. """ if param is None: return param if getattr(datatype, 'c...
= str() elif datatype is int and not isinstance(param, int): try: param = int(param) except ValueError: param = int() elif datatype is bool and not isinstance(param, bool): param = str(param).lower() in ("true", "t", "1", "y", "yes") elif ( datatype is datetime.datetime and not isinstance(param, datetime.datetime) ): t...
def authenticate(user=None): # noqa: E501 """Authenticate Authenticate with the API # noqa: E501 :param user: The user authentication object. :type user: dict | bytes :rtype: UserAuth """ if connexion.request.is_json: user = UserAuth.from_dict(connexion.request.get_json()) # noqa: E501 credentials = mapUserAuthToCreden...
def resolve_local(self, uri, base_uri, ref): """ Resolve a local ``uri``. Does not check the store first. :argument str uri: the URI to resolve :returns: the retrieved document """ # read it from the filesystem file_path = None # make the reference saleskingstyle item_name = None if (uri.startswith(u"file") or uri.star...
raise SalesKingException("SCHEMA_NOT_FOUND", msg) if self.cache_remote: self.store[uri] = result return result
def resolving(self, ref): """ Context manager which resolves a JSON ``ref`` and enters the resolution scope of this ref. :argument str ref: reference to resolve """ # print u"resol_scope: %s, ref: %s" % (self.resolution_scope, ref) full_uri = urljoin(self.resolution_scope, ref) uri, fragment = urldefrag(full_uri) if no...
def cached(func): """ A decorator function to cache values. It uses the decorated function's arguments as the keys to determine if the function has been called previously. """ cache = {} @f.wraps(func) def wrapper(*args, **kwargs): key = func.__name__ + str(sorted(args)) + str(sorted(kwargs.items())) if key not in cach...
def retry_wait_time(attempt, cap): """ Determine a retry wait time based on the number of the retry attempt and a cap on the wait time. The wait time uses an exponential backoff with a random jitter. The algorithm used is explained at https://www.awsarchitectureblog.com/2015/03/backoff.html. :param int attempt: The num...
def retry_ex(callback, times=3, cap=120000): """ Retry a callback function if any exception is raised. :param function callback: The function to call :keyword int times: Number of times to retry on initial failure :keyword int cap: Maximum wait time in milliseconds :returns: The return value of the callback :raises Exc...
def retry_bool(callback, times=3, cap=120000): """ Retry a callback function if it returns False. :param function callback: The function to call :keyword int times: Number of times to retry on initial failure :keyword int cap: Maximum wait time in milliseconds :returns: The return value of the callback :rtype: bool """...
def retryable(retryer=retry_ex, times=3, cap=120000): """ A decorator to make a function retry. By default the retry occurs when an exception is thrown, but this may be changed by modifying the ``retryer`` argument. See also :py:func:`retry_ex` and :py:func:`retry_bool`. By default :py:func:`retry_ex` is used as the re...
def ensure_environment(variables): """ Check os.environ to ensure that a given collection of variables has been set. :param variables: A collection of environment variable names :returns: os.environ :raises IncompleteEnvironment: if any variables are not set, with the exception's ``variables`` attribute populated with ...
def change_column_length(table: Table, column: Column, length: int, engine: Engine) -> None: """ Change the column length in the supplied table """ if column.type.length < length: print("Changing length of {} from {} to {}".format(column, column.type.length, length)) column.type.length = length column_name = column.nam...
def _db_urls(opts: Namespace) -> Tuple[str, str]: """ Return the crc and ontology db urls :param opts: options :return: Tuple w/ crc and ontology url """ return opts.crcdb.replace("//", "//{crcuser}:{crcpassword}@".format(**opts.__dict__)),\ opts.ontodb.replace("//", "//{ontouser}:{ontopassword}@".format(**opts.__dict_...
def _tables(self) -> List[Tuple[str, str]]: """ Return a list of all known tables and and its full URI :return: table name and full URI """ return [(k.rsplit('.', 1)[1] if '.' in k else k, k) for k in self._ont_tables.keys()]
def isdir(path, message): """ Raise an exception if the given directory does not exist. :param path: The path to a directory to be tested :param message: A custom message to report in the exception :raises: FileNotFoundError """ if not os.path.isdir(path): raise FileNotFoundError( errno.ENOENT, "{}: {}".format(message,...
def flush(self): """ Sends buffered data to the target """ # Flush buffer line = self._buffer.getvalue() self._buffer = StringIO() # Send the message content = {"session_id": self._session, "text": line} self._herald.fire(self._peer, beans.Message(MSG_CLIENT_PRINT, content))
def readline(self): """ Waits for a line from the Herald client """ content = {"session_id": self._session} prompt_msg = self._herald.send( self._peer, beans.Message(MSG_CLIENT_PROMPT, content)) if prompt_msg.subject == MSG_SERVER_CLOSE: # Client closed its shell raise EOFError return prompt_msg.content
def make_frog_fresco(text, width, padding=8): """\ Formats your lovely text into a speech bubble spouted by this adorable little frog. """ stem = r' /' frog = r""" {text} {stem} @..@ (----) ( >__< ) ^^ ~~ ^^""" offset = len(stem) - 1 formatted_indent = ' ' * offset formatted_text = textwrap.fill(text, width=width-paddi...
def mgz_to_nifti(filename,prefix=None,gzip=True): '''Convert ``filename`` to a NIFTI file using ``mri_convert``''' setup_freesurfer() if prefix==None: prefix = nl.prefix(filename) + '.nii' if gzip and not prefix.endswith('.gz'): prefix += '.gz' nl.run([os.path.join(freesurfer_home,'bin','mri_convert'),filename,prefix],...
def guess_home(): '''If ``freesurfer_home`` is not set, try to make an intelligent guess at it''' global freesurfer_home if freesurfer_home != None: return True # if we already have it in the path, use that fv = nl.which('freeview') if fv: freesurfer_home = parpar_dir(os.path.realpath(fv)) return True for guess_dir in ...
def setup_freesurfer(): '''Setup the freesurfer environment variables''' guess_home() os.environ['FREESURFER_HOME'] = freesurfer_home os.environ['SUBJECTS_DIR'] = subjects_dir # Run the setup script and collect the output: o = subprocess.check_output(['bash','-c','source %s/SetUpFreeSurfer.sh && env' % freesurfer_home]...
def recon_all(subj_id,anatomies): '''Run the ``recon_all`` script''' if not environ_setup: setup_freesurfer() if isinstance(anatomies,basestring): anatomies = [anatomies] nl.run([os.path.join(freesurfer_home,'bin','recon-all'),'-all','-subjid',subj_id] + [['-i',anat] for anat in anatomies])
def parse_docstring(docstring): """ Parse a PEP-257 docstring. SHORT -> blank line -> LONG """ short_desc = long_desc = '' if docstring: docstring = trim(docstring.lstrip('\n')) lines = docstring.split('\n\n', 1) short_desc = lines[0].strip().replace('\n', ' ') if len(lines) > 1: long_desc = lines[1].strip() return sho...
def add_command(self, factory, main, name=None, context_kwargs=None): """ Attach a command directly to the :class:`CLI` object. """ if name is None: name = factory.__name__.replace('_', '-') if context_kwargs is None: context_kwargs = {} short_desc, long_desc = parse_docstring(factory.__doc__) if long_desc: long_desc =...
def command(self, *args, **kwargs): """ Attach a command to the current :class:`CLI` object. The function should accept an instance of an :class:`argparse.ArgumentParser` and use it to define extra arguments and options. These options will only affect the specified command. """ def wrapper(func): self.add_command(func,...
def load_commands(self, obj): """ Load commands defined on an arbitrary object. All functions decorated with the :func:`subparse.command` decorator attached the specified object will be loaded. The object may be a dictionary, an arbitrary python object, or a dotted path. The dotted path may be absolute, or relative to ...
def load_commands_from_entry_point(self, specifier): """ Load commands defined within a pkg_resources entry point. Each entry will be a module that should be searched for functions decorated with the :func:`subparse.command` decorator. This operation is not recursive. """ for ep in pkg_resources.iter_entry_points(speci...
def run(self, argv=None): """ Run the command-line application. This will dispatch to the specified function or raise a ``SystemExit`` and output the appropriate usage information if there is an error parsing the arguments. The default ``argv`` is equivalent to ``sys.argv[1:]``. """ if argv is None: # pragma: no cover ...
def main(xmpp_server, xmpp_port, peer_name, node_name, app_id, xmpp_jid=None, xmpp_password=None): """ Runs the framework :param xmpp_server: Address of the XMPP server :param xmpp_port: Port of the XMPP server :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app...
the framework and wait for it to stop framework.wait_for_stop()
def remove_small_objects(image, min_size=50, connectivity=1): """Remove small objects from an boolean image. :param image: boolean numpy array or :class:`jicbioimage.core.image.Image` :returns: boolean :class:`jicbioimage.core.image.Image` """ return skimage.morphology.remove_small_objects(image, min_size=min_size, con...
def invert(image): """Return an inverted image of the same dtype. Assumes the full range of the input dtype is in use and that no negative values are present in the input image. :param image: :class:`jicbioimage.core.image.Image` :returns: inverted image of the same dtype as the input """ if image.dtype == bool: return...
def run(*popenargs, **kwargs): """Run command with arguments and return a `CompletedProcess` instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes will be None. Pass stdout=PIPE and/or stderr=PIPE in order to captur...
to the subprocess's stdin. If you use this argument you may not also use the Popen constructor's `stdin` argument, as it will be used internally. The other arguments are the same as for the Popen constructor. If universal_newlines=True is passed, the `input` argument must be a string and stdout/stderr in the returned o...
pylint: disable=no-member raise _TimeoutExpired(process.args, timeout, output=stdout, stderr=stderr) except: process.kill() process.wait() raise retcode = process.poll() if check and retcode: raise CalledProcessError(retcode, popenargs, output=stdout, stderr=stderr) return CompletedProcess(popenargs, retcode, stdout, s...
def check_returncode(self): """Raise CalledProcessError if the exit code is non-zero.""" if self.returncode: raise CalledProcessError(self.returncode, self.args, self.stdout, self.stderr)
def double_lorgauss(x,p): """Evaluates a normalized distribution that is a mixture of a double-sided Gaussian and Double-sided Lorentzian. Parameters ---------- x : float or array-like Value(s) at which to evaluate distribution p : array-like Input parameters: mu (mode of distribution), sig1 (LH Gaussian width), sig2 (...
G2 - L2 #print G1,G2,L1,L2 y1 = G1/(sig1*np.sqrt(2*np.pi)) * np.exp(-0.5*(x-mu)**2/sig1**2) +\ L1/(np.pi*gam1) * gam1**2/((x-mu)**2 + gam1**2) y2 = G2/(sig2*np.sqrt(2*np.pi)) * np.exp(-0.5*(x-mu)**2/sig2**2) +\ L2/(np.pi*gam2) * gam2**2/((x-mu)**2 + gam2**2) lo = (x < mu) hi = (x >= mu) return y1*lo + y2*hi
def fit_double_lorgauss(bins,h,Ntry=5): """Uses lmfit to fit a "Double LorGauss" distribution to a provided histogram. Uses a grid of starting guesses to try to avoid local minima. Parameters ---------- bins, h : array-like Bins and heights of a histogram, as returned by, e.g., `np.histogram`. Ntry : int, optional Spac...
dbin = (bins[1:]-bins[:-1]).mean() newbins = np.concatenate((np.linspace(bins.min() - N/10*dbin,bins.min(),N/10), bins, np.linspace(bins.max(),bins.max() + N/10*dbin,N/10))) newh = np.concatenate((np.zeros(N/10),h,np.zeros(N/10))) mu0 = bins[np.argmax(newh)] sig0 = abs(mu0 - newbins[np.argmin(np.absolute(newh - 0.5*new...
def doublegauss(x,p): """Evaluates normalized two-sided Gaussian distribution Parameters ---------- x : float or array-like Value(s) at which to evaluate distribution p : array-like Parameters of distribution: (mu: mode of distribution, sig1: LH width, sig2: RH width) Returns ------- value : float or array-like Distrib...
def doublegauss_cdf(x,p): """Cumulative distribution function for two-sided Gaussian Parameters ---------- x : float Input values at which to calculate CDF. p : array-like Parameters of distribution: (mu: mode of distribution, sig1: LH width, sig2: RH width) """ x = np.atleast_1d(x) mu,sig1,sig2 = p sig1 = np.absolute(...
def fit_doublegauss_samples(samples,**kwargs): """Fits a two-sided Gaussian to a set of samples. Calculates 0.16, 0.5, and 0.84 quantiles and passes these to `fit_doublegauss` for fitting. Parameters ---------- samples : array-like Samples to which to fit the Gaussian. kwargs Keyword arguments passed to `fit_doublegaus...
def fit_doublegauss(med,siglo,sighi,interval=0.683,p0=None,median=False,return_distribution=True): """Fits a two-sided Gaussian distribution to match a given confidence interval. The center of the distribution may be either the median or the mode. Parameters ---------- med : float The center of the distribution to whic...