positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def apply_patch(patchfile,cwd=None,posix=False,level=0): """call 'patch -p[level] [--posix] < arg1' posix mode is sometimes necessary. It keeps empty files so that dpkg-source removes their contents. """ if not os.path.exists(patchfile): raise RuntimeError('patchfile "%s" does not exist'%p...
call 'patch -p[level] [--posix] < arg1' posix mode is sometimes necessary. It keeps empty files so that dpkg-source removes their contents.
def rank(self, n, mu, sigma, crit=.5, upper=10000, xtol=1): """%(super)s Additional Parameters ---------------------- {0} """ return _make_rank(self, n, mu, sigma, crit=crit, upper=upper, xtol=xtol)
%(super)s Additional Parameters ---------------------- {0}
async def cellAuthToHive(dirn, auth): ''' Migrate old cell Auth() data into a HiveAuth(). ''' logger.warning('migrating old cell auth to hive') path = os.path.join(dirn, 'auth.lmdb') lenv = lmdb.open(path, max_dbs=128) userdb = lenv.open_db(b'users') roledb = lenv.open_db(b'roles') ...
Migrate old cell Auth() data into a HiveAuth().
def cached_get(timeout, *params): """Decorator applied specifically to a view's get method""" def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(view_or_request, *args, **kwargs): # The type of the request gets muddled when using a fu...
Decorator applied specifically to a view's get method
def _create_metadata_converter_action(self): """Create action for showing metadata converter dialog.""" icon = resources_path('img', 'icons', 'show-metadata-converter.svg') self.action_metadata_converter = QAction( QIcon(icon), self.tr('InaSAFE Metadata Converter'), ...
Create action for showing metadata converter dialog.
def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit): '''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits''' assert start_hit.qry_name == end_hit.qry_name if start_hit.ref_name == end_hit.ref_name: ...
Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits
def get_value(self, **kwargs): """Return the value for a specific key.""" key = tuple(kwargs[group] for group in self.groups) if key not in self.data: self.data[key] = 0 return self.data[key]
Return the value for a specific key.
def get_one_parameter(self, regex_exp, parameters): """ Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return: """ Rx, other = self.get_parameters(regex_exp, parame...
Get three parameters from a given regex expression Raise an exception if more than three were found :param regex_exp: :param parameters: :return:
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
Execute code in the kernel without increasing the prompt
def check_out_item(self, expiration): """Get the highest-priority item out of this queue. Returns the item, or None if no items are available. The item must be either ``return_item()`` or ``renew_item()`` before ``expiration`` seconds pass, or it will become available to future...
Get the highest-priority item out of this queue. Returns the item, or None if no items are available. The item must be either ``return_item()`` or ``renew_item()`` before ``expiration`` seconds pass, or it will become available to future callers. The item will be marked as being owned...
def application_adapter(obj, request): """ Adapter for rendering a :class:`pyramid_urireferencer.models.ApplicationResponse` to json. :param pyramid_urireferencer.models.ApplicationResponse obj: The response to be rendered. :rtype: :class:`dict` """ return { 'title': obj.title, ...
Adapter for rendering a :class:`pyramid_urireferencer.models.ApplicationResponse` to json. :param pyramid_urireferencer.models.ApplicationResponse obj: The response to be rendered. :rtype: :class:`dict`
def store_sentry(self, username, sentry_bytes): """ Store sentry bytes under a username :param username: username :type username: :class:`str` :return: Whenver the operation succeed :rtype: :class:`bool` """ filepath = self._get_sentry_path(username) ...
Store sentry bytes under a username :param username: username :type username: :class:`str` :return: Whenver the operation succeed :rtype: :class:`bool`
def Freqs(self,jr,jphi,jz,**kwargs): """ NAME: Freqs PURPOSE: return the frequencies corresponding to a torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) tol= (...
NAME: Freqs PURPOSE: return the frequencies corresponding to a torus INPUT: jr - radial action (scalar) jphi - azimuthal action (scalar) jz - vertical action (scalar) tol= (object-wide value) goal for |dJ|/|J| along the torus ...
def __dbfRecord(self, record): """Writes the dbf records.""" f = self.__getFileObj(self.dbf) if self.recNum == 0: # first records, so all fields should be set # allowing us to write the dbf header # cannot change the fields after this point ...
Writes the dbf records.
def to_python(self, value): """ "Called during deserialization and during the clean() method used from forms.... [s]hould deal gracefully with... (*) an instance of the correct type; (*) a string; (*) None (if the field allows null=True)." "For ``to_python()``, if anythi...
"Called during deserialization and during the clean() method used from forms.... [s]hould deal gracefully with... (*) an instance of the correct type; (*) a string; (*) None (if the field allows null=True)." "For ``to_python()``, if anything goes wrong during value conversion, y...
def value(self): """returns the object as dictionary""" if self._outline is None: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle, ...
returns the object as dictionary
def getAggregation(self): """Returns: str : URIRef of the Aggregation entity """ self._check_initialized() return [ o for o in self.subjects(predicate=rdflib.RDF.type, object=ORE.Aggregation) ][0]
Returns: str : URIRef of the Aggregation entity
def connect(self, fedora_url, data=None, method='Get'): """Method attempts to connect to REST servers of the Fedora Commons repository using optional data parameter. Args: fedora_url(string): Fedora URL data(dict): Data to ...
Method attempts to connect to REST servers of the Fedora Commons repository using optional data parameter. Args: fedora_url(string): Fedora URL data(dict): Data to through to REST endpoint method(str): REST Method, defaults to GET Returns: result...
def padding(self): """Returns the padding algorithm used, if this is the same for all dims. Use `.paddings` if you want a tuple with the padding algorithm used for each dimension. Returns: The padding algorithm used, if this is the same for all dimensions. Raises: ValueError: If diffe...
Returns the padding algorithm used, if this is the same for all dims. Use `.paddings` if you want a tuple with the padding algorithm used for each dimension. Returns: The padding algorithm used, if this is the same for all dimensions. Raises: ValueError: If different padding algorithms ar...
def __detect_cl_tool(env, chainkey, cdict, cpriority=None): """ Helper function, picks a command line tool from the list and initializes its environment variables. """ if env.get(chainkey,'') == '': clpath = '' if cpriority is None: cpriority = cdict.keys() for c...
Helper function, picks a command line tool from the list and initializes its environment variables.
def clean_requires_python(candidates): """Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes.""" all_candidates = [] sys_version = ".".join(map(str, sys.version_info[:3])) from packaging.version import parse as parse_version py_version = parse_version...
Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes.
def acquire(self, host: str, port: int, use_ssl: bool=False, host_key: Optional[Any]=None) \ -> Union[Connection, SSLConnection]: '''Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether ...
Return an available connection. Args: host: A hostname or IP address. port: Port number. use_ssl: Whether to return a SSL connection. host_key: If provided, it overrides the key used for per-host connection pooling. This is useful for proxies for ...
def add_methods(source_class, blacklist=()): """Add wrapped versions of the `api` member's methods to the class. Any methods passed in `blacklist` are not added. Additionally, any methods explicitly defined on the wrapped class are not added. """ def wrap(wrapped_fx): """Wrap a GAPIC m...
Add wrapped versions of the `api` member's methods to the class. Any methods passed in `blacklist` are not added. Additionally, any methods explicitly defined on the wrapped class are not added.
def sendDocument(self, chat_id, document, thumb=None, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://cor...
See: https://core.telegram.org/bots/api#senddocument :param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
def handle_verification_form(form): """Handle email sending verification form.""" form.process(formdata=request.form) if form.validate_on_submit(): send_confirmation_instructions(current_user) # NOTE: Flash message. flash(_("Verification email sent."), category="success")
Handle email sending verification form.
def build_tree(self, data, tagname, attrs=None, depth=0): r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. De...
r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. Default:``0``. :type depth: int
def _run_command( command, input_data=None, stdin=None, out_pipe=subprocess.PIPE, err_pipe=subprocess.PIPE, env=None, uuid=None, **kwargs ): """ Runs a command Args: command(list of str): args of the command to execute, including the command itself as com...
Runs a command Args: command(list of str): args of the command to execute, including the command itself as command[0] as `['ls', '-l']` input_data(str): If passed, will feed that data to the subprocess through stdin out_pipe(int or file): File descriptor as passed to...
def check_update (): """Return the following values: (False, errmsg) - online version could not be determined (True, None) - user has newest version (True, (version, url string)) - update available (True, (version, None)) - current version is newer than online version """ version...
Return the following values: (False, errmsg) - online version could not be determined (True, None) - user has newest version (True, (version, url string)) - update available (True, (version, None)) - current version is newer than online version
def chainproperty(func): """Extend sure with a custom chain property.""" func = assertionproperty(func) setattr(AssertionBuilder, func.fget.__name__, func) return func
Extend sure with a custom chain property.
def add_allowance(self, caller): """Adds a new allowance for the method. :param: tuple caller: A tuple indicating where the method was called :return: The new ``Allowance``. :rtype: Allowance """ allowance = Allowance(self._target, self._method_name, caller) sel...
Adds a new allowance for the method. :param: tuple caller: A tuple indicating where the method was called :return: The new ``Allowance``. :rtype: Allowance
def load(fnames, tag='', sat_id=None): """ Load the SuperMAG files Parameters ----------- fnames : (list) List of filenames tag : (str or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (d...
Load the SuperMAG files Parameters ----------- fnames : (list) List of filenames tag : (str or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (default='') sat_id : (str or NoneType) ...
def create(self, name: str, descriptor: str, value: Constant=None) -> Field: """ Creates a new field from `name` and `descriptor`. For example:: >>> from jawa.cf import ClassFile >>> cf = ClassFile.create('BeerCounter') >>> field = cf.fields.create('BeerCount', 'I') ...
Creates a new field from `name` and `descriptor`. For example:: >>> from jawa.cf import ClassFile >>> cf = ClassFile.create('BeerCounter') >>> field = cf.fields.create('BeerCount', 'I') To automatically create a static field, pass a value:: >>> from jawa.cf imp...
def get_dataset(dataset_id,**kwargs): """ Get a single dataset, by ID """ user_id = int(kwargs.get('user_id')) if dataset_id is None: return None try: dataset_rs = db.DBSession.query(Dataset.id, Dataset.type, Dataset.unit_id, ...
Get a single dataset, by ID
def lines(self: object, fileids: str, plaintext: bool = True): """ Tokenizes documents in the corpus by line """ for text in self.texts(fileids, plaintext): text = re.sub(r'\n\s*\n', '\n', text, re.MULTILINE) # Remove blank lines for line in text.split('\n'): ...
Tokenizes documents in the corpus by line
def _add_subtitles(self, subtitles): '''Adds subtitles to playing video. :param subtitles: A URL to a remote subtitles file or a local filename for a subtitles file. .. warning:: You must start playing a video before calling this method or it will...
Adds subtitles to playing video. :param subtitles: A URL to a remote subtitles file or a local filename for a subtitles file. .. warning:: You must start playing a video before calling this method or it will loop for an indefinite length.
def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths. """ # Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or pas...
Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths.
def _logging_callback(level, domain, message, data): """ Callback that outputs libgphoto2's logging message via Python's standard logging facilities. :param level: libgphoto2 logging level :param domain: component the message originates from :param message: logging message :param data: ...
Callback that outputs libgphoto2's logging message via Python's standard logging facilities. :param level: libgphoto2 logging level :param domain: component the message originates from :param message: logging message :param data: Other data in the logging record (unused)
def Sign(self, data, signing_key, verify_key=None): """Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: se...
Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: self for call chaining.
def initializerepo(self): """ Fill empty directory with products and make first commit """ try: os.mkdir(self.repopath) except OSError: pass cmd = self.repo.init(bare=self.bare, shared=self.shared) if not self.bare: self.write_testing_data([...
Fill empty directory with products and make first commit
def decimal_year(year, month, day): """ Allows to calculate the decimal year for a vector of dates (TODO this is legacy code kept to maintain comparability with previous declustering algorithms!) :param year: year column from catalogue matrix :type year: numpy.ndarray :param month: month co...
Allows to calculate the decimal year for a vector of dates (TODO this is legacy code kept to maintain comparability with previous declustering algorithms!) :param year: year column from catalogue matrix :type year: numpy.ndarray :param month: month column from catalogue matrix :type month: nump...
def case(self, case_id=None): """Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object """ cases = self.cases() if case_id: for case ...
Return a Case object If no case_id is given return one case Args: case_id (str): A case id Returns: case(Case): A Case object
def _parseDOM(istack): """ Recursively go through element array and create DOM. Args: istack (list): List of :class:`.HTMLElement` objects. Returns: list: DOM tree as list. """ ostack = [] end_tag_index = 0 def neither_nonpair_or_end_or_comment(el): return not ...
Recursively go through element array and create DOM. Args: istack (list): List of :class:`.HTMLElement` objects. Returns: list: DOM tree as list.
def create_resource(self, resource_type=None, uri=None): ''' Convenience method for creating a new resource Note: A Resource is instantiated, but is not yet created. Still requires resource.create(). Args: uri (rdflib.term.URIRef, str): uri of resource to create resource_type (NonRDFSource (Binary), B...
Convenience method for creating a new resource Note: A Resource is instantiated, but is not yet created. Still requires resource.create(). Args: uri (rdflib.term.URIRef, str): uri of resource to create resource_type (NonRDFSource (Binary), BasicContainer, DirectContainer, IndirectContainer): resource type...
def list_(): ''' Return a list of accepted, denied, unaccepted and rejected keys. This is the same output as `salt-key -L` CLI Example: .. code-block:: bash salt 'master' minion.list ''' pki_dir = __salt__['config.get']('pki_dir', '') # We have to replace the minion/master di...
Return a list of accepted, denied, unaccepted and rejected keys. This is the same output as `salt-key -L` CLI Example: .. code-block:: bash salt 'master' minion.list
def get_port_vendor_info(port=None): """ Return vendor informations of a usb2serial device. It may depends on the Operating System. :param string port: port of the usb2serial device :Example: Result with a USB2Dynamixel on Linux: In [1]: import pypot.dynamixel In [2...
Return vendor informations of a usb2serial device. It may depends on the Operating System. :param string port: port of the usb2serial device :Example: Result with a USB2Dynamixel on Linux: In [1]: import pypot.dynamixel In [2]: pypot.dynamixel.get_port_vendor_info('/dev...
def debug_dump(message, file_prefix="dump"): """ Utility while developing to dump message data to play with in the interpreter """ global index index += 1 with open("%s_%s.dump" % (file_prefix, index), 'w') as f: f.write(message.SerializeToString()) f.close()
Utility while developing to dump message data to play with in the interpreter
def process(self, request, item): """Do a direct payment.""" warn_untested() from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) # Change the model information into a dict that PayPal can understand. params = model_to_dict(self, exclude=self.ADMIN_FIELDS) ...
Do a direct payment.
def date_to_um_dump_date(date): """ Convert a time date object to a um dump format date which is <decade><year><month><day>0 To accommodate two digit months and days the UM uses letters. e.g. 1st oct is writing 01a10. """ assert(date.month <= 12) decade = date.year // 10 # UM can ...
Convert a time date object to a um dump format date which is <decade><year><month><day>0 To accommodate two digit months and days the UM uses letters. e.g. 1st oct is writing 01a10.
def clausulae_analysis(prosody): """ Return dictionary in which the key is a type of clausula and the value is its frequency. :param prosody: the prosody of a prose text (must be in the format of the scansion produced by the scanner classes. :return: dictionary of prosody """ ...
Return dictionary in which the key is a type of clausula and the value is its frequency. :param prosody: the prosody of a prose text (must be in the format of the scansion produced by the scanner classes. :return: dictionary of prosody
def load_config(self): """Load the config from the config file or template.""" config = Config() self.config_obj = config.load('awsshellrc') self.config_section = self.config_obj['aws-shell'] self.model_completer.match_fuzzy = self.config_section.as_bool( 'match_fuzzy...
Load the config from the config file or template.
def datacenter_configured(name): ''' Makes sure a datacenter exists. If the state is run by an ``esxdatacenter`` minion, the name of the datacenter is retrieved from the proxy details, otherwise the datacenter has the same name as the state. Supported proxies: esxdatacenter name: ...
Makes sure a datacenter exists. If the state is run by an ``esxdatacenter`` minion, the name of the datacenter is retrieved from the proxy details, otherwise the datacenter has the same name as the state. Supported proxies: esxdatacenter name: Datacenter name. Ignored if the proxytype is ...
def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get...
Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae
def has_integration(self, path, method): """ Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present """ metho...
Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present
def pop(self, key, resource_type): """ Extract an object from the list. If the key is not in the cache, this will raise a KeyError. If the list is empty, method will return None """ with self._objects_queue_lock: objects = self._objects_queue[key].get(resource...
Extract an object from the list. If the key is not in the cache, this will raise a KeyError. If the list is empty, method will return None
def get_sci_segs_for_ifo(ifo, cp, start_time, end_time, out_dir, tags=None): """ Obtain science segments for the selected ifo Parameters ----------- ifo : string The string describing the ifo to obtain science times for. start_time : gps time (either int/LIGOTimeGPS) The time at...
Obtain science segments for the selected ifo Parameters ----------- ifo : string The string describing the ifo to obtain science times for. start_time : gps time (either int/LIGOTimeGPS) The time at which to begin searching for segments. end_time : gps time (either int/LIGOTimeGPS) ...
def unserialize(jsonstr): ''' Unserialize a JSON string representation of a topology ''' topod = json.loads(jsonstr) G = json_graph.node_link_graph(topod) for n,ndict in G.nodes(data=True): if 'nodeobj' not in ndict or 'type' not in ndict: rais...
Unserialize a JSON string representation of a topology
def temp_dir(sub_dir='work'): """Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a tem...
Obtain the temporary working directory for the operating system. An inasafe subdirectory will automatically be created under this and if specified, a user subdirectory under that. .. note:: You can use this together with unique_filename to create a file in a temporary directory under the inasafe wo...
def is_monotonic(full_list): """ Determine whether elements in a list are monotonic. ie. unique elements are clustered together. ie. [5,5,3,4] is, [5,3,5] is not. """ prev_elements = set({full_list[0]}) prev_item = full_list[0] for item in full_list: if item != prev_item: ...
Determine whether elements in a list are monotonic. ie. unique elements are clustered together. ie. [5,5,3,4] is, [5,3,5] is not.
def _to_protobuf(self): """Convert the current query into the equivalent protobuf. Returns: google.cloud.firestore_v1beta1.types.StructuredQuery: The query protobuf. """ projection = self._normalize_projection(self._projection) orders = self._normalize_or...
Convert the current query into the equivalent protobuf. Returns: google.cloud.firestore_v1beta1.types.StructuredQuery: The query protobuf.
def center(self): """Return footprint center in world coordinates, as GeoVector.""" image_center = Point(self.width / 2, self.height / 2) return self.to_world(image_center)
Return footprint center in world coordinates, as GeoVector.
def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(re...
Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]'
def transfer_learning_tuner(self, additional_parents=None, estimator=None): """Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as "TransferL...
Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as "TransferLearning" and parents as the union of provided list of ``additional_parents`` and the ``...
def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None, pw=None, timeout=None): """ Deletes an object. """ raise NotImplementedError
Deletes an object.
def quadratic_jacobian_polynomial(nodes): r"""Compute the Jacobian determinant of a quadratic surface. .. note:: This is used **only** by :meth:`Surface._compute_valid` (which is in turn used to compute / cache the :attr:`Surface.is_valid` property). Converts :math:`\det(J(s, t))` to...
r"""Compute the Jacobian determinant of a quadratic surface. .. note:: This is used **only** by :meth:`Surface._compute_valid` (which is in turn used to compute / cache the :attr:`Surface.is_valid` property). Converts :math:`\det(J(s, t))` to a polynomial on the reference triangle an...
def link(self): """Link all the types in this module and all included modules.""" if self.linked: return self self.linked = True included_modules = [] # Link includes for include in self.includes.values(): included_modules.append(include.link()....
Link all the types in this module and all included modules.
def main(league, time, standings, team, live, use12hour, players, output_format, output_file, upcoming, lookup, listcodes, apikey): """ A CLI for live and past football scores from various football leagues. League codes: \b - WC: World Cup - EC: European Championship - CL: Champio...
A CLI for live and past football scores from various football leagues. League codes: \b - WC: World Cup - EC: European Championship - CL: Champions League - PL: English Premier League - ELC: English Championship - FL1: French Ligue 1 - BL: German Bundesliga - SA: Serie A - ...
def status(*args): """ Get the current status of the fragments repository, limited to FILENAME(s) if specified. Limit output to files with status STATUS, if present. """ parser = argparse.ArgumentParser(prog="%s %s" % (__package__, status.__name__), description=status.__doc__) parser.add_argumen...
Get the current status of the fragments repository, limited to FILENAME(s) if specified. Limit output to files with status STATUS, if present.
def verify(self): ''' Verify the correctness of the region arcs. Throws an VennRegionException if verification fails (or any other exception if it happens during verification). ''' # Verify size of arcs list if (len(self.arcs) < 2): raise VennRegionException("...
Verify the correctness of the region arcs. Throws an VennRegionException if verification fails (or any other exception if it happens during verification).
def rewrite_file_imports(item, vendored_libs): """Rewrite 'import xxx' and 'from xxx import' for vendored_libs""" text = item.read_text(encoding='utf-8') for lib in vendored_libs: text = re.sub( r'(\n\s*)import %s(\n\s*)' % lib, r'\1from pythonfinder._vendor import %s\2' % li...
Rewrite 'import xxx' and 'from xxx import' for vendored_libs
def is_token_annotation_tier(self, tier): """ returns True, iff all events in the given tier annotate exactly one token. """ for i, event in enumerate(tier.iter('event')): if self.indexdelta(event.attrib['end'], event.attrib['start']) != 1: return Fals...
returns True, iff all events in the given tier annotate exactly one token.
def alloc(self): """from _mosquitto_packet_alloc.""" byte = 0 remaining_bytes = bytearray(5) i = 0 remaining_length = self.remaining_length self.payload = None self.remaining_count = 0 loop_flag = True #self.dump() ...
from _mosquitto_packet_alloc.
def adjust_status(info: dict) -> dict: """Apply status mapping to a raw API result.""" modified_info = deepcopy(info) modified_info.update({ 'level': get_nearest_by_numeric_key(STATUS_MAP, int(info['level'])), 'level2': STATUS_MAP[99] if info['level2'] is None else ...
Apply status mapping to a raw API result.
def describe_subnet(subnet_id=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash ...
Given a subnet id or name, describe its properties. Returns a dictionary of interesting properties. .. versionadded:: 2015.8.0 CLI Examples: .. code-block:: bash salt myminion boto_vpc.describe_subnet subnet_id=subnet-123456 salt myminion boto_vpc.describe_subnet subnet_name=mysubne...
def run_cli(): "Command line interface to hiwenet." features_path, groups_path, weight_method, num_bins, edge_range, \ trim_outliers, trim_percentile, return_networkx_graph, out_weights_path = parse_args() # TODO add the possibility to process multiple combinations of parameters: diff subjects, diff m...
Command line interface to hiwenet.
def iter_commands(self): """Iterator returning ImportCommand objects.""" while True: line = self.next_line() if line is None: if b'done' in self.features: raise errors.PrematureEndOfStream(self.lineno) break elif len...
Iterator returning ImportCommand objects.
def pmag_results_extract(res_file="pmag_results.txt", crit_file="", spec_file="", age_file="", latex=False, grade=False, WD="."): """ Generate tab delimited output file(s) with result data. Save output files and return True if successful. Possible output files: Directions, Inten...
Generate tab delimited output file(s) with result data. Save output files and return True if successful. Possible output files: Directions, Intensities, SiteNfo, Criteria, Specimens Optional Parameters (defaults are used if not specified) ---------- res_file : name of pma...
def source(self): """Source.""" if "source" not in self.attrs.keys(): self.attrs["source"] = "None" value = self.attrs["source"] return value if not value == "None" else None
Source.
def OnRowSize(self, event): """Row size event handler""" row = event.GetRowOrCol() tab = self.grid.current_table rowsize = self.grid.GetRowSize(row) / self.grid.grid_renderer.zoom # Detect for resizing group of rows rows = self.grid.GetSelectedRows() if len(rows...
Row size event handler
def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(Tru...
Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:".
def hse_output(pdb_file, file_type): """ The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, buried and deepl...
The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, buried and deeply buried residues. Hamelryck et al. [73] establi...
def fix_shapes(self): """ Fixes the shape of the data fields on edges. Left edges should be column vectors, and top edges should be row vectors, for example. """ for i in xrange(self.n_chunks): for side in ['left', 'right', 'top', 'bottom']: edge = get...
Fixes the shape of the data fields on edges. Left edges should be column vectors, and top edges should be row vectors, for example.
def send_registered_email(self, user, user_email, request_email_confirmation): """Send the 'user has registered' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return # The ...
Send the 'user has registered' notification email.
def _iterate(self, url, params, api_entity): """ Args: url: params: api_entity: Return: """ params['resultLimit'] = self.result_limit should_iterate = True result_start = 0 while should_iterate: # params['re...
Args: url: params: api_entity: Return:
def _show_annotation_box(self, event): """Update an existing box or create an annotation box for an event.""" ax = event.artist.axes # Get the pre-created annotation box for the axes or create a new one. if self.display != 'multiple': annotation = self.annotations[ax] ...
Update an existing box or create an annotation box for an event.
def send_json_message(address, message, **kwargs): """ a shortcut for message sending """ data = { 'message': message, } if not kwargs.get('subject_id'): data['subject_id'] = address data.update(kwargs) hxdispatcher.send(address, data)
a shortcut for message sending
def orc(self, path): """Loads a ORC file stream, returning the result as a :class:`DataFrame`. .. note:: Evolving. >>> orc_sdf = spark.readStream.schema(sdf_schema).orc(tempfile.mkdtemp()) >>> orc_sdf.isStreaming True >>> orc_sdf.schema == sdf_schema True ...
Loads a ORC file stream, returning the result as a :class:`DataFrame`. .. note:: Evolving. >>> orc_sdf = spark.readStream.schema(sdf_schema).orc(tempfile.mkdtemp()) >>> orc_sdf.isStreaming True >>> orc_sdf.schema == sdf_schema True
def model_installed(name): """Check if spaCy language model is installed. From https://github.com/explosion/spaCy/blob/master/spacy/util.py :param name: :return: """ data_path = util.get_data_path() if not data_path or not data_path.exists(): raise I...
Check if spaCy language model is installed. From https://github.com/explosion/spaCy/blob/master/spacy/util.py :param name: :return:
def _update_dPrxy(self): """Update `dPrxy`.""" super(ExpCM_fitprefs, self)._update_dPrxy() if 'zeta' in self.freeparams: tildeFrxyQxy = self.tildeFrxy * self.Qxy j = 0 zetaxterm = scipy.ndarray((self.nsites, N_CODON, N_CODON), dtype='float') zetay...
Update `dPrxy`.
def noise_get_fbm( n: tcod.noise.Noise, f: Sequence[float], oc: float, typ: int = NOISE_DEFAULT, ) -> float: """Return the fractal Brownian motion sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. ...
Return the fractal Brownian motion sampled from the ``f`` coordinate. Args: n (Noise): A Noise instance. f (Sequence[float]): The point to sample the noise from. typ (int): The noise algorithm to use. octaves (float): The level of level. Should be more than 1. Returns: ...
def safe_write(filename, blob): """ A two-step write. :param filename: full path :param blob: binary data :return: None """ temp_file = filename + '.saving' with open(temp_file, 'bw') as f: f.write(blob) os.rename(temp_file, filename)
A two-step write. :param filename: full path :param blob: binary data :return: None
def stop_change(self): """Stop changing light level manually""" self.logger.info("Dimmer %s stop_change", self.device_id) self.hub.direct_command(self.device_id, '18', '00') success = self.hub.check_success(self.device_id, '18', '00') if success: self.logger.info("Di...
Stop changing light level manually
def _parse_string_host(host_str): """ Parse host string into a dictionary host :param host_str: :return: """ host_str = EsParser._fix_host_prefix(host_str) parsed_url = urlparse(host_str) host = {HostParsing.HOST: parsed_url.hostname} if parsed_url...
Parse host string into a dictionary host :param host_str: :return:
def items(self): """ Request URL and parse response. Yield a ``Torrent`` for every torrent on page. """ request = get(str(self.url), headers={'User-Agent' : "Magic Browser","origin_req_host" : "thepiratebay.se"}) root = html.fromstring(request.text) items = [self....
Request URL and parse response. Yield a ``Torrent`` for every torrent on page.
def text_color(self, value): """ Setter for **self.__text_color** attribute. :param value: Attribute value. :type value: int or QColor """ if value is not None: assert type(value) in (Qt.GlobalColor, QColor), \ "'{0}' attribute: '{1}' type is...
Setter for **self.__text_color** attribute. :param value: Attribute value. :type value: int or QColor
def ed25519_public_key_to_string(key): """Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.public_bytes( encoding=serializatio...
Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this block.""" self.validate() if len(self.start_class) == 1: # The official Gremlin documentation claims that this approach # is generally faster than the one below, since it makes using ...
Return a unicode object with the Gremlin representation of this block.
def check_forbidden_filename(filename, destiny_os=os.name, restricted_names=restricted_names): ''' Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_en...
Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (or filesystem) or not :rtype: bool
def assign_yourself(self): """ Assigning the workflow to itself. The selected job is checked to see if there is an assigned role. If it does not have a role assigned to it, it takes the job to itself and displays a message that the process is successful. ...
Assigning the workflow to itself. The selected job is checked to see if there is an assigned role. If it does not have a role assigned to it, it takes the job to itself and displays a message that the process is successful. If there is a role assigned to it, it does not d...
def eaSimpleConverge(population, toolbox, cxpb, mutpb, ngen, stats=None, halloffame=None, callback=None, verbose=True): """This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, a...
This algorithm reproduce the simplest evolutionary algorithm as presented in chapter 7 of [Back2000]_. Modified to allow checking if there is no change for ngen, as a simple rule for convergence. Interface is similar to eaSimple(). However, in eaSimple, ngen is total number of iterations; in eaSimpleCo...
def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs): """ Create the Signature TI object. Args: owner: file_content: file_name: file_type: name: **kwargs: Return: """ ...
Create the Signature TI object. Args: owner: file_content: file_name: file_type: name: **kwargs: Return: