code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_url_from_model_core(request, obj): """ Returns object URL from model core. """ from is_core.site import get_model_core model_core = get_model_core(obj.__class__) if model_core and hasattr(model_core, 'ui_patterns'): edit_pattern = model_core.ui_patterns.get('detail') ret...
Returns object URL from model core.
def from_code(cls, co): """Disassemble a Python code object into a Code object.""" co_code = co.co_code labels = dict((addr, Label()) for addr in findlabels(co_code)) linestarts = dict(cls._findlinestarts(co)) cellfree = co.co_cellvars + co.co_freevars code = CodeList() ...
Disassemble a Python code object into a Code object.
def save_photon_hdf5(self, identity=None, overwrite=True, path=None): """Create a smFRET Photon-HDF5 file with current timestamps.""" filepath = self.filepath if path is not None: filepath = Path(path, filepath.name) self.merge_da() data = self._make_photon_hdf5(ident...
Create a smFRET Photon-HDF5 file with current timestamps.
def quote_datetime(self, value): """ Force the quote_datetime to always be a datetime :param value: :return: """ if value: if isinstance(value, type_check): self._quote_datetime = parse(value) elif isinstance(value, datetime.datetim...
Force the quote_datetime to always be a datetime :param value: :return:
def parse_ndxlist(output): """Parse output from make_ndx to build list of index groups:: groups = parse_ndxlist(output) output should be the standard output from ``make_ndx``, e.g.:: rc,output,junk = gromacs.make_ndx(..., input=('', 'q'), stdout=False, stderr=True) (or simply use rc...
Parse output from make_ndx to build list of index groups:: groups = parse_ndxlist(output) output should be the standard output from ``make_ndx``, e.g.:: rc,output,junk = gromacs.make_ndx(..., input=('', 'q'), stdout=False, stderr=True) (or simply use rc,output,junk = cbook.make_ndx_capt...
def getBucketIndices(self, input): """ See method description in base.py """ if input == SENTINEL_VALUE_FOR_MISSING_DATA: # Encoder each sub-field return [None] * len(self.encoders) else: assert isinstance(input, datetime.datetime) # Get the scalar values for each sub-field ...
See method description in base.py
def contents(self, from_date=DEFAULT_DATETIME, offset=None, max_contents=MAX_CONTENTS): """Get the contents of a repository. This method returns an iterator that manages the pagination over contents. Take into account that the seconds of `from_date` parameter will be ig...
Get the contents of a repository. This method returns an iterator that manages the pagination over contents. Take into account that the seconds of `from_date` parameter will be ignored because the API only works with hours and minutes. :param from_date: fetch the contents updat...
def apply_backspaces_and_linefeeds(text): """ Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next ...
Interpret backspaces and linefeeds in text like a terminal would. Interpret text like a terminal by removing backspace and linefeed characters and applying them line by line. If final line ends with a carriage it keeps it to be concatenable with next output chunk.
def set_color_zones(self, start_index, end_index, color, duration=0, apply=1, callb=None, rapid=False): """Convenience method to set the colour status zone of the device This method will send a MultiZoneSetColorZones message to the device, and request callb be executed when an ACK is received. ...
Convenience method to set the colour status zone of the device This method will send a MultiZoneSetColorZones message to the device, and request callb be executed when an ACK is received. The default callback will simply cache the value. :param start_index: Index of the start of the zone o...
def latencies(self): """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.ite...
List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``.
def getargnames(argspecs, with_unbox=False): """Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args. """ # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: ...
Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args.
def context(fname, node): """ Context manager managing exceptions and adding line number of the current node and name of the current file to the error message. :param fname: the current file being processed :param node: the current node being processed """ try: yield node except...
Context manager managing exceptions and adding line number of the current node and name of the current file to the error message. :param fname: the current file being processed :param node: the current node being processed
def check_X_y(X, y): """ tool to ensure input and output data have the same number of samples Parameters ---------- X : array-like y : array-like Returns ------- None """ if len(X) != len(y): raise ValueError('Inconsistent input and output data shapes. '\ ...
tool to ensure input and output data have the same number of samples Parameters ---------- X : array-like y : array-like Returns ------- None
def filterOverlappingAlignments(alignments): """Filter alignments to be non-overlapping. """ l = [] alignments = alignments[:] sortAlignments(alignments) alignments.reverse() for pA1 in alignments: for pA2 in l: if pA1.contig1 == pA2.contig1 and getPositiveCoordinateRange...
Filter alignments to be non-overlapping.
def _gridmake2(x1, x2): """ Expands two vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- x1 : np.ndarray First vec...
Expands two vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays. Each column of the input arrays will correspond to one column of the output matrix. Parameters ---------- x1 : np.ndarray First vector to be expanded. x2 : np.nda...
def ensure_path(path): # type: (Union[vistir.compat.Path, str]) -> vistir.compat.Path """ Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fu...
Given a path (either a string or a Path object), expand variables and return a Path object. :param path: A string or a :class:`~pathlib.Path` object. :type path: str or :class:`~pathlib.Path` :return: A fully expanded Path object. :rtype: :class:`~pathlib.Path`
def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None, force_host=None): """ Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finall...
Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finally load the snapshot.
def _query(self, *criterion): """ Construct a query for the model. """ return self.session.query( self.model_class ).filter( *criterion )
Construct a query for the model.
def p_arguments(self, p): """arguments : LPAREN RPAREN | LPAREN argument_list RPAREN """ if len(p) == 4: p[0] = self.asttypes.Arguments(p[2]) else: p[0] = self.asttypes.Arguments([]) p[0].setpos(p)
arguments : LPAREN RPAREN | LPAREN argument_list RPAREN
def destroy(self, request, *args, **kwargs): """ Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item. Only customer owner and staff can delete price items. """ return super(PriceListItemViewSet, self).destroy(request, *args, **kwargs)
Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item. Only customer owner and staff can delete price items.
def update_all(self, criteria: Q, *args, **kwargs): """Update all objects satisfying the criteria """ items = self._filter(criteria, self.conn['data'][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.upda...
Update all objects satisfying the criteria
def decode(self, descriptor): """ Produce a list of dictionaries for each dimension in this transcoder """ i = iter(descriptor) n = len(self._schema) # Add the name key to our schema schema = self._schema + ('name',) # For each dimensions, generator takes n items off ite...
Produce a list of dictionaries for each dimension in this transcoder
def write(self, process_tile, data): """ Write data from process tiles into GeoJSON file(s). Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid`` """ if data is None or len(data) == 0: return ...
Write data from process tiles into GeoJSON file(s). Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid``
def get_comparable_values_for_ordering(self): """Return a tupple of values representing the unicity of the object """ return (0 if self.position >= 0 else 1, int(self.position), str(self.name), str(self.description))
Return a tupple of values representing the unicity of the object
def get_releasenotes(repo_path, from_commit=None, bugtracker_url=''): """ Given a repo and optionally a base revision to start from, will return a text suitable for the relase notes announcement, grouping the bugs, the features and the api-breaking changes. Args: repo_path(str): Path to the...
Given a repo and optionally a base revision to start from, will return a text suitable for the relase notes announcement, grouping the bugs, the features and the api-breaking changes. Args: repo_path(str): Path to the code git repository. from_commit(str): Refspec of the commit to start agg...
def copyFile(src, dest): """Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- Path for destination file (also a string) """ #Src Exists? try: if os.path.isfile(src): dpath, dfile = os.path...
Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- Path for destination file (also a string)
def cmd_example(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.status()) elif args[0] == "set": self.example_settings.command(args[1:]) else: print(self...
control behaviour of the module
def __process_node(self, node: yaml.Node, expected_type: Type) -> yaml.Node: """Processes a node. This is the main function that implements yatiml's \ functionality. It figures out how to interpret this node \ (recognition), then applies syntactic sugar, and final...
Processes a node. This is the main function that implements yatiml's \ functionality. It figures out how to interpret this node \ (recognition), then applies syntactic sugar, and finally \ recurses to the subnodes, if any. Args: node: The node to process. ...
def astype(self, dtype): """ Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double """ if dtype not in _supported_dtypes: raise ValueEr...
Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double
def _parse(self): """ The function for parsing the JSON response to the vars dictionary. """ try: self.vars['status'] = self.json['status'] except (KeyError, ValueError, TypeError): pass for v in ['remarks', 'notices']: try: ...
The function for parsing the JSON response to the vars dictionary.
def to_schema(self): """Return field schema for this field.""" if not self.name or not self.process: raise ValueError("field is not registered with process") schema = { 'name': self.name, 'type': self.get_field_type(), } if self.required is no...
Return field schema for this field.
def retinotopy_comparison(arg1, arg2, arg3=None, eccentricity_range=None, polar_angle_range=None, visual_area_mask=None, weight=Ellipsis, weight_min=None, visual_area=Ellipsis, method='rmse', distance='scaled', gold=None): ''' retinot...
retinotopy_comparison(dataset1, dataset2) yields a pimms itable comparing the two retinotopy datasets. retinotopy_error(obj, dataset1, dataset2) is equivalent to retinotopy_comparison(x, y) where x and y are retinotopy(obj, dataset1) and retinotopy_data(obj, dataset2). The datasets may be speci...
def get_neuroml_from_sonata(sonata_filename, id, generate_lems = True, format='xml'): """ Return a NeuroMLDocument with (most of) the contents of the Sonata model """ from neuroml.hdf5.NetworkBuilder import NetworkBuilder neuroml_handler = NetworkBuilder() sr = SonataReader(filename=s...
Return a NeuroMLDocument with (most of) the contents of the Sonata model
def attr_subresource(raml_resource, route_name): """ Determine if :raml_resource: is an attribute subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:. """ static_parent = get_static_parent(raml_resource, method='POST') i...
Determine if :raml_resource: is an attribute subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:.
def root_sync(args, l, config): """Sync with the remote. For more options, use library sync """ from requests.exceptions import ConnectionError all_remote_names = [ r.short_name for r in l.remotes ] if args.all: remotes = all_remote_names else: remotes = args.refs prt("Syn...
Sync with the remote. For more options, use library sync
def has_minimum_version(raises=True): """ Return if tmux meets version requirement. Version >1.8 or above. Parameters ---------- raises : bool raise exception if below minimum version requirement Returns ------- bool True if tmux meets minimum required version. Rai...
Return if tmux meets version requirement. Version >1.8 or above. Parameters ---------- raises : bool raise exception if below minimum version requirement Returns ------- bool True if tmux meets minimum required version. Raises ------ libtmux.exc.VersionTooLow ...
def fingerprint(self): """ Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selec...
Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the ke...
def genlmsg_parse(nlh, hdrlen, tb, maxtype, policy): """Parse Generic Netlink message including attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L191 Verifies the validity of the Netlink and Generic Netlink headers using genlmsg_valid_hdr() and calls nla_parse() on the mes...
Parse Generic Netlink message including attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L191 Verifies the validity of the Netlink and Generic Netlink headers using genlmsg_valid_hdr() and calls nla_parse() on the message payload to parse eventual attributes. Positional a...
def draw_heading(self, writer): """ Conditionally redraw screen when ``dirty`` attribute is valued REFRESH. When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved to (0,0), screen is cleared, and heading is displayed. :param writer: callable writes to output strea...
Conditionally redraw screen when ``dirty`` attribute is valued REFRESH. When Pager attribute ``dirty`` is ``STATE_REFRESH``, cursor is moved to (0,0), screen is cleared, and heading is displayed. :param writer: callable writes to output stream, receiving unicode. :returns: True if clas...
def get_background_rms(self): """ Calculate the rms of the image. The rms is calculated from the interqurtile range (IQR), to reduce bias from source pixels. Returns ------- rms : float The image rms. Notes ----- The rms value is cach...
Calculate the rms of the image. The rms is calculated from the interqurtile range (IQR), to reduce bias from source pixels. Returns ------- rms : float The image rms. Notes ----- The rms value is cached after first calculation.
def top_referrers(self, domain_only=True): """ What domains send us the most traffic? """ referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(...
What domains send us the most traffic?
def export_recordeddata_to_file(time_min=None, time_max=None, filename=None, active_vars=None, file_extension=None, append_to_file=False, no_mean_value=False, mean_value_period=5.0, backgroundprocess_id=None, export_task_id=None, **kwargs): """ rea...
read all data
def get_closest(self, lon, lat, depth=0): """ Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance) ...
Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance)
def add_forwarding_rules(self, forwarding_rules): """ Adds new forwarding rules to a LoadBalancer. Args: forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects """ rules_dict = [rule.__dict__ for rule in forwarding_rules] return self.get_data( ...
Adds new forwarding rules to a LoadBalancer. Args: forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
def move_item(self, item, origin, destination): """ Moves an item from one cluster to anoter cluster. :param item: the item to be moved. :param origin: the originating cluster. :param destination: the target cluster. """ if self.equality: item_index =...
Moves an item from one cluster to anoter cluster. :param item: the item to be moved. :param origin: the originating cluster. :param destination: the target cluster.
def saveSession(self): """Save cookies/session.""" if self.cookies_file: self.r.cookies.save(ignore_discard=True) with open(self.token_file, 'w') as f: f.write('%s %s' % (self.token_type, self.access_token))
Save cookies/session.
def edit_message_media( self, chat_id: Union[int, str], message_id: int, media: InputMedia, reply_markup: "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message": """Use this method to edit audio, document, photo, or video messages. If a message is a p...
Use this method to edit audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded ...
def addsystemhook(self, url): """ Add a system hook :param url: url of the hook :return: True if success """ data = {"url": url} request = requests.post( self.hook_url, headers=self.headers, data=data, verify=self.verify_ssl, auth=self.au...
Add a system hook :param url: url of the hook :return: True if success
def set(self, data, start=None, count=None, stride=None): """Write data to the dataset. Args:: data : array of data to write; can be given as a numpy array, or as Python sequence (whose elements can be imbricated sequences) start : indic...
Write data to the dataset. Args:: data : array of data to write; can be given as a numpy array, or as Python sequence (whose elements can be imbricated sequences) start : indices where to start writing in the dataset; default...
def format_help(self, description): """ Format the setting's description into HTML. """ for bold in ("``", "*"): parts = [] if description is None: description = "" for i, s in enumerate(description.split(bold)): parts.a...
Format the setting's description into HTML.
def mkdir(self, name=None, folder_id='0'): '''Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder.''' return self( 'folders', method='post', encode='json', data=dict(name=name, parent=dict(id=folder_id)) )
Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder.
def explode_line(argument_line: str) -> typing.Tuple[str, str]: """ Returns a tuple containing the parameter name and the description parsed from the given argument line """ parts = tuple(argument_line.split(' ', 1)[-1].split(':', 1)) return parts if len(parts) > 1 else (parts[0], '')
Returns a tuple containing the parameter name and the description parsed from the given argument line
def obtain_licenses(): """Obtain the licenses in a dictionary form, keyed by url.""" with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT combined_row.url, row_to_json(combined_row) FROM ( SELECT "code", "version", "name", "url", "is_valid_for_publicati...
Obtain the licenses in a dictionary form, keyed by url.
def get_key_codes(keys): """ Calculates the list of key codes from a string with key combinations. Ex: 'CTRL+A' will produce the output (17, 65) """ keys = keys.strip().upper().split('+') codes = list() for key in keys: code = ks_settings.KEY_CODES.get(key.strip()) if code: ...
Calculates the list of key codes from a string with key combinations. Ex: 'CTRL+A' will produce the output (17, 65)
def predict(self, Xnew=None, filteronly=False, include_likelihood=True, balance=None, **kw): """ Inputs: ------------------ balance: bool Whether to balance or not the model as a whole """ if balance is None: p_balance = self...
Inputs: ------------------ balance: bool Whether to balance or not the model as a whole
def with_(self, replacement): """Provide replacement for string "needles". :param replacement: Target replacement for needles given in constructor :return: The :class:`Replacement` object :raise TypeError: If ``replacement`` is not a string :raise ReplacementError: If replaceme...
Provide replacement for string "needles". :param replacement: Target replacement for needles given in constructor :return: The :class:`Replacement` object :raise TypeError: If ``replacement`` is not a string :raise ReplacementError: If replacement has been already given
def process_summary(article): """Ensures summaries are not cut off. Also inserts mathjax script so that math will be rendered""" summary = article.summary summary_parsed = BeautifulSoup(summary, 'html.parser') math = summary_parsed.find_all(class_='math') if len(math) > 0: last_math_te...
Ensures summaries are not cut off. Also inserts mathjax script so that math will be rendered
def add_untagged_ok(self, text: MaybeBytes, code: Optional[ResponseCode] = None) -> None: """Add an untagged ``OK`` response. See Also: :meth:`.add_untagged`, :class:`ResponseOk` Args: text: The response text. code: Optional response ...
Add an untagged ``OK`` response. See Also: :meth:`.add_untagged`, :class:`ResponseOk` Args: text: The response text. code: Optional response code.
def disco_loop_asm_format(opc, version, co, real_out, fn_name_map, all_fns): """Produces disassembly in a format more conducive to automatic assembly by producing inner modules before they are used by outer ones. Since this is recusive, we'll use more stack space at runtime. ...
Produces disassembly in a format more conducive to automatic assembly by producing inner modules before they are used by outer ones. Since this is recusive, we'll use more stack space at runtime.
def segments(self, **kwargs): """ Segments are yielded when they are available Segments appear on a time line, for dynamic content they are only available at a certain time and sometimes for a limited time. For static content they are all available at the same time. :param kwar...
Segments are yielded when they are available Segments appear on a time line, for dynamic content they are only available at a certain time and sometimes for a limited time. For static content they are all available at the same time. :param kwargs: extra args to pass to the segment template ...
def dump(obj, fp, **kw): r"""Dump python object to file. >>> import lazyxml >>> data = {'demo': {'foo': 1, 'bar': 2}} >>> lazyxml.dump(data, 'dump.xml') >>> with open('dump-fp.xml', 'w') as fp: >>> lazyxml.dump(data, fp) >>> from cStringIO import StringIO >>> data = {'demo': {'foo'...
r"""Dump python object to file. >>> import lazyxml >>> data = {'demo': {'foo': 1, 'bar': 2}} >>> lazyxml.dump(data, 'dump.xml') >>> with open('dump-fp.xml', 'w') as fp: >>> lazyxml.dump(data, fp) >>> from cStringIO import StringIO >>> data = {'demo': {'foo': 1, 'bar': 2}} >>> buffe...
def estimate_gas( self, block_identifier, function: str, *args, **kwargs, ) -> typing.Optional[int]: """Returns a gas estimate for the function with the given arguments or None if the function call will fail due to Insufficient funds or ...
Returns a gas estimate for the function with the given arguments or None if the function call will fail due to Insufficient funds or the logic in the called function.
def handle_resourceset(ltext, **kwargs): ''' A helper that converts sets of resources from a textual format such as Markdown, including absolutizing relative IRIs ''' fullprop=kwargs.get('fullprop') rid=kwargs.get('rid') base=kwargs.get('base', VERSA_BASEIRI) model=kwargs.get('model') ir...
A helper that converts sets of resources from a textual format such as Markdown, including absolutizing relative IRIs
def is_lazy_user(user): """ Return True if the passed user is a lazy user. """ # Anonymous users are not lazy. if user.is_anonymous: return False # Check the user backend. If the lazy signup backend # authenticated them, then the user is lazy. backend = getattr(user, 'backend', None) ...
Return True if the passed user is a lazy user.
def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to datetime. The string format is specified by the 'format' parameter. Parameters ---------- format : str The string format of the input SArray. Default ...
Create a new SArray with all the values cast to datetime. The string format is specified by the 'format' parameter. Parameters ---------- format : str The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP". If format is "ISO", the the for...
def roi_pooling(input, rois, pool_height, pool_width): """ returns a tensorflow operation for computing the Region of Interest Pooling @arg input: feature maps on which to perform the pooling operation @arg rois: list of regions of interest in the format (feature map index, upper left, bottom...
returns a tensorflow operation for computing the Region of Interest Pooling @arg input: feature maps on which to perform the pooling operation @arg rois: list of regions of interest in the format (feature map index, upper left, bottom right) @arg pool_width: size of the pooling sections
def calculate_size(name, sequence): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += LONG_SIZE_IN_BYTES return data_size
Calculates the request payload size
def system_find_databases(input_params={}, always_retry=True, **kwargs): """ Invokes the /system/findDatabases API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindDatabases """ return DXHTTPRequest('/system/findDatabases', input_pa...
Invokes the /system/findDatabases API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindDatabases
def remove(parent, idx): """Remove a value from a dict.""" if isinstance(parent, dict): del parent[idx] elif isinstance(parent, list): del parent[int(idx)] else: raise JSONPathError("Invalid path for operation")
Remove a value from a dict.
def modified(self): ''' Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str ''' try: dt = datetime.datetime.fromtimestamp(self.stats.st_mtime) return dt.strftime('%Y.%m.%d %H:%M:%S...
Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str
def _init_create_child(self): """ Initialize the base class :attr:`create_child` and :attr:`create_child_args` according to whether we need a PTY or not. """ if self._requires_pty(): self.create_child = mitogen.parent.hybrid_tty_create_child else: ...
Initialize the base class :attr:`create_child` and :attr:`create_child_args` according to whether we need a PTY or not.
def _save_state_and_schedule_next(self, shard_state, tstate, task_directive): """Save state and schedule task. Save shard state to datastore. Schedule next slice if needed. Set HTTP response code. No modification to any shard_state or tstate. Args: shard_state: model.ShardState for curre...
Save state and schedule task. Save shard state to datastore. Schedule next slice if needed. Set HTTP response code. No modification to any shard_state or tstate. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. task_direc...
def _configure_context(ctx, opts, skip=()): """ Configures context of public key operations @param ctx - context to configure @param opts - dictionary of options (from kwargs of calling function) @param skip - list of options which shouldn't be passed to c...
Configures context of public key operations @param ctx - context to configure @param opts - dictionary of options (from kwargs of calling function) @param skip - list of options which shouldn't be passed to context
def _lookup_vpc_count_min_max(session=None, **bfilter): """Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound. """ ...
Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound.
def numDomtblout(domtblout, numHits, evalueT, bitT, sort): """ parse hmm domain table output this version is faster but does not work unless the table is sorted """ if sort is True: for hit in numDomtblout_sort(domtblout, numHits, evalueT, bitT): yield hit return head...
parse hmm domain table output this version is faster but does not work unless the table is sorted
def _get_config_instance(group_or_term, session, **kwargs): """ Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool): """ ...
Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool):
def register_master(): """Register the SDP Master device.""" tango_db = Database() device = "sip_sdp/elt/master" device_info = DbDevInfo() device_info._class = "SDPMasterDevice" device_info.server = "sdp_master_ds/1" device_info.name = device devices = tango_db.get_device_name(device_inf...
Register the SDP Master device.
def prepare_batch(self): """ Propagates exception on failure :return: byte array to put on the blockchain """ # validate batch for _, metadata in self.certificates_to_issue.items(): self.certificate_handler.validate_certificate(metadata) # sign batch...
Propagates exception on failure :return: byte array to put on the blockchain
def P_conditional(self, i, li, j, lj, y): """Compute the conditional probability P_\theta(li | lj, y) = Z^{-1} exp( theta_{i|y} \indpm{ \lambda_i = Y } + \theta_{i,j} \indpm{ \lambda_i = \lambda_j } ) In other words, compute...
Compute the conditional probability P_\theta(li | lj, y) = Z^{-1} exp( theta_{i|y} \indpm{ \lambda_i = Y } + \theta_{i,j} \indpm{ \lambda_i = \lambda_j } ) In other words, compute the conditional probability that LF i outputs ...
def encoder_data(self, data): """ This method handles the incoming encoder data message and stores the data in the digital response table. :param data: Message data from Firmata :return: No return value. """ prev_val = self.digital_response_table[data[self.RESPO...
This method handles the incoming encoder data message and stores the data in the digital response table. :param data: Message data from Firmata :return: No return value.
def process_user_record(cls, info): """Type convert the csv record, modifies in place.""" keys = list(info.keys()) # Value conversion for k in keys: v = info[k] if v in ('N/A', 'no_information'): info[k] = None elif v == 'false': ...
Type convert the csv record, modifies in place.
def monkeypatch_method(cls, patch_name): # This function's code was inspired from the following thread: # "[Python-Dev] Monkeypatching idioms -- elegant or ugly?" # by Robert Brewer <fumanchu at aminus.org> # (Tue Jan 15 19:13:25 CET 2008) """ Add the decorated method to the given class; r...
Add the decorated method to the given class; replace as needed. If the named method already exists on the given class, it will be replaced, and a reference to the old method is created as cls._old<patch_name><name>. If the "_old_<patch_name>_<name>" attribute already exists, KeyError is raised.
def to_python(self, omobj): """ Convert OpenMath object to Python """ # general overrides if omobj.__class__ in self._omclass_to_py: return self._omclass_to_py[omobj.__class__](omobj) # oms elif isinstance(omobj, om.OMSymbol): return self._lookup_to_python...
Convert OpenMath object to Python
def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', bn=True, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, trainable=True): """ 2D Convolutional Layer. :param filter_size: int. assumes square filter :param output_channels: int :param stri...
2D Convolutional Layer. :param filter_size: int. assumes square filter :param output_channels: int :param stride: int :param padding: 'VALID' or 'SAME' :param activation_fn: tf.nn function :param b_value: float :param s_value: float
def parse_message(self, msg, msg_signature, timestamp, nonce): """ 处理 wechat server 推送消息 :params msg: 加密内容 :params msg_signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数 """ content = self.crypto.decrypt_message(msg, msg_signature, timestamp, nonce...
处理 wechat server 推送消息 :params msg: 加密内容 :params msg_signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数
def html_visit_inheritance_diagram( self: NodeVisitor, node: inheritance_diagram ) -> None: """ Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node. """ inheritance_graph = node["graph"] urls = build_urls(self, node) graphviz_graph = inheritance_graph.bu...
Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
def split_fixed_pattern(path): """ Split path into fixed and masked parts :param path: e.g https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz :return: _path_fixed: https://repo.example.com/artifactory/li...
Split path into fixed and masked parts :param path: e.g https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/*.*.*/vc110/x86/win/boost.*.*.*.tar.gz :return: _path_fixed: https://repo.example.com/artifactory/libs-cpp-release.snapshot/boost/1.60-pm/ ...
def merge_errors(self, errors_local, errors_remote): """ Merge errors Recursively traverses error graph to merge remote errors into local errors to return a new joined graph. :param errors_local: dict, local errors, will be updated :param errors_remote: dict, remote erro...
Merge errors Recursively traverses error graph to merge remote errors into local errors to return a new joined graph. :param errors_local: dict, local errors, will be updated :param errors_remote: dict, remote errors, provides updates :return: dict
def read_fastq(filename): """ return a stream of FASTQ entries, handling gzipped and empty files """ if not filename: return itertools.cycle((None,)) if filename == "-": filename_fh = sys.stdin elif filename.endswith('gz'): if is_python3: filename_fh = gzip.op...
return a stream of FASTQ entries, handling gzipped and empty files
def imprints2marc(self, key, value): """Populate the ``260`` MARC field.""" return { 'a': value.get('place'), 'b': value.get('publisher'), 'c': value.get('date'), }
Populate the ``260`` MARC field.
def preprocess(self, dataset, mode, hparams, interleave=True): """Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preproc...
Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preprocessed features. mode: tf.estimator.ModeKeys hparams: HPara...
def record_participation(self, client, dt=None): """Record a user's participation in a test along with a given variation""" if dt is None: date = datetime.now() else: date = dt experiment_key = self.experiment.name pipe = self.redis.pipeline() p...
Record a user's participation in a test along with a given variation
def _parse_members(self, contents, anexec, params, mode="insert"): """Parses the local variables for the contents of the specified executable.""" #First get the variables declared in the body of the executable, these can #be either locals or parameter declarations. members = self.vparser...
Parses the local variables for the contents of the specified executable.
def neg_int(i): """ Simple negative integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i > 0: raise Exception() except: raise ValueError("Not a negative integer") return i
Simple negative integer validation.
def opener_from_zipfile(zipfile): """ Returns a function that will open a file in a zipfile by name. For Python3 compatibility, the raw file will be converted to text. """ def opener(filename): inner_file = zipfile.open(filename) if PY3: from io import TextIOWrapper ...
Returns a function that will open a file in a zipfile by name. For Python3 compatibility, the raw file will be converted to text.
def get_letters( word ): """ splits the word into a character-list of tamil/english characters present in the stream """ ta_letters = list() not_empty = False WLEN,idx = len(word),0 while (idx < WLEN): c = word[idx] #print(idx,hex(ord(c)),len(ta_letters)) if c in uyir_let...
splits the word into a character-list of tamil/english characters present in the stream
def dzip(items1, items2, cls=dict): """ Zips elementwise pairs between items1 and items2 into a dictionary. Values from items2 can be broadcast onto items1. Args: items1 (Iterable): full sequence items2 (Iterable): can either be a sequence of one item or a sequence of equal ...
Zips elementwise pairs between items1 and items2 into a dictionary. Values from items2 can be broadcast onto items1. Args: items1 (Iterable): full sequence items2 (Iterable): can either be a sequence of one item or a sequence of equal length to `items1` cls (Type[dict]): dic...
def render(self, name, value, attrs=None, renderer=None): """Include a hidden input to store the serialized upload value.""" location = getattr(value, '_seralized_location', '') if location and not hasattr(value, 'url'): value.url = '#' if hasattr(self, 'get_template_subs...
Include a hidden input to store the serialized upload value.
def parse_markdown(markdown_content, site_settings): """Parse markdown text to html. :param markdown_content: Markdown text lists #TODO# """ markdown_extensions = set_markdown_extensions(site_settings) html_content = markdown.markdown( markdown_content, extensions=markdown_extensio...
Parse markdown text to html. :param markdown_content: Markdown text lists #TODO#
def _to_autoassign(self): """Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str` """ autoassign_str = "#Index\t\t{}\t\tIntensity\t\tWorkbook\n".format( "\t\t"...
Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str`