Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
4,200
def get_url_from_model_core(request, obj): from is_core.site import get_model_core model_core = get_model_core(obj.__class__) if model_core and hasattr(model_core, ): edit_pattern = model_core.ui_patterns.get() return ( edit_pattern.get_url_string(request, obj=obj) ...
Returns object URL from model core.
4,201
def from_code(cls, co): 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() n = len(co_code) i = 0 extended_ar...
Disassemble a Python code object into a Code object.
4,202
def save_photon_hdf5(self, identity=None, overwrite=True, path=None): filepath = self.filepath if path is not None: filepath = Path(path, filepath.name) self.merge_da() data = self._make_photon_hdf5(identity=identity) phc.hdf5.save_photon_hdf5(data, h5_fname=...
Create a smFRET Photon-HDF5 file with current timestamps.
4,203
def quote_datetime(self, value): if value: if isinstance(value, type_check): self._quote_datetime = parse(value) elif isinstance(value, datetime.datetime): self._quote_datetime = value
Force the quote_datetime to always be a datetime :param value: :return:
4,204
def parse_ndxlist(output): m = NDXLIST.search(output) grouplist = m.group() return parse_groups(grouplist)
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...
4,205
def getBucketIndices(self, input): if input == SENTINEL_VALUE_FOR_MISSING_DATA: return [None] * len(self.encoders) else: assert isinstance(input, datetime.datetime) scalars = self.getScalars(input) result = [] for i in xrange(len(self.encoders)): ...
See method description in base.py
4,206
def contents(self, from_date=DEFAULT_DATETIME, offset=None, max_contents=MAX_CONTENTS): resource = self.RCONTENTS + + self.MSEARCH date = from_date.strftime("%Y-%m-%d %H:%M") cql = self.VCQL % {: date} params = { self.PCQL: cql, ...
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...
4,207
def apply_backspaces_and_linefeeds(text): orig_lines = text.split() orig_lines_len = len(orig_lines) new_lines = [] for orig_line_idx, orig_line in enumerate(orig_lines): chars, cursor = [], 0 orig_line_len = len(orig_line) for orig_char_idx, orig_char in enumerate(orig_line...
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.
4,208
def set_color_zones(self, start_index, end_index, color, duration=0, apply=1, callb=None, rapid=False): if len(color) == 4: args = { "start_index": start_index, "end_index": end_index, "color": color, "duration": duration, ...
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...
4,209
def latencies(self): return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.items()]
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)``.
4,210
def getargnames(argspecs, with_unbox=False): args = argspecs.args vargs = argspecs.varargs try: kw = argspecs.keywords except AttributeError: kw = argspecs.varkw try: kwonly = argspecs.kwonlyargs except AttributeError: kwonly = None res = [] if n...
Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args.
4,211
def context(fname, node): try: yield node except Exception: etype, exc, tb = sys.exc_info() msg = % ( striptag(node.tag), exc, getattr(node, , ), fname) raise_(etype, msg, tb)
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
4,212
def check_X_y(X, y): if len(X) != len(y): raise ValueError(\ .format(X.shape, y.shape))
tool to ensure input and output data have the same number of samples Parameters ---------- X : array-like y : array-like Returns ------- None
4,213
def filterOverlappingAlignments(alignments): l = [] alignments = alignments[:] sortAlignments(alignments) alignments.reverse() for pA1 in alignments: for pA2 in l: if pA1.contig1 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start1+1, pA2.e...
Filter alignments to be non-overlapping.
4,214
def _gridmake2(x1, x2): if x1.ndim == 1 and x2.ndim == 1: return np.column_stack([np.tile(x1, x2.shape[0]), np.repeat(x2, x1.shape[0])]) elif x1.ndim > 1 and x2.ndim == 1: first = np.tile(x1, (x2.shape[0], 1)) second = np.repeat(x2, x1.shape[0]) ...
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...
4,215
def ensure_path(path): if isinstance(path, vistir.compat.Path): return path path = vistir.compat.Path(os.path.expandvars(path)) return path.absolute()
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`
4,216
def load(self, dump_fn=, prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None, force_host=None): r = self.database_renderer(name=name, site=site) r.env.dump_fn = self.get_default_db_fn(fn_template=dump_fn, dest_dir=dest_dir) from_local = int(from_lo...
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.
4,217
def _query(self, *criterion): return self.session.query( self.model_class ).filter( *criterion )
Construct a query for the model.
4,218
def p_arguments(self, p): 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
4,219
def destroy(self, request, *args, **kwargs): 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.
4,220
def update_all(self, criteria: Q, *args, **kwargs): items = self._filter(criteria, self.conn[][self.schema_name]) update_count = 0 for key in items: item = items[key] item.update(*args) item.update(kwargs) self.conn[][self.schema_name][ke...
Update all objects satisfying the criteria
4,221
def decode(self, descriptor): i = iter(descriptor) n = len(self._schema) schema = self._schema + (,) tuple_gen = (tuple(itertools.islice(i, n)) + (d, ) for d in self._dimensions) return [{ k: v for k, v in zip(sc...
Produce a list of dictionaries for each dimension in this transcoder
4,222
def write(self, process_tile, data): if data is None or len(data) == 0: return if not isinstance(data, (list, types.GeneratorType)): raise TypeError( "GeoJSON driver data has to be a list or generator of GeoJSON objects" ) data = list...
Write data from process tiles into GeoJSON file(s). Parameters ---------- process_tile : ``BufferedTile`` must be member of process ``TilePyramid``
4,223
def get_comparable_values_for_ordering(self): 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
4,224
def get_releasenotes(repo_path, from_commit=None, bugtracker_url=): repo = dulwich.repo.Repo(repo_path) tags = get_tags(repo) refs = get_refs(repo) maj_version = 0 feat_version = 0 fix_version = 0 start_including = False release_notes_per_major = OrderedDict() cur_line = i...
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...
4,225
def copyFile(src, dest): try: if os.path.isfile(src): dpath, dfile = os.path.split(dest) if not os.path.isdir(dpath): os.makedirs(dpath) if not os.path.exists(dest): touch(dest) try: shutil.copy2(src,...
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)
4,226
def cmd_example(self, args): 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.usage())
control behaviour of the module
4,227
def __process_node(self, node: yaml.Node, expected_type: Type) -> yaml.Node: logger.info(.format( node, expected_type)) recognized_types, message = self.__recognizer.recognize( node, expected_type) if len(recognized_types) != 1: ...
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. ...
4,228
def astype(self, dtype): if dtype not in _supported_dtypes: raise ValueError( % (dtype, _supported_dtypes)) pixeltype = _npy_to_itk_map[dtype] return self.clone(pixeltype)
Cast & clone an ANTsImage to a given numpy datatype. Map: uint8 : unsigned char uint32 : unsigned int float32 : float float64 : double
4,229
def _parse(self): try: self.vars[] = self.json[] except (KeyError, ValueError, TypeError): pass for v in [, ]: try: self.vars[v] = self.summarize_notices(self.json[v]) except (KeyError, ValueError, TypeError): ...
The function for parsing the JSON response to the vars dictionary.
4,230
def to_schema(self): if not self.name or not self.process: raise ValueError("field is not registered with process") schema = { : self.name, : self.get_field_type(), } if self.required is not None: schema[] = self.required ...
Return field schema for this field.
4,231
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=, distance=, gold=None): visualweightpolar_angle_1pola...
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...
4,232
def get_neuroml_from_sonata(sonata_filename, id, generate_lems = True, format=): from neuroml.hdf5.NetworkBuilder import NetworkBuilder neuroml_handler = NetworkBuilder() sr = SonataReader(filename=sonata_filename, id=id) sr.parse(neuroml_handler) nml_doc...
Return a NeuroMLDocument with (most of) the contents of the Sonata model
4,233
def attr_subresource(raml_resource, route_name): static_parent = get_static_parent(raml_resource, method=) if static_parent is None: return False schema = resource_schema(static_parent) or {} properties = schema.get(, {}) if route_name in properties: db_settings = properties[rou...
Determine if :raml_resource: is an attribute subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:.
4,234
def root_sync(args, l, config): 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("Sync with {} remotes or bundles ".format(len(remotes))) if not re...
Sync with the remote. For more options, use library sync
4,235
def has_minimum_version(raises=True): if get_version() < LooseVersion(TMUX_MIN_VERSION): if raises: raise exc.VersionTooLow( % (TMUX_MIN_VERSION, get_version()) ) else: return False return 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. Raises ------ libtmux.exc.VersionTooLow ...
4,236
def fingerprint(self): if self._fingerprint is None: params = self[][] key = self[].parsed if self.algorithm == : to_hash = % ( key[].native, key[].native, ) elif self.algorithm =...
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...
4,237
def genlmsg_parse(nlh, hdrlen, tb, maxtype, policy): if not genlmsg_valid_hdr(nlh, hdrlen): return -NLE_MSG_TOOSHORT ghdr = genlmsghdr(nlmsg_data(nlh)) return int(nla_parse(tb, maxtype, genlmsg_attrdata(ghdr, hdrlen), genlmsg_attrlen(ghdr, hdrlen), 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 message payload to parse eventual attributes. Positional a...
4,238
def draw_heading(self, writer): if self.dirty == self.STATE_REFRESH: writer(u.join( (self.term.home, self.term.clear, self.screen.msg_intro, , self.screen.header, ,))) return True
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...
4,239
def get_background_rms(self): if self._rms is None: data = numpy.extract(self.hdu.data > -9999999, self.hdu.data) p25 = scipy.stats.scoreatpercentile(data, 25) p75 = scipy.stats.scoreatpercentile(data, 75) iqr = p75...
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.
4,240
def top_referrers(self, domain_only=True): referrer = self._referrer_clause(domain_only) return (self.get_query() .select(referrer, fn.Count(PageView.id)) .group_by(referrer) .order_by(fn.Count(PageView.id).desc()) .tuples())
What domains send us the most traffic?
4,241
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): if bac...
read all data
4,242
def get_closest(self, lon, lat, depth=0): xyz = spherical_to_cartesian(lon, lat, depth) min_dist, idx = self.kdtree.query(xyz) return self.objects[idx], min_dist
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)
4,243
def add_forwarding_rules(self, forwarding_rules): rules_dict = [rule.__dict__ for rule in forwarding_rules] return self.get_data( "load_balancers/%s/forwarding_rules/" % self.id, type=POST, params={"forwarding_rules": rules_dict} )
Adds new forwarding rules to a LoadBalancer. Args: forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
4,244
def move_item(self, item, origin, destination): if self.equality: item_index = 0 for i, element in enumerate(origin): if self.equality(element, item): item_index = i break else: item_index = origin.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.
4,245
def saveSession(self): if self.cookies_file: self.r.cookies.save(ignore_discard=True) with open(self.token_file, ) as f: f.write( % (self.token_type, self.access_token))
Save cookies/session.
4,246
def edit_message_media( self, chat_id: Union[int, str], message_id: int, media: InputMedia, reply_markup: "pyrogram.InlineKeyboardMarkup" = None ) -> "pyrogram.Message": style = self.html if media.parse_mode.lower() == "html" else self.markdown captio...
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 ...
4,247
def addsystemhook(self, url): data = {"url": url} request = requests.post( self.hook_url, headers=self.headers, data=data, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 201: return True else: ...
Add a system hook :param url: url of the hook :return: True if success
4,248
def set(self, data, start=None, count=None, stride=None): try: sds_name, rank, dim_sizes, data_type, n_attrs = self.info() if isinstance(dim_sizes, type(1)): dim_sizes = [dim_sizes] except HDF4Error: raise HDF4Error() ...
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...
4,249
def format_help(self, description): for bold in ("``", "*"): parts = [] if description is None: description = "" for i, s in enumerate(description.split(bold)): parts.append(s if i % 2 == 0 else "<b>%s</b>" % s) description...
Format the setting's description into HTML.
4,250
def mkdir(self, name=None, folder_id=): return self( , method=, encode=, 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.
4,251
def explode_line(argument_line: str) -> typing.Tuple[str, str]: 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
4,252
def obtain_licenses(): with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute() licenses = {r[0]: r[1] for r in cursor.fetchall()} return licenses
Obtain the licenses in a dictionary form, keyed by url.
4,253
def get_key_codes(keys): keys = keys.strip().upper().split() codes = list() for key in keys: code = ks_settings.KEY_CODES.get(key.strip()) if code: codes.append(code) return codes
Calculates the list of key codes from a string with key combinations. Ex: 'CTRL+A' will produce the output (17, 65)
4,254
def predict(self, Xnew=None, filteronly=False, include_likelihood=True, balance=None, **kw): if balance is None: p_balance = self.balance else: p_balance = balance (m, V) = self._raw_predict(Xnew,filteronly=filteronly, p_balance=p_b...
Inputs: ------------------ balance: bool Whether to balance or not the model as a whole
4,255
def with_(self, replacement): ensure_string(replacement) if is_mapping(self._replacements): raise ReplacementError("string replacements already provided") self._replacements = dict.fromkeys(self._replacements, replacement) return self
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
4,256
def process_summary(article): summary = article.summary summary_parsed = BeautifulSoup(summary, ) math = summary_parsed.find_all(class_=) if len(math) > 0: last_math_text = math[-1].get_text() if len(last_math_text) > 3 and last_math_text[-3:] == : content_parsed = Bea...
Ensures summaries are not cut off. Also inserts mathjax script so that math will be rendered
4,257
def add_untagged_ok(self, text: MaybeBytes, code: Optional[ResponseCode] = None) -> None: response = ResponseOk(b, text, code) self.add_untagged(response)
Add an untagged ``OK`` response. See Also: :meth:`.add_untagged`, :class:`ResponseOk` Args: text: The response text. code: Optional response code.
4,258
def disco_loop_asm_format(opc, version, co, real_out, fn_name_map, all_fns): if version < 3.0: co = code2compat(co) else: co = code3compat(co) co_name = co.co_name mapped_name = fn_name_map.get(co_name, co_name) new_consts = [] for c in co.co_con...
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.
4,259
def segments(self, **kwargs): segmentBase = self.segmentBase or self.walk_back_get_attr("segmentBase") segmentLists = self.segmentList or self.walk_back_get_attr("segmentList") segmentTemplate = self.segmentTemplate or self.walk_back_get_attr("segmentTemplate") if segmentTempl...
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 ...
4,260
def dump(obj, fp, **kw): r xml = dumps(obj, **kw) if isinstance(fp, basestring): with open(fp, ) as fobj: fobj.write(xml) else: fp.write(xml)
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...
4,261
def estimate_gas( self, block_identifier, function: str, *args, **kwargs, ) -> typing.Optional[int]: fn = getattr(self.contract.functions, function) address = to_checksum_address(self.jsonrpc_client.address) if self.jsonrpc...
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.
4,262
def handle_resourceset(ltext, **kwargs): fullprop=kwargs.get() rid=kwargs.get() base=kwargs.get(, VERSA_BASEIRI) model=kwargs.get() iris = ltext.strip().split() for i in iris: model.add(rid, fullprop, I(iri.absolutize(i, base))) return None
A helper that converts sets of resources from a textual format such as Markdown, including absolutizing relative IRIs
4,263
def is_lazy_user(user): if user.is_anonymous: return False backend = getattr(user, , None) if backend == : return True from lazysignup.models import LazyUser return bool(LazyUser.objects.filter(user=user).count() > 0)
Return True if the passed user is a lazy user.
4,264
def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"): if(self.dtype != str): raise TypeError("str_to_datetime expects SArray of str as input SArray") with cython_context(): return SArray(_proxy=self.__proxy__.str_to_datetime(format))
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...
4,265
def roi_pooling(input, rois, pool_height, pool_width): out = roi_pooling_module.roi_pooling(input, rois, pool_height=pool_height, pool_width=pool_width) output, argmax_output = out[0], out[1] return output
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
4,266
def calculate_size(name, sequence): data_size = 0 data_size += calculate_size_str(name) data_size += LONG_SIZE_IN_BYTES return data_size
Calculates the request payload size
4,267
def system_find_databases(input_params={}, always_retry=True, **kwargs): return DXHTTPRequest(, input_params, always_retry=always_retry, **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
4,268
def remove(parent, idx): 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.
4,269
def modified(self): try: dt = datetime.datetime.fromtimestamp(self.stats.st_mtime) return dt.strftime() except OSError: return None
Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str
4,270
def _init_create_child(self): if self._requires_pty(): self.create_child = mitogen.parent.hybrid_tty_create_child else: self.create_child = mitogen.parent.create_child self.create_child_args = { : True, }
Initialize the base class :attr:`create_child` and :attr:`create_child_args` according to whether we need a PTY or not.
4,271
def _save_state_and_schedule_next(self, shard_state, tstate, task_directive): spec = tstate.mapreduce_spec if task_directive == self._TASK_DIRECTIVE.DROP_TASK: return if task_directive in (self._TASK_DIRECTIVE.RETRY_SLICE, self._TASK_DIRECTIVE.RETRY_TASK): ...
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...
4,272
def _configure_context(ctx, opts, skip=()): for oper in opts: if oper in skip: continue if isinstance(oper,chartype): op = oper.encode("ascii") else: op = oper if isinstance(opts[oper],chartype): ...
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
4,273
def _lookup_vpc_count_min_max(session=None, **bfilter): if session is None: session = bc.get_reader_session() try: res = session.query( func.count(nexus_models_v2.NexusVPCAlloc.vpc_id), func.min(nexus_models_v2.NexusVPCAlloc.vpc_id), func.max(nexus_mode...
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.
4,274
def numDomtblout(domtblout, numHits, evalueT, bitT, sort): if sort is True: for hit in numDomtblout_sort(domtblout, numHits, evalueT, bitT): yield hit return header = [, , , , , , , , , , , , , , , , , , , , ,...
parse hmm domain table output this version is faster but does not work unless the table is sorted
4,275
def _get_config_instance(group_or_term, session, **kwargs): path = group_or_term._get_path() cached = group_or_term._top._cached_configs.get(path) if cached: config = cached created = False else: config, created = get_or_create(session, Config, **kwargs) return ...
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):
4,276
def register_master(): 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_info.server, device_info._class) if ...
Register the SDP Master device.
4,277
def prepare_batch(self): for _, metadata in self.certificates_to_issue.items(): self.certificate_handler.validate_certificate(metadata) with FinalizableSigner(self.secret_manager) as signer: for _, metadata in self.certificates_to_issue.items(): ...
Propagates exception on failure :return: byte array to put on the blockchain
4,278
def P_conditional(self, i, li, j, lj, y): Z = np.sum([self._P(i, _li, j, lj, y) for _li in range(self.k + 1)]) return self._P(i, li, j, lj, y) / Z
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 ...
4,279
def encoder_data(self, data): prev_val = self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE] val = int((data[self.MSB] << 7) + data[self.LSB]) if val > 8192: val -= 16384 pin = data[0] with self.pymata.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.
4,280
def process_user_record(cls, info): keys = list(info.keys()) for k in keys: v = info[k] if v in (, ): info[k] = None elif v == : info[k] = False elif v == : info[k] = True f...
Type convert the csv record, modifies in place.
4,281
def monkeypatch_method(cls, patch_name): def decorator(func): fname = func.__name__ old_func = getattr(cls, fname, None) if old_func is not None: old_ref = "_old_%s_%s" % (patch_name, fname) old_attr = getattr(cls, old_re...
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.
4,282
def to_python(self, omobj): if omobj.__class__ in self._omclass_to_py: return self._omclass_to_py[omobj.__class__](omobj) elif isinstance(omobj, om.OMSymbol): return self._lookup_to_python(omobj.cdbase, omobj.cd, omobj.name) elif isinst...
Convert OpenMath object to Python
4,283
def conv2d(self, filter_size, output_channels, stride=1, padding=, bn=True, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, trainable=True): self.count[] += 1 scope = + str(self.count[]) with tf.variable_scope(scope): input_channels = self.i...
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
4,284
def parse_message(self, msg, msg_signature, timestamp, nonce): content = self.crypto.decrypt_message(msg, msg_signature, timestamp, nonce) message = xmltodict.parse(to_text(content))[] message_type = message[].lower() message_class = COMPONENT_MESSAGE_TYPES.get(message_type, Com...
处理 wechat server 推送消息 :params msg: 加密内容 :params msg_signature: 消息签名 :params timestamp: 时间戳 :params nonce: 随机数
4,285
def html_visit_inheritance_diagram( self: NodeVisitor, node: inheritance_diagram ) -> None: inheritance_graph = node["graph"] urls = build_urls(self, node) graphviz_graph = inheritance_graph.build_graph(urls) dot_code = format(graphviz_graph, "graphviz") aspect_ratio = inheritance_grap...
Builds HTML output from an :py:class:`~uqbar.sphinx.inheritance.inheritance_diagram` node.
4,286
def split_fixed_pattern(path): _first_pattern_pos = path.find() _path_separator_pos = path.rfind(, 0, _first_pattern_pos) + 1 _path_fixed = path[:_path_separator_pos] _path_pattern = path[_path_separator_pos:] return _path_fixed, _path_pattern
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/ ...
4,287
def merge_errors(self, errors_local, errors_remote): for prop in errors_remote: return errors_local
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
4,288
def read_fastq(filename): if not filename: return itertools.cycle((None,)) if filename == "-": filename_fh = sys.stdin elif filename.endswith(): if is_python3: filename_fh = gzip.open(filename, mode=) else: filename_fh = BufferedReader(gzip.open(f...
return a stream of FASTQ entries, handling gzipped and empty files
4,289
def imprints2marc(self, key, value): return { : value.get(), : value.get(), : value.get(), }
Populate the ``260`` MARC field.
4,290
def preprocess(self, dataset, mode, hparams, interleave=True): def _preprocess(example): examples = self.preprocess_example(example, mode, hparams) if not isinstance(examples, tf.data.Dataset): examples = tf.data.Dataset.from_tensors(examples) return examples if interleave: ...
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...
4,291
def record_participation(self, client, dt=None): if dt is None: date = datetime.now() else: date = dt experiment_key = self.experiment.name pipe = self.redis.pipeline() pipe.sadd(_key("p:{0}:years".format(experiment_key)), date.strftime()) ...
Record a user's participation in a test along with a given variation
4,292
def _parse_members(self, contents, anexec, params, mode="insert"): members = self.vparser.parse(contents, anexec) for param in list(params): lparam = param.lower() if lparam in members: if mode == "insert" and not lparam in ane...
Parses the local variables for the contents of the specified executable.
4,293
def neg_int(i): 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.
4,294
def opener_from_zipfile(zipfile): def opener(filename): inner_file = zipfile.open(filename) if PY3: from io import TextIOWrapper return TextIOWrapper(inner_file) else: return inner_file return opener
Returns a function that will open a file in a zipfile by name. For Python3 compatibility, the raw file will be converted to text.
4,295
def get_letters( word ): ta_letters = list() not_empty = False WLEN,idx = len(word),0 while (idx < WLEN): c = word[idx] if c in uyir_letter_set or c == ayudha_letter: ta_letters.append(c) not_empty = True elif c in grantha_agaram_set: ...
splits the word into a character-list of tamil/english characters present in the stream
4,296
def dzip(items1, items2, cls=dict): try: len(items1) except TypeError: items1 = list(items1) try: len(items2) except TypeError: items2 = list(items2) if len(items1) == 0 and len(items2) == 1: items2 = [] if...
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...
4,297
def render(self, name, value, attrs=None, renderer=None): location = getattr(value, , ) if location and not hasattr(value, ): value.url = if hasattr(self, ): self.template_with_initial = ( ) ...
Include a hidden input to store the serialized upload value.
4,298
def parse_markdown(markdown_content, site_settings): markdown_extensions = set_markdown_extensions(site_settings) html_content = markdown.markdown( markdown_content, extensions=markdown_extensions, ) return html_content
Parse markdown text to html. :param markdown_content: Markdown text lists #TODO#
4,299
def _to_autoassign(self): autoassign_str = " "\t\t".join([str(i + 1) + "Dim" for i in range(len(self.labels))])) for peak_idx, peak in enumerate(self): dimensions_str = "\t\t".join([str(chemshift) for chemshift in peak.chemshifts_list]) autoassign_str += "{}...
Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string. :return: Peak list representation in AutoAssign format. :rtype: :py:class:`str`