positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def preview(self, page, filelike, format='png', dpi=72, background_colour=0xFFFFFF): """Render a preview image of a page. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] filelike: path or file-like object ...
Render a preview image of a page. Parameters ---------- page: positive integer Which page to render. Must be in the range [1, page_count] filelike: path or file-like object Can be a filename as a string, a Python file object, or something which behave...
def get_hardware_info(self): """ Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see structure :class:`Hardware...
Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for both CAN channels are returned separately. :return: Tuple with extended hardware information structure (see structure :class:`HardwareInfoEx`) and structures with informat...
def _mark_html_fields_as_safe(self, page): """ Mark the html content as safe so we don't have to use the safe template tag in all cms templates: """ page.title = mark_safe(page.title) page.content = mark_safe(page.content) return page
Mark the html content as safe so we don't have to use the safe template tag in all cms templates:
def get_perm_by_code(perm_code,**kwargs): """ Get a permission by its code """ try: perm = db.DBSession.query(Perm).filter(Perm.code==perm_code).one() return perm except NoResultFound: raise ResourceNotFoundError("Permission not found (perm_code={})".format(perm_code))
Get a permission by its code
def validate_current_password(self, value): """ current password check """ if self.instance and self.instance.has_usable_password() and not self.instance.check_password(value): raise serializers.ValidationError(_('Current password is not correct')) return value
current password check
def get_historical_info(self, symbol,items=None, startDate=None, endDate=None, limit=None): """get_historical_info() uses the csv datatable to retrieve all available historical data on a typical historical prices page """ startDate, endDate = self.__get_time_range(startDate, endDate) res...
get_historical_info() uses the csv datatable to retrieve all available historical data on a typical historical prices page
def load_module(filename): """ Loads a module by filename """ basename = os.path.basename(filename) path = os.path.dirname(filename) sys.path.append(path) # TODO(tlan) need to figure out how to handle errors thrown here return __import__(os.path.splitext(basename)[0])
Loads a module by filename
def silent(cmd, **kwargs): """Calls the given shell command. Output will not be displayed. Returns the status code. **Examples**: :: auxly.shell.silent("ls") """ return call(cmd, shell=True, stdout=NULL, stderr=NULL, **kwargs)
Calls the given shell command. Output will not be displayed. Returns the status code. **Examples**: :: auxly.shell.silent("ls")
def load_qrandom(): """ Loads a set of 10000 random numbers generated by qrandom. This dataset can be used when you want to do some limited tests with "true" random data without an internet connection. Returns: int array the dataset """ fname = "datasets/qrandom.npy" with pkg_resources.resou...
Loads a set of 10000 random numbers generated by qrandom. This dataset can be used when you want to do some limited tests with "true" random data without an internet connection. Returns: int array the dataset
def get_location(self, project_path, source, position, filename): """Return line number and file path where name under cursor is defined If line is None location wasn't finded. If file path is None, defenition is located in the same source. :param project_path: absolute project path ...
Return line number and file path where name under cursor is defined If line is None location wasn't finded. If file path is None, defenition is located in the same source. :param project_path: absolute project path :param source: unicode or byte string code source :param positi...
def to_subject_paths(paths): ''' to_subject_paths(paths) accepts either a string that is a :-separated list of directories or a list of directories and yields a list of all the existing directories. ''' if paths is None: return [] if pimms.is_str(paths): paths = paths.split(':') paths = [os...
to_subject_paths(paths) accepts either a string that is a :-separated list of directories or a list of directories and yields a list of all the existing directories.
def extendedEuclid(a, b): """return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b""" if a == 0: return b, 0, 1 else: g, y, x = extendedEuclid(b % a, a) return g, x - (b // a) * y, y
return a tuple of three values: x, y and z, such that x is the GCD of a and b, and x = y * a + z * b
def load_global_config(config_path): """ Load a global configuration object, and query for any required variables along the way """ config = configparser.RawConfigParser() if os.path.exists(config_path): logger.debug("Checking and setting global parameters...") config.read(config_path) e...
Load a global configuration object, and query for any required variables along the way
def _get_caller_globals_and_locals(): """ Returns the globals and locals of the calling frame. Is there an alternative to frame hacking here? """ caller_frame = inspect.stack()[2] myglobals = caller_frame[0].f_globals mylocals = caller_frame[0].f_locals return myglobals, mylocals
Returns the globals and locals of the calling frame. Is there an alternative to frame hacking here?
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list ...
Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :param big_endian: True for big endian/False for little ...
def GetElevation(self, latitude, longitude, timeout=0): '''Returns the altitude (m ASL) of a given lat/long pair, or None if unknown''' if latitude is None or longitude is None: return None if self.database == 'srtm': TileID = (numpy.floor(latitude), numpy.floor(longitude...
Returns the altitude (m ASL) of a given lat/long pair, or None if unknown
def factors(self): """ Access the factors :returns: twilio.rest.authy.v1.service.entity.factor.FactorList :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList """ if self._factors is None: self._factors = FactorList( self._version, ...
Access the factors :returns: twilio.rest.authy.v1.service.entity.factor.FactorList :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList
def log_progress(sequence, every=None, size=None, name='Items'): """Taken from https://github.com/alexanderkuk/log-progress""" from ipywidgets import IntProgress, HTML, VBox from IPython.display import display is_iterator = False if size is None: try: size = len(sequence) ...
Taken from https://github.com/alexanderkuk/log-progress
def quantile(self, q, dim=None, interpolation='linear'): """Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements. Parameters ---------- q : float in range of [0,1] (or sequence of floats) Quantile to ...
Compute the qth quantile of the data along the specified dimension. Returns the qth quantiles(s) of the array elements. Parameters ---------- q : float in range of [0,1] (or sequence of floats) Quantile to compute, which must be between 0 and 1 inclusive. ...
def authentication(self, username, password): """Configures the user authentication for eAPI This method configures the username and password combination to use for authenticating to eAPI. Args: username (str): The username to use to authenticate the eAPI co...
Configures the user authentication for eAPI This method configures the username and password combination to use for authenticating to eAPI. Args: username (str): The username to use to authenticate the eAPI connection with password (str): The password in...
def upsert(self, document, cond): """ Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a lis...
Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a list containing the updated document's ID
def getServiceNamesToTraceIds(self, time_stamp, service_name, rpc_name): """ Given a time stamp, server service name, and rpc name, fetch all of the client services calling in paired with the lists of every trace Ids (list<i64>) from the server to client. The three arguments specify epoch time in micro...
Given a time stamp, server service name, and rpc name, fetch all of the client services calling in paired with the lists of every trace Ids (list<i64>) from the server to client. The three arguments specify epoch time in microseconds, server side service name and rpc name. The return maps contains the key ...
def add_label(self, name, color): """Add a new label. It's id will automatically be calculated.""" color_upper = color.upper() if not self._color_re.match(color_upper): raise ValueError('Invalid color: {}'.format(color)) labels_tag = self.root[0] last_id = int(labels...
Add a new label. It's id will automatically be calculated.
def cut(self, name, disconnect=False): """ Cut a wire (undo a wire() call) Arguments: - name (str): name of the wire Keyword Arguments: - disconnect (bool): if True also disconnect all connections on the specified wire """ wir...
Cut a wire (undo a wire() call) Arguments: - name (str): name of the wire Keyword Arguments: - disconnect (bool): if True also disconnect all connections on the specified wire
def proxy_servers(self): """ Return the proxy servers available. First env variables will be searched and updated with values from condarc config file. """ proxy_servers = {} if self._load_rc_func is None: return proxy_servers else: ...
Return the proxy servers available. First env variables will be searched and updated with values from condarc config file.
def gantry_axes(cls) -> Tuple['Axis', 'Axis', 'Axis', 'Axis']: """ The axes which are tied to the gantry and require the deck calibration transform """ return (cls.X, cls.Y, cls.Z, cls.A)
The axes which are tied to the gantry and require the deck calibration transform
def to_dict(value, prefix=None, separators="=,"): """ Args: value: Value to turn into a dict prefix (str | unicode | None): Optional prefix for keys (if provided, `prefix.` is added to all keys) separators (str | unicode): 2 chars: 1st is assignment separator, 2nd is key-value pair separ...
Args: value: Value to turn into a dict prefix (str | unicode | None): Optional prefix for keys (if provided, `prefix.` is added to all keys) separators (str | unicode): 2 chars: 1st is assignment separator, 2nd is key-value pair separator Returns: (dict): Parse key/values
def add(connect_spec, dn, attributes): '''Add an entry to an LDAP database. :param connect_spec: See the documentation for the ``connect_spec`` parameter for :py:func:`connect`. :param dn: Distinguished name of the entry. :param attributes: Non-empty dict mapping each ...
Add an entry to an LDAP database. :param connect_spec: See the documentation for the ``connect_spec`` parameter for :py:func:`connect`. :param dn: Distinguished name of the entry. :param attributes: Non-empty dict mapping each of the new entry's attributes to a non...
def regexpr_validator(value): """ Test that ``value`` is a valid regular expression :param unicode value: A regular expression to test :raises ValidationError: if ``value`` is not a valid regular expression """ try: re.compile(value) except re.error: raise Valida...
Test that ``value`` is a valid regular expression :param unicode value: A regular expression to test :raises ValidationError: if ``value`` is not a valid regular expression
def hash(cls, path, digest=None, hasher=sha1): """Return the digest of a single file in a memory-efficient manner.""" if digest is None: digest = hasher() with open(path, 'rb') as fh: cls.update_hash(fh, digest) return digest.hexdigest()
Return the digest of a single file in a memory-efficient manner.
def download(self, streamed=False, action=None, chunk_size=1024, **kwargs): """Download the archive of a project export. Args: streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for reatment ...
Download the archive of a project export. Args: streamed (bool): If True the data will be processed by chunks of `chunk_size` and each chunk is passed to `action` for reatment action (callable): Callable responsible of dealing with chunk of ...
def nl_msg_in_handler_debug(msg, arg): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L114.""" ofd = arg or _LOGGER.debug ofd('-- Debug: Received Message:') nl_msg_dump(msg, ofd) return NL_OK
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L114.
def cancel_id(cls, id): """ Cancels command denoted by this id Args: `id`: command id """ conn = Qubole.agent() data = {"status": "kill"} return conn.put(cls.element_path(id), data)
Cancels command denoted by this id Args: `id`: command id
def getSonarData(self): ''' Returns last LaserData. @return last JdeRobotTypes LaserData saved ''' if self.hasproxy(): self.lock.acquire() sonar = self.sonar self.lock.release() return sonar return None
Returns last LaserData. @return last JdeRobotTypes LaserData saved
def set_comment(self, cellid, comment): """Saves the provided comment to the current dataset. :param cellid: number of the current cell :type cellid: int :param comment: a message to add documentation to data :type comment: str """ info = {'cellid': cellid, 'comm...
Saves the provided comment to the current dataset. :param cellid: number of the current cell :type cellid: int :param comment: a message to add documentation to data :type comment: str
def geom_dict_to_array_dict(geom_dict, coord_names=['Longitude', 'Latitude']): """ Converts a dictionary containing an geometry key to a dictionary of x- and y-coordinate arrays and if present a list-of-lists of hole array. """ x, y = coord_names geom = geom_dict['geometry'] new_dict = {...
Converts a dictionary containing an geometry key to a dictionary of x- and y-coordinate arrays and if present a list-of-lists of hole array.
def get_chrom_for_transcript(self, transcript_id, hgnc_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=gene".format(transcript_id) r = self.ense...
obtain the sequence for a transcript from ensembl
def from_parfiles(cls,pst,parfile_names,real_names=None): """ create a parameter ensemble from parfiles. Accepts parfiles with less than the parameters in the control (get NaNs in the ensemble) or extra parameters in the parfiles (get dropped) Parameters: pst : pyemu.Pst ...
create a parameter ensemble from parfiles. Accepts parfiles with less than the parameters in the control (get NaNs in the ensemble) or extra parameters in the parfiles (get dropped) Parameters: pst : pyemu.Pst parfile_names : list of str par file names ...
def _format(self, posts): """ This method is called by get_content() method""" if posts.__class__ == Post: # format a single post return posts.dict() formated_posts = [] for post in posts: formated_posts.append(post.dict()) return formated_post...
This method is called by get_content() method
def _set_buttons(self, chat, bot): """ Helper methods to set the buttons given the input sender and chat. """ if isinstance(self.reply_markup, ( types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)): self._buttons = [[ MessageButton(self._client...
Helper methods to set the buttons given the input sender and chat.
def get_functions_writing_to_variable(self, variable): ''' Return the functions writting the variable ''' return [f for f in self.functions if f.is_writing(variable)]
Return the functions writting the variable
def _save_one(self, model, ctx): """ Saves the created instance. """ assert isinstance(ctx, ResourceQueryContext) self._orm.add(model) self._orm.flush()
Saves the created instance.
def get_last_ticker(self, symbol, _async=False): """ 获取tradedetail :param symbol :return: """ params = {'symbol': symbol} url = u.MARKET_URL + '/market/trade' return http_get_request(url, params, _async=_async)
获取tradedetail :param symbol :return:
def getElementById(self, _id): ''' getElementById - Search children of this tag for a tag containing an id @param _id - String of id @return - AdvancedTag or None ''' for child in self.children: if child.getAttribute('id') == _id: ...
getElementById - Search children of this tag for a tag containing an id @param _id - String of id @return - AdvancedTag or None
def process_docopts(test=None): # type: (Optional[Dict[str,Any]])->None """ Just process the command line options and commands :return: """ if test: arguments = test else: arguments = docopt(__doc__, version="Jiggle Version {0}".format(__version__)) logger.debug(arguments) ...
Just process the command line options and commands :return:
def apmAggregate(self, **criteria): """collect all match history's apm data to report player's calculated MMR""" apms = [m.apm(self) for m in self.matchSubset(**criteria)] if not apms: return 0 # no apm information without match history return sum(apms) / len(apms)
collect all match history's apm data to report player's calculated MMR
def getOrderVectorEGMM(self): """ Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally. """ # We sort the candidates based o...
Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally.
def read_namespaced_replica_set(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set # noqa: E501 read the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=T...
read_namespaced_replica_set # noqa: E501 read the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set(name, namespace, async_req=True) ...
def free_source(self, name, free=True, pars=None, **kwargs): """Free/Fix parameters of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False) source parameters. par...
Free/Fix parameters of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False) source parameters. pars : list Set a list of parameters to be freed/fixed for this...
def antonym(phrase, format="json"): """ queries the bighugelabs API for the antonym. The results include - "syn" (synonym) - "ant" (antonym) - "rel" (related terms) - "sim" (similar terms) - "usr" (user suggestions) But currently parsing only the ant...
queries the bighugelabs API for the antonym. The results include - "syn" (synonym) - "ant" (antonym) - "rel" (related terms) - "sim" (similar terms) - "usr" (user suggestions) But currently parsing only the antonym as I have already done - synonym (using glo...
def modify_sub_vect_frags(self): "include repeated frags" modified_vect_frags = dict() init_vect_frags = self.sub_level.S_o_A_frags # init_max_id_d = init_vect_frags["id"].max() max_id_F = len(init_vect_frags["id"]) max_id_C = init_vect_frags["id_c"].max() + 1 #...
include repeated frags
def _read(self, pin): """Perform an ADC read. Returns the signed integer result of the read.""" config = _ADS1X15_CONFIG_OS_SINGLE config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET config |= _ADS1X15_CONFIG_GAIN[self.gain] config |= self.mode config |= self.rate_config...
Perform an ADC read. Returns the signed integer result of the read.
def contains(self, points): """ Given a set of points, determine whether or not they are inside the mesh. This raises an error if called on a non- watertight mesh. Parameters --------- points : (n, 3) float Points in cartesian space Returns ---...
Given a set of points, determine whether or not they are inside the mesh. This raises an error if called on a non- watertight mesh. Parameters --------- points : (n, 3) float Points in cartesian space Returns --------- contains : (n, ) bool W...
def iter_forks(self, number=-1, etag=None): """Iterator of forks of this gist. .. versionchanged:: 0.9 Added params ``number`` and ``etag``. :param int number: (optional), number of forks to iterate over. Default: -1 will iterate over all forks of this gist. :p...
Iterator of forks of this gist. .. versionchanged:: 0.9 Added params ``number`` and ``etag``. :param int number: (optional), number of forks to iterate over. Default: -1 will iterate over all forks of this gist. :param str etag: (optional), ETag from a previous request...
def transfer(self, name, cache_key=None): """ Transfers the file with the given name to the remote storage backend by queuing the task. :param name: file name :type name: str :param cache_key: the cache key to set after a successful task run :type cache_key: str ...
Transfers the file with the given name to the remote storage backend by queuing the task. :param name: file name :type name: str :param cache_key: the cache key to set after a successful task run :type cache_key: str :rtype: task result
def DiffDataObjects(self, oldObj, newObj): """Diff Data Objects""" if oldObj == newObj: return True if not oldObj or not newObj: __Log__.debug('DiffDataObjects: One of the objects in None') return False oldType = Type(oldObj) newType = Type(newObj) if oldTy...
Diff Data Objects
def open(filename=None, file=None, mode='r', suffix=None, options=None): """ Opens the archive at the specified *filename* or from the file-like object *file* using the appropriate opener. A specific opener can be specified by passing the *suffix* argument. # Parameters filename (str): A filename to open t...
Opens the archive at the specified *filename* or from the file-like object *file* using the appropriate opener. A specific opener can be specified by passing the *suffix* argument. # Parameters filename (str): A filename to open the archive from. file (file-like): A file-like object as source/destination. ...
def valid_zcta_or_raise(zcta): """ Check if ZCTA is valid and raise eeweather.UnrecognizedZCTAError if not. """ conn = metadata_db_connection_proxy.get_connection() cur = conn.cursor() cur.execute( """ select exists ( select zcta_id from zcta_metadata ...
Check if ZCTA is valid and raise eeweather.UnrecognizedZCTAError if not.
def get_sys_path(cls, python_path): """Get the :data:`sys.path` data for a given python executable. :param str python_path: Path to a specific python executable. :return: The system path information for that python runtime. :rtype: list """ command = [python_path, "-c",...
Get the :data:`sys.path` data for a given python executable. :param str python_path: Path to a specific python executable. :return: The system path information for that python runtime. :rtype: list
def update(self, byte_arr): """Read bytes and update the CRC computed.""" if byte_arr: self.value = self.calculate(byte_arr, self.value)
Read bytes and update the CRC computed.
def configure_discord_logger( self, discord_webhook=None, discord_recipient=None, log_level='ERROR', log_format=ReportingFormats.PRETTY_PRINT.value, custom_args='' ): """logger for sending messages to Discord. Easy way to alert humans ...
logger for sending messages to Discord. Easy way to alert humans of issues Note: Will try to overwrite minimum log level to enable requested log_level Will warn and not attach hipchat logger if missing webhook key Learn more about webhooks: https://support.discordapp.com/hc...
def project_graph(G, to_crs=None): """ Project a graph from lat-long to the UTM zone appropriate for its geographic location. Parameters ---------- G : networkx multidigraph the networkx graph to be projected to_crs : dict if not None, just project to this CRS instead of to ...
Project a graph from lat-long to the UTM zone appropriate for its geographic location. Parameters ---------- G : networkx multidigraph the networkx graph to be projected to_crs : dict if not None, just project to this CRS instead of to UTM Returns ------- networkx multi...
def bedInterval(self, who): "return a BED6 entry, thus DOES coordinate conversion for minus strands" if who == 't': st, en = self.tStart, self.tEnd if self.tStrand == '-': st, en = self.tSize-en, self.tSize-st return (self.tName, st, en, self.id, self...
return a BED6 entry, thus DOES coordinate conversion for minus strands
def cut(self): """ Cuts the selected text or the whole line if no text was selected. """ tc = self.textCursor() helper = TextHelper(self) tc.beginEditBlock() no_selection = False sText = tc.selection().toPlainText() if not helper.current_line_text(...
Cuts the selected text or the whole line if no text was selected.
def activate_conf_set(self, set_name): '''Activate a configuration set by name. @raises NoSuchConfSetError ''' with self._mutex: if not set_name in self.conf_sets: raise exceptions.NoSuchConfSetError(set_name) self._conf.activate_configuration_se...
Activate a configuration set by name. @raises NoSuchConfSetError
def _get_pidfile_path(self): """Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError """ if self.config.daemon.pidfile: pidfile = path.abspath(self.config.daemon....
Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError
def serialize_encryption_context(encryption_context): """Serializes the contents of a dictionary into a byte string. :param dict encryption_context: Dictionary of encrytion context keys/values. :returns: Serialized encryption context :rtype: bytes """ if not encryption_context: return b...
Serializes the contents of a dictionary into a byte string. :param dict encryption_context: Dictionary of encrytion context keys/values. :returns: Serialized encryption context :rtype: bytes
def meid(number, separator=u' '): ''' Printable Mobile Equipment Identifier (MEID) number. >>> print(meid(123456789012345678)) 1B 69B4BA 630F34 6 >>> print(meid('1B69B4BA630F34')) 1B 69B4BA 630F34 6 ''' if isinstance(number, six.string_types): number = re.sub(r'[\s-]', '', numb...
Printable Mobile Equipment Identifier (MEID) number. >>> print(meid(123456789012345678)) 1B 69B4BA 630F34 6 >>> print(meid('1B69B4BA630F34')) 1B 69B4BA 630F34 6
def capture(self, commit = ""): """Capture the current state of a project based on its provider Commit is relevant only for upstream providers. If empty, the latest commit from provider repository is taken. It is ignored for distribution providers. :param provider: project provider, e.g. upstream repository...
Capture the current state of a project based on its provider Commit is relevant only for upstream providers. If empty, the latest commit from provider repository is taken. It is ignored for distribution providers. :param provider: project provider, e.g. upstream repository, distribution builder :type provi...
def getWindowRect(self, hwnd): """ Returns a rect (x,y,w,h) for the specified window's area """ rect = ctypes.wintypes.RECT() if ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)): x1 = rect.left y1 = rect.top x2 = rect.right y2 = rect.bo...
Returns a rect (x,y,w,h) for the specified window's area
def _from_dict(cls, _dict): """Initialize a Expansions object from a json dictionary.""" args = {} if 'expansions' in _dict: args['expansions'] = [ Expansion._from_dict(x) for x in (_dict.get('expansions')) ] else: raise ValueError( ...
Initialize a Expansions object from a json dictionary.
def schema(ctx, schema): """ Load schema definitions from a YAML file. """ data = yaml.load(schema) if not isinstance(data, (list, tuple)): data = [data] with click.progressbar(data, label=schema.name) as bar: for schema in bar: ctx.obj['grano'].schemata.upsert(schema)
Load schema definitions from a YAML file.
def unserialize(wd: WordDictionary, text: Dict): """ Transforms back a serialized value of `serialize()` """ if not isinstance(text, Mapping): raise ValueError('Text has not the right format') try: t = text['type'] if t == 'string': return text['value'] ...
Transforms back a serialized value of `serialize()`
def scripts(cls, pkg, metadata, paths=[], **kwargs): """This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among scri...
This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among scripts against particular criteria. Its use is application specific...
def size(self): """Size is number of nodes under the trie, including the current node""" if self.children: return sum( ( c.size() for c in self.children.values() ) ) + 1 else: return 1
Size is number of nodes under the trie, including the current node
def volume_detach(self, name, timeout=300): ''' Detach a block device ''' try: volume = self.volume_show(name) except KeyError as exc: raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))...
Detach a block device
def cube(target, pore_diameter='pore.diameter', throat_area='throat.area'): r""" Calculates internal surface area of pore bodies assuming they are cubes then subtracts the area of the neighboring throats. Parameters ---------- target : OpenPNM Object The object for which these values ar...
r""" Calculates internal surface area of pore bodies assuming they are cubes then subtracts the area of the neighboring throats. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, a...
def _to_M8(key, tz=None): """ Timestamp-like => dt64 """ if not isinstance(key, Timestamp): # this also converts strings key = Timestamp(key) if key.tzinfo is not None and tz is not None: # Don't tz_localize(None) if key is already tz-aware key = key.tz_co...
Timestamp-like => dt64
def post_run_cell(self): """Runs after the user-entered code in a cell has been executed. It detects any new, decoratable objects that haven't been decorated yet and then decorates them. """ #We just want to detect any new, decoratable objects that haven't been #decorated...
Runs after the user-entered code in a cell has been executed. It detects any new, decoratable objects that haven't been decorated yet and then decorates them.
def require_server(fn): """ Checks if the user has called the task with a server name. Fabric tasks decorated with this decorator must be called like so:: fab <server name> <task name> If no server name is given, the task will not be executed. """ @wraps(fn) def wrapper(*args, **...
Checks if the user has called the task with a server name. Fabric tasks decorated with this decorator must be called like so:: fab <server name> <task name> If no server name is given, the task will not be executed.
def next(self): """ Where to redirect after authorization """ next = request.args.get('next') if next is None: params = self.default_redirect_params next = url_for(self.default_redirect_endpoint, **params) return next
Where to redirect after authorization
def validate_bool(b): """Convert b to a boolean or raise""" if isinstance(b, six.string_types): b = b.lower() if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False else: raise ValueEr...
Convert b to a boolean or raise
def to_dict(_dict, onts, mdb_safe=False): """ Convert a pysaml2 SAML2 message class instance into a basic dictionary format. The export interface. :param _dict: The pysaml2 metadata instance :param onts: List of schemas to use for the conversion :return: The converted information """ ...
Convert a pysaml2 SAML2 message class instance into a basic dictionary format. The export interface. :param _dict: The pysaml2 metadata instance :param onts: List of schemas to use for the conversion :return: The converted information
def pyoidcMiddleware(func): """Common wrapper for the underlying pyoidc library functions. Reads GET params and POST data before passing it on the library and converts the response from oic.utils.http_util to wsgi. :param func: underlying library function """ def wrapper(environ, start_response...
Common wrapper for the underlying pyoidc library functions. Reads GET params and POST data before passing it on the library and converts the response from oic.utils.http_util to wsgi. :param func: underlying library function
def all_states(n, big_endian=False): """Return all binary states for a system. Args: n (int): The number of elements in the system. big_endian (bool): Whether to return the states in big-endian order instead of little-endian order. Yields: tuple[int]: The next state of ...
Return all binary states for a system. Args: n (int): The number of elements in the system. big_endian (bool): Whether to return the states in big-endian order instead of little-endian order. Yields: tuple[int]: The next state of an ``n``-element system, in little-endian ...
def p_ifdef_else(p): """ ifdef : ifdefelsea ifdefelseb ENDIF """ global ENABLED p[0] = p[1] + p[2] p[0] += ['#line %i "%s"' % (p.lineno(3) + 1, CURRENT_FILE[-1])] ENABLED = IFDEFS[-1][0] IFDEFS.pop()
ifdef : ifdefelsea ifdefelseb ENDIF
def compute_heterozygosity(in_prefix, nb_samples): """Computes the heterozygosity ratio of samples (from tped).""" tped_name = in_prefix + ".tped" tfam_name = in_prefix + ".tfam" # The function we want to use check_heterozygosity = np.vectorize(is_heterozygous) # The autosomes autosomes = ...
Computes the heterozygosity ratio of samples (from tped).
def file_names(self) -> Iterable[str]: """Generates all file names that are used to generate file_handles. """ if self.is_sharded(): yield from ShardedFile(self.filename_spec).get_filenames() elif self.filename_spec: yield self.filename_spec
Generates all file names that are used to generate file_handles.
def simulate(args): """ %prog simulate run_dir 1 300 Simulate BAMs with varying inserts with dwgsim. The above command will simulate between 1 to 300 CAGs in the HD region, in a directory called `run_dir`. """ p = OptionParser(simulate.__doc__) p.add_option("--method", choices=("wgsim",...
%prog simulate run_dir 1 300 Simulate BAMs with varying inserts with dwgsim. The above command will simulate between 1 to 300 CAGs in the HD region, in a directory called `run_dir`.
def _slurm_info(queue): """Returns machine information for a slurm job scheduler. """ cl = "sinfo -h -p {} --format '%c %m %D'".format(queue) num_cpus, mem, num_nodes = subprocess.check_output(shlex.split(cl)).decode().split() # if the queue contains multiple memory configurations, the minimum value...
Returns machine information for a slurm job scheduler.
def monitor(self, timeout): """ Monitor the process, check whether it runs out of time. """ def check(self, timeout): time.sleep(timeout) self.stop() wather = threading.Thread(target=check) wather.setDaemon(True) wather.start()
Monitor the process, check whether it runs out of time.
def update(self): """Update swap memory stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Grab SWAP using the psutil swap_memory method sm_st...
Update swap memory stats using the input method.
def cal_pth(self, v, temp): """ calculate thermal pressure :param v: unit-cell volume in A^3 :param temp: temperature in K :return: thermal pressure in GPa """ params_t = self._set_params(self.params_therm) return constq_pth(v, temp, *params_t, self.n, se...
calculate thermal pressure :param v: unit-cell volume in A^3 :param temp: temperature in K :return: thermal pressure in GPa
def remove(self, line): """Delete all lines matching the given line.""" nb = 0 for block in self.blocks: nb += block.remove(line) return nb
Delete all lines matching the given line.
def feature_hash(feature, dim, seed=123): """Feature hashing. Args: feature (str): Target feature represented as string. dim (int): Number of dimensions for a hash value. seed (float): Seed of a MurmurHash3 hash function. Returns: numpy 1d array: one-hot-encoded feature vec...
Feature hashing. Args: feature (str): Target feature represented as string. dim (int): Number of dimensions for a hash value. seed (float): Seed of a MurmurHash3 hash function. Returns: numpy 1d array: one-hot-encoded feature vector for `s`.
def decomposed_diffusion_program(qubits: List[int]) -> Program: """ Constructs the diffusion operator used in Grover's Algorithm, acted on both sides by an a Hadamard gate on each qubit. Note that this means that the matrix representation of this operator is diag(1, -1, ..., -1). In particular, this dec...
Constructs the diffusion operator used in Grover's Algorithm, acted on both sides by an a Hadamard gate on each qubit. Note that this means that the matrix representation of this operator is diag(1, -1, ..., -1). In particular, this decomposes the diffusion operator, which is a :math:`2**{len(qubits)}\times...
def plotMatches2(listofNValues, errors, listOfScales, scaleErrors, fileName = "images/scalar_matches.pdf"): """ Plot two figures side by side in an aspect ratio appropriate for the paper. """ w, h = figaspect(0.4) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(w,h)) plotMat...
Plot two figures side by side in an aspect ratio appropriate for the paper.
def tpm(tpm, check_independence=True): """Validate a TPM. The TPM can be in * 2-dimensional state-by-state form, * 2-dimensional state-by-node form, or * multidimensional state-by-node form. """ see_tpm_docs = ( 'See the documentation on TPM conventions and the `pyphi.N...
Validate a TPM. The TPM can be in * 2-dimensional state-by-state form, * 2-dimensional state-by-node form, or * multidimensional state-by-node form.
def binary_operator(op): """ Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__. """ # When combining a Filter with a NumericalExpression, we use this # attrgetter instance...
Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__.
def get_rot(slab): """ Gets the transformation to rotate the z axis into the miller index """ new_z = get_mi_vec(slab) a, b, c = slab.lattice.matrix new_x = a / np.linalg.norm(a) new_y = np.cross(new_z, new_x) x, y, z = np.eye(3) rot_matrix = np.array([np.dot(*el) for el in ...
Gets the transformation to rotate the z axis into the miller index