Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
372,400
def get_settings_json(self): return { : None if self.scanner is None else self.scanner.save(), : None if self.parser is None else self.parser.save() }
Convert generator settings to JSON. Returns ------- `dict` JSON data.
372,401
def isTagEqual(self, other): something try: if self.tagName != other.tagName: return False myAttributes = self._attributes otherAttributes = other._attributes attributeKeysSelf = list(myAttributes.keys()) attributeKeysOth...
isTagEqual - Compare if a tag contains the same tag name and attributes as another tag, i.e. if everything between < and > parts of this tag are the same. Does NOT compare children, etc. Does NOT compare if these are the same exact tag in the html (use regular == operator for that) ...
372,402
def ackermann_naive(m: int, n: int) -> int: if m == 0: return n + 1 elif n == 0: return ackermann(m - 1, 1) else: return ackermann(m - 1, ackermann(m, n - 1))
Ackermann number.
372,403
def hsvToRGB(h, s, v): hi = math.floor(h / 60.0) % 6 f = (h / 60.0) - math.floor(h / 60.0) p = v * (1.0 - s) q = v * (1.0 - (f * s)) t = v * (1.0 - ((1.0 - f) * s)) D = {0: (v, t, p), 1: (q, v, p), 2: (p, v, t), 3: (p, q, v), 4: (t, p, v), 5: (v, p, q)} return D[hi]
Convert HSV (hue, saturation, value) color space to RGB (red, green blue) color space. **Parameters** **h** : float Hue, a number in [0, 360]. **s** : float Saturation, a number in [0, 1]. **v** : float Va...
372,404
def blockType(self, kind): NBLTYPES = self.verboseRead(TypeCountAlphabet( +kind[0].upper(), description=.format(kind), )) self.numberOfBlockTypes[kind] = NBLTYPES if NBLTYPES>=2: self.blockTypeCodes[kind] = self.readPrefixCode( ...
Read block type switch descriptor for given kind of blockType.
372,405
def _initAsteriskVersion(self): if self._ami_version > util.SoftwareVersion(): cmd = "core show version" else: cmd = "show version" cmdresp = self.executeCommand(cmd) mobj = re.match(, cmdresp) if mobj: self._asterisk_version = util.So...
Query Asterisk Manager Interface for Asterisk Version to configure system for compatibility with multiple versions . CLI Command - core show version
372,406
def set_back(self, x: int, y: int, r: int, g: int, b: int) -> None: i = self.width * y + x self.back_r[i] = r self.back_g[i] = g self.back_b[i] = b
Set the background color of one cell. Args: x (int): X position to change. y (int): Y position to change. r (int): Red background color, from 0 to 255. g (int): Green background color, from 0 to 255. b (int): Blue background color, from 0 to 255.
372,407
def _save_np(obj, pathfileext, compressed=False): func = np.savez_compressed if compressed else np.savez dId = obj.Id._todict() if obj.Id.Cls==: func(pathfileext, Id=dId, arrayorder=obj._arrayorder, Clock=obj._Clock, Poly=obj.Poly, Lim=obj.Lim, Sino_RefPt=obj.sino[], ...
elif obj.Id.Cls=='GLOS': LIdLOS = [ll.Id.todict() for ll in obj.LLOS] LDs, Lus = np.array([ll.D for ll in obj.LLOS]).T, np.array([ll.u for ll in obj.LLOS]).T func(pathfileext, Idsave=Idsave, LIdLOS=LIdLOS, LDs=LDs, Lus=Lus, Sino_RefPt=obj.Sino_RefPt, arrayorder=obj._arrayorder, Clock=obj._Clock)...
372,408
def check_authorization(self): try: store = self.__config.get() if store is None: return True auth_info = self.headers.get() if not auth_info: return False auth_info = auth_info.split() if len(auth_info) != 2 or auth_info[0] != : return False auth_info = base64.b64decode(auth_info[...
Check for the presence of a basic auth Authorization header and if the credentials contained within in are valid. :return: Whether or not the credentials are valid. :rtype: bool
372,409
def surface_nodes(self): line = [] for point in self.mesh: line.append(point.longitude) line.append(point.latitude) line.append(point.depth) return [Node(, nodes=[Node(, {}, line)])]
:param points: a list of Point objects :returns: a Node of kind 'griddedSurface'
372,410
def _post_deactivate_injection(self): self.active = False self.app.signals.send("plugin_deactivate_post", self) self.signals.deactivate_plugin_signals()
Injects functions after the deactivation routine of child classes got called :return: None
372,411
def omegac(self,R): return nu.sqrt(-self.Rforce(R,use_physical=False)/R)
NAME: omegac PURPOSE: calculate the circular angular speed at R in potential Pot INPUT: Pot - Potential instance or list of such instances R - Galactocentric radius (can be Quantity) OUTPUT: ...
372,412
def log(self, level, prefix = ): logging.log(level, "%sname: %s", prefix, self.__name) logging.log(level, "%soptions: %s", prefix, self.__options)
Writes the contents of the Extension to the logging system.
372,413
def _parse_sid_response(res): res = json.loads(list(ChunkParser().get_chunks(res))[0]) sid = res[0][1][1] gsessionid = res[1][1][0][] return (sid, gsessionid)
Parse response format for request for new channel SID. Example format (after parsing JS): [ [0,["c","SID_HERE","",8]], [1,[{"gsid":"GSESSIONID_HERE"}]]] Returns (SID, gsessionid) tuple.
372,414
def gettext(ui_file_path): with open(ui_file_path, ) as fin: content = fin.read() content = re.sub(r, , content) content = content.replace( , ) with open(ui_file_path, ) as fout: fout.write(content)
Let you use gettext instead of the Qt tools for l18n
372,415
def get_perceel_by_id_and_sectie(self, id, sectie): sid = sectie.id aid = sectie.afdeling.id gid = sectie.afdeling.gemeente.id sectie.clear_gateway() def creator(): url = self.base_url + % ( gid, aid, sid, id) h = self.base_headers ...
Get a `perceel`. :param id: An id for a `perceel`. :param sectie: The :class:`Sectie` that contains the perceel. :rtype: :class:`Perceel`
372,416
def download_wiki(): ambiguous = [i for i in l.UNITS.items() if len(i[1]) > 1] ambiguous += [i for i in l.DERIVED_ENT.items() if len(i[1]) > 1] pages = set([(j.name, j.uri) for i in ambiguous for j in i[1]]) print objs = [] for num, page in enumerate(pages): obj = {: page[1]} ...
Download WikiPedia pages of ambiguous units.
372,417
def from_tree(cls, repo, *treeish, **kwargs): if len(treeish) == 0 or len(treeish) > 3: raise ValueError("Please specify between 1 and 3 treeish, got %i" % len(treeish)) arg_list = [] if len(treeish) > 1: arg_list.append("--reset") ...
Merge the given treeish revisions into a new index which is returned. The original index will remain unaltered :param repo: The repository treeish are located in. :param treeish: One, two or three Tree Objects, Commits or 40 byte hexshas. The result changes ...
372,418
def get_chat_ids(self): updates = self.get_updates() chat_ids = [] if updates: for update in updates: message = update[] if message[] == : chat_ids.append(message[][]) return list(set(chat_ids))
Returns unique chat IDs from `/start` command messages sent to our bot by users. Those chat IDs can be used to send messages to chats. :rtype: list
372,419
def fetch_ensembl_exons(build=): LOG.info("Fetching ensembl exons build %s ...", build) if build == : url = else: url = dataset_name = dataset = pybiomart.Dataset(name=dataset_name, host=url) attributes = [ , , , , , ...
Fetch the ensembl genes Args: build(str): ['37', '38']
372,420
def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False): holodeck_worlds = _get_worlds_map() if world_name not in holodeck_worlds: raise HolodeckException("Invalid World Name") param_dict = copy(holodeck_worlds[world_name]) param_dict["start_world"...
Creates a holodeck environment using the supplied world name. Args: world_name (str): The name of the world to load as an environment. Must match the name of a world in an installed package. gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VERSION.OPENG...
372,421
def format_bytes_size(val): if not val: return for sz_name in [, , , , , , ]: if val < 1024.0: return "{0:.2f} {1}".format(val, sz_name) val /= 1024.0 raise OverflowError()
Take a number of bytes and convert it to a human readable number. :param int val: The number of bytes to format. :return: The size in a human readable format. :rtype: str
372,422
def inspect_members(self): if not self._inspect_members: TemplateGenerator._inspect_members = \ self._import_all_troposphere_modules() return self._inspect_members
Returns the list of all troposphere members we are able to construct
372,423
def create_machine_group(self, project_name, group_detail): headers = {} params = {} resource = "/machinegroups" headers[] = body = six.b(json.dumps(group_detail.to_json())) headers[] = str(len(body)) (resp, headers) = self._send("POST", projec...
create machine group in a project Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type group_detail: MachineGroupDetail :param group_detail: the machine group detail config :return: CreateMa...
372,424
async def send_tokens(payment_handle: int, tokens: int, address: str) -> str: logger = logging.getLogger(__name__) if not hasattr(Wallet.send_tokens, "cb"): logger.debug("vcx_wallet_send_tokens: Creating callback") Wallet.send_tokens.cb = create_cb(CFUNCTYPE(None, c_uin...
Sends tokens to an address payment_handle is always 0 :param payment_handle: Integer :param tokens: Integer :param address: String Example: payment_handle = 0 amount = 1000 address = await Wallet.create_payment_address('00000000000000000000000001234567') ...
372,425
def execute(self, eopatch=None, bbox=None, time_interval=None): if eopatch is None: eopatch = EOPatch() request_params, service_type = self._prepare_request_data(eopatch, bbox, time_interval) request = {ServiceType.WMS: WmsRequest, ServiceType.WCS: WcsReq...
Creates OGC (WMS or WCS) request, downloads requested data and stores it together with valid data mask in newly created EOPatch. Returns the EOPatch. :param eopatch: :type eopatch: EOPatch or None :param bbox: specifies the bounding box of the requested image. Coordinates must be in ...
372,426
def check_base_suggested_attributes(self, dataset): persongroupinstitutionpositions institution. (ACDD) :publisher_type = "" ; //...................................... SUGGESTED - Specifies type of publisher with one of the following: , , , or . (ACDD) :publisher_institution = "" ; //..............
Check the global suggested attributes for 2.0 templates. These go an extra step besides just checking that they exist. :param netCDF4.Dataset dataset: An open netCDF dataset :creator_type = "" ; //........................................ SUGGESTED - Specifies type of creator with one of the fo...
372,427
def _display_token(self): if self.token is None: return "301 Moved", "", {"Location": "/login"} return ("200 OK", self.TOKEN_TEMPLATE.format( access_token=self.token["access_token"]), {"Content-Type": "text/html"})
Display token information or redirect to login prompt if none is available.
372,428
def yahoo(base, target): api_url = resp = requests.get( api_url, params={ : , : , : .format(base, target) }, timeout=1, ) value = resp.text.split(, 2)[1] return decimal.Decimal(value)
Parse data from Yahoo.
372,429
def degree_circle(self,EdgeAttribute=None,network=None,NodeAttribute=None,\ nodeList=None,singlePartition=None,verbose=None): network=check_network(self,network,verbose=verbose) PARAMS=set_param([,,,,\ ],[EdgeAttribute,network,NodeAttribute,nodeList,\ singlePartition]) response=api(url=self.__url+"/degre...
Execute the Degree Sorted Circle Layout on a network. :param EdgeAttribute (string, optional): The name of the edge column contai ning numeric values that will be used as weights in the layout algor ithm. Only columns containing numeric values are shown :param network (string, optional): Specifies a network ...
372,430
def to_python(cls, value, **kwargs): if not value: return try: return str(value) except: pass try: return value.encode() except: pass raise cls.exception("Cannot deserialize value {0} tostring".format(v...
String deserialisation just return the value as a string
372,431
def BuildAdGroupCriterionOperations(adgroup_operations, number_of_keywords=1): criterion_operations = [ { : , : { : , : adgroup_operation[][], : { : , ...
Builds the operations adding a Keyword Criterion to each AdGroup. Args: adgroup_operations: a list containing the operations that will add AdGroups. number_of_keywords: an int defining the number of Keywords to be created. Returns: a list containing the operations that will create a new Keyword Criter...
372,432
def get_remote_url(self, remote=, cached=True): if hasattr(self.__class__, ) and cached: url = self.__class__._remote_url else: r = self.get_remote(remote) try: url = list(r.urls)[0] except GitCommandError as ex: if...
Get a git remote URL for this instance.
372,433
def _get_ensemble_bed_files(items): bed_files = [] for data in items: for sv in data.get("sv", []): if sv["variantcaller"] == "sv-ensemble": if ("vrn_file" in sv and not vcfutils.get_paired_phenotype(data) == "normal" and file_exists(sv["vrn_file"])...
get all ensemble structural BED file calls, skipping any normal samples from tumor/normal calls
372,434
def get_load(jid): cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: return {} ret = {} try: ret = jid_doc.value[] ret[] = jid_doc.value[] except KeyError as e: log.error(e) return ret
Return the load data that marks a specified jid
372,435
def vlink(s_expnum, s_ccd, s_version, s_ext, l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None): source_uri = get_uri(s_expnum, ccd=s_ccd, version=s_version, ext=s_ext, prefix=s_prefix) link_uri = get_uri(l_expnum, ccd=l_ccd, version=l_version, ext=l_ext, prefix=l_prefix) retur...
make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @param l_ext: @param s_prefix: @param l_prefix: @return:
372,436
def hover_pixmap(self, value): if value is not None: assert type(value) is QPixmap, " attribute: type is not !".format( "hover_pixmap", value) self.__hover_pixmap = value
Setter for **self.__hover_pixmap** attribute. :param value: Attribute value. :type value: QPixmap
372,437
def omim_terms(case_obj): LOG.info("Collecting OMIM disorders for case {}".format(case_obj.get())) disorders = [] case_disorders = case_obj.get() if case_disorders: for disorder in case_disorders: disorder_obj = { "id" : .join([ , str(disorder)]) } ...
Extract all OMIM phenotypes available for the case Args: case_obj(dict): a scout case object Returns: disorders(list): a list of OMIM disorder objects
372,438
def get_streaming(self, path, stype="M3U8_AUTO_480", **kwargs): params = { : path, : stype } url = .format(BAIDUPCS_SERVER) while True: ret = self._request(, , url=url, extra_params=params, **kwargs) if not ret.ok: ...
获得视频的m3u8列表 :param path: 视频文件路径 :param stype: 返回stream类型, 已知有``M3U8_AUTO_240``/``M3U8_AUTO_480``/``M3U8_AUTO_720`` .. warning:: M3U8_AUTO_240会有问题, 目前480P是最稳定的, 也是百度网盘默认的 :return: str 播放(列表)需要的信息
372,439
def create_html(self, filename=None): if isinstance(self.style, str): style = "".format(self.style) else: style = self.style options = dict( gl_js_version=GL_JS_VERSION, accessToken=self.access_token, div_id=s...
Create a circle visual from a geojson data source
372,440
def make_conditional( self, request_or_environ, accept_ranges=False, complete_length=None ): environ = _get_environ(request_or_environ) if environ["REQUEST_METHOD"] in ("GET", "HEAD"): if "date" not in self.headers: ...
Make the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is...
372,441
def parse(self, parser): lineno = next(parser.stream).lineno num_called_num = False plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != : if variables: ...
Parse a translatable tag.
372,442
def apply_patch(self): if sys.version_info >= (3, 0): pass else: from .patch.socket import socket as patch socket.socket = patch
Fix default socket lib to handle client disconnection while receiving data (Broken pipe)
372,443
def boundary_polygon(self, time): ti = np.where(time == self.times)[0][0] com_x, com_y = self.center_of_mass(time) padded_mask = np.pad(self.masks[ti], 1, , constant_values=0) chull = convex_hull_image(padded_mask) boundary_image = find_boundar...
Get coordinates of object boundary in counter-clockwise order
372,444
def to_value_list(original_strings, corenlp_values=None): assert isinstance(original_strings, (list, tuple, set)) if corenlp_values is not None: assert isinstance(corenlp_values, (list, tuple, set)) assert len(original_strings) == len(corenlp_values) return list(set(to_value(x, y) f...
Convert a list of strings to a list of Values Args: original_strings (list[basestring]) corenlp_values (list[basestring or None]) Returns: list[Value]
372,445
def name(object): "Try to find some reasonable name for the object." return (getattr(object, , 0) or getattr(object, , 0) or getattr(getattr(object, , 0), , 0) or str(object))
Try to find some reasonable name for the object.
372,446
def getVariable(dbg, thread_id, frame_id, scope, attrs): if scope == : if thread_id != get_current_thread_id(threading.currentThread()): raise VariableError("getVariable: must execute on same thread") try: import gc objects = gc.get_objects() except:...
returns the value of a variable :scope: can be BY_ID, EXPRESSION, GLOBAL, LOCAL, FRAME BY_ID means we'll traverse the list of all objects alive to get the object. :attrs: after reaching the proper scope, we have to get the attributes until we find the proper location (i.e.: obj\tattr1\tattr2)...
372,447
def copy_ecu_with_frames(ecu_or_glob, source_db, target_db): if isinstance(ecu_or_glob, cm.Ecu): ecu_list = [ecu_or_glob] else: ecu_list = source_db.glob_ecus(ecu_or_glob) for ecu in ecu_list: logger.info("Copying ECU " + ecu.name) target_db.add_ecu(copy.deep...
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix. This function additionally copy all relevant Frames and Defines. :param ecu_or_glob: Ecu instance or glob pattern for Ecu name :param source_db: Source CAN matrix :param target_db: Destination CAN matrix
372,448
def use(self, func, when=): print(.format(func.__name__)) self.middlewares.append({ : func, : func.__name__, : func.func_code.co_varnames, : when })
Append a middleware to the algorithm
372,449
def get_descriptor_defaults(self, api_info, hostname=None, x_google_api_name=False): hostname = (hostname or util.get_app_hostname() or api_info.hostname) protocol = if ((hostname and hostname.startswith()) or util.is_running_on_devserver()) else base_path = ...
Gets a default configuration for a service. Args: api_info: _ApiInfo object for this service. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary with the default configuration.
372,450
def dev_get_chunk(dev_name, state, pugrp=None, punit=None): rprt = dev_get_rprt(dev_name, pugrp, punit) if not rprt: return None return next((d for d in rprt if d["cs"] == state), None)
Get a chunk-descriptor for the first chunk in the given state. If the pugrp and punit is set, then search only that pugrp/punit @returns the first chunk in the given state if one exists, None otherwise
372,451
def generate(env): "Add RPCGEN Builders and construction variables for an Environment." client = Builder(action=rpcgen_client, suffix=, src_suffix=) header = Builder(action=rpcgen_header, suffix=, src_suffix=) service = Builder(action=rpcgen_service, suffix=, src_suffix=) xdr = Bu...
Add RPCGEN Builders and construction variables for an Environment.
372,452
def _compile_int_g(self): string = self.int_g = compile(eval(string), , )
Time Domain Simulation - update algebraic equations and Jacobian
372,453
def createFromSource(cls, vs, name, registry): s a valid package name (this does not guarantee that the component actually exists in the registry: use availableVersions() for that). t match this then escalate to make if registry == : name_match = re.m...
returns a registry component for anything that's a valid package name (this does not guarantee that the component actually exists in the registry: use availableVersions() for that).
372,454
def _get_build_prefix(): path = os.path.join( tempfile.gettempdir(), % __get_username().replace(, ) ) if WINDOWS: return path try: os.mkdir(path) write_delete_marker_file(path) except OSError: file_uid = None try: ...
Returns a safe build_prefix
372,455
def entropy_H(self, data): if len(data) == 0: return 0.0 occurences = array.array(, [0]*256) for x in data: occurences[ord(x)] += 1 entropy = 0 for x in occurences: if x: p_x = float(...
Calculate the entropy of a chunk of data.
372,456
def _newproject(command, path, name, settings): key = None title = _get_project_title() template = _get_template(settings) git = sh.git.bake(_cwd=path) puts(git.init()) if template.get("url"): puts(git.submodule.add(template[], )) puts(git.submodule.update(*[...
Helper to create new project.
372,457
def get_text_stream(name, encoding=None, errors=): opener = text_streams.get(name) if opener is None: raise TypeError( % name) return opener(encoding, errors)
Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts on Python 3 for already correctly configured streams. :param name: the name of the stream to open. Valid names are ``'stdin'...
372,458
def update(self, response, **kwargs): response_cls = super( LocationResponseClassLegacyAccessor, self)._get_instance(**kwargs) if response_cls: setattr(response_cls, self.column, self.accessor(response)) setattr( response_cls, self.venue_colum...
If a record matching the instance already exists in the database, update both the column and venue column attributes, else create a new record.
372,459
def from_Solis(filepath, name=None, parent=None, verbose=True) -> Data: filestr = os.fspath(filepath) filepath = pathlib.Path(filepath) if not ".asc" in filepath.suffixes: wt_exceptions.WrongFileTypeWarning.warn(filepath, ".asc") if not name: name = filepath.name.split("....
Create a data object from Andor Solis software (ascii exports). Parameters ---------- filepath : path-like Path to .txt file. Can be either a local or remote file (http/ftp). Can be compressed with gz/bz2, decompression based on file name. name : string (optional) Name t...
372,460
def parse_plays_stream(self): lx_doc = self.html_doc() if lx_doc is not None: parser = PlayParser(self.game_key.season, self.game_key.game_type) plays = lx_doc.xpath() for p in plays: p_obj = parser.build_play(p) self....
Generate and yield a stream of parsed plays. Useful for per play processing.
372,461
def accpro20_summary(self, cutoff): summary = {} if cutoff < 1: cutoff = 1 * 100 records = read_accpro20(self.out_accpro20) for k,v in records.items(): seq_summary = {} exposed = 0 buried = 0 for s in v: ...
Parse the ACCpro output file and return a summary of percent exposed/buried residues based on a cutoff. Below the cutoff = buried Equal to or greater than cutoff = exposed The default cutoff used in accpro is 25%. The output file is just a FASTA formatted file, so you can get residue l...
372,462
def embedded_preview(src_path): try: assert(exists(src_path) and isdir(src_path)) preview_list = glob(join(src_path, , )) assert(preview_list) with NamedTemporaryFile(prefix=, suffix=extension(preview_path), delete=False) as tempfileobj: dest_path = tempfileobj.name shutil.copy(prev...
Returns path to temporary copy of embedded QuickLook preview, if it exists
372,463
def solve(self): fmtstr, nsep = self.display_start() self.timer.start([, , , ]) for self.k in range(self.k, self.k + self.opt[]): self.store_prev() if self.opt[, ] and self.k >= 0...
Start (or re-start) optimisation. This method implements the framework for the iterations of a FISTA algorithm. There is sufficient flexibility in overriding the component methods that it calls that it is usually not necessary to override this method in derived clases. If option...
372,464
def attach_volume_to_device(self, volume_id, device_id): try: volume = self.manager.get_volume(volume_id) volume.attach(device_id) except packet.baseapi.Error as msg: raise PacketManagerException(msg) return volume
Attaches the created Volume to a Device.
372,465
def ctcBeamSearch(mat, classes, lm, k, beamWidth): blankIdx = len(classes) maxT, maxC = mat.shape last = BeamState() labeling = () last.entries[labeling] = BeamEntry() last.entries[labeling].prBlank = 1 last.entries[labeling].prTotal = 1 for t in range(maxT): cu...
beam search as described by the paper of Hwang et al. and the paper of Graves et al.
372,466
def _search_dirs(self, dirs, basename, extension=""): for d in dirs: path = os.path.join(d, % (basename, extension)) if os.path.exists(path): return path return None
Search a list of directories for a given filename or directory name. Iterator over the supplied directories, returning the first file found with the supplied name and extension. :param dirs: a list of directories :param basename: the filename :param extension: the file e...
372,467
def parse_scale(x): match = re.match(r, x) if not match: raise ValueError( % x) return match.group(1), int(match.group(2))
Splits a "%s:%d" string and returns the string and number. :return: A ``(string, int)`` pair extracted from ``x``. :raise ValueError: the string ``x`` does not respect the input format.
372,468
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r if isinstance(levels, (int, float, basestring, str, bytes)): levels = [float(levels)] levels = set([int(i) for i in levels]) if isinstance(lines, basestring): lines = lines.splitlines() level_lines = [] for line...
r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bullet \n##bad\n# hello\n ### world\n') [(0, '- bullet '), (2, 'bad')...
372,469
def _compute_geometric_decay_term(self, C, mag, dists): c1 = self.CONSTS[] return ( (C[] + C[] * (mag - c1)) * np.log(np.sqrt(dists.rjb ** 2.0 + C[] ** 2.0)) )
Compute and return geometric decay term in equation 3, page 970.
372,470
def calculate_ef_var(tpf, fpf): efvara = (tpf * (1 - tpf)) efvard = (fpf * (1 - fpf)) ef = tpf / fpf if fpf == 1: return(0, 0, 0) else: s = ef * ( 1 + (np.log(ef)/np.log(fpf))) s2 = s * s return (efvara, efvard, s2)
determine variance due to actives (efvar_a) decoys (efvar_d) and s2, the slope of the ROC curve tangent to the fpf @ which the enrichment factor was calculated :param tpf: float tpf @ which the enrichment factor was calculated :param fpf: float fpf @ which the enrichment factor was calculated :return ef...
372,471
def makeringlatticeCIJ(n, k, seed=None): s global random state to generate random numbers. Otherwise, use a new np.random.RandomState instance seeded with the given value. Returns ------- CIJ : NxN np.ndarray connection matrix Notes ----- The lattice is made by placing conn...
This function generates a directed lattice network with toroidal boundary counditions (i.e. with ring-like "wrapping around"). Parameters ---------- N : int number of vertices K : int number of edges seed : hashable, optional If None (default), use the np.random's global...
372,472
def read_records(file): records = [] for record_data in read_recordio(file): record = Record() record.ParseFromString(record_data) records.append(record) return records
Eagerly read a collection of amazon Record protobuf objects from file.
372,473
def list_users(verbose=True, hashes=False): * users = {} if verbose else [] if verbose: res = __salt__[]( .format(hashes="--smbpasswd-style" if hashes else ""), ) if res[] > 0: log.error(res[] if in res else res[]) return users ...
List user accounts verbose : boolean return all information hashes : boolean include NT HASH and LM HASH in verbose output CLI Example: .. code-block:: bash salt '*' pdbedit.list
372,474
def response(self, parameters): r self._set_parameters(parameters) terms = self.m * (1 - (1 / (1 + (1j * self.w * self.tau) ** self.c))) specs = np.sum(terms, axis=1) rcomplex = self.rho0 * (1 - specs) response = sip_response.sip_response(self.f, rcomple...
r"""Complex response of the Cole-Cole model:: :math:`\hat{\rho} = \rho_0 \left(1 - \sum_i m_i (1 - \frac{1}{1 + (j \omega \tau_i)^c_i})\right)` Parameters ---------- parameters: list or tuple or numpy.ndarray Cole-Cole model parameters: rho0, m, tau, c (all linear) ...
372,475
def authenticate(devices, params, facet, check_only): for device in devices[:]: try: device.open() except: devices.remove(device) try: prompted = False while devices: removed = [] for device in devices: try: ...
Interactively authenticates a AuthenticateRequest using an attached U2F device.
372,476
def set_server_callback(self, handle): if self.on_events: for event in self.on_events: handle.on_event(event, self.on_event) if self.on_changes: for change in self.on_changes: if change in [, ]: con...
Set up on_change events for bokeh server interactions.
372,477
def _ExecuteTransaction(self, transaction): def Action(connection): connection.cursor.execute("START TRANSACTION") for query in transaction: connection.cursor.execute(query["query"], query["args"]) connection.cursor.execute("COMMIT") return connection.cursor.fetchall() ret...
Get connection from pool and execute transaction.
372,478
def rate(self): end = self._end_time if self._end_time else time.time() return self._count / (end - self._start_time)
Report the insertion rate in records per second
372,479
def adjustSize( self ): cell = self.scene().cellWidth() * 2 minheight = cell minwidth = 2 * cell metrics = QFontMetrics(QApplication.font()) width = metrics.width(self.displayName()) + 20 width = ((width/cell) * cell) + (cell % width) ...
Adjusts the size of this node to support the length of its contents.
372,480
def __op(name, val, fmt=None, const=False, consume=0, produce=0): name = name.lower() if isinstance(fmt, str): fmt = partial(_unpack, compile_struct(fmt)) operand = (name, val, fmt, consume, produce, const) assert(name not in __OPTABLE) assert(val not in __OPTABLE) ...
provides sensible defaults for a code, and registers it with the __OPTABLE for lookup.
372,481
def bubble_sizes_ref(self, series): top_row = self.series_table_row_offset(series) + 2 bottom_row = top_row + len(series) - 1 return "Sheet1!$C$%d:$C$%d" % (top_row, bottom_row)
The Excel worksheet reference to the range containing the bubble sizes for *series* (not including the column heading cell).
372,482
def _do_request(self, url, params=None, data=None, headers=None): if not headers: headers = {: } try: response = requests.get( url, params=params, data=data, headers=headers) except: return None if response.status_code == 20...
Realiza as requisições diversas utilizando a biblioteca requests, tratando de forma genérica as exceções.
372,483
def pb2dict(obj): adict = {} if not obj.IsInitialized(): return None for field in obj.DESCRIPTOR.fields: if not getattr(obj, field.name): continue if not field.label == FD.LABEL_REPEATED: if not field.type == FD.TYPE_MESSAGE: adict[field.n...
Takes a ProtoBuf Message obj and convertes it to a dict.
372,484
def get_log_entry_log_assignment_session(self, proxy): if not self.supports_log_entry_log_assignment(): raise errors.Unimplemented() return sessions.LogEntryLogAssignmentSession(proxy=proxy, runtime=self._runtime)
Gets the session for assigning log entry to log mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLogAssignmentSession) - a ``LogEntryLogAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to c...
372,485
def download(self, location, local_dir=): self.logger.debug() bucket = self.info[] prefix = self.info[] self.logger.debug() s3conn = self.client location = location.strip() self.logger.debug() objects = s3conn.list_objects(Bucket=buck...
Download content from bucket/prefix/location. Location can be a directory or a file (e.g., my_dir or my_dir/my_image.tif) If location is a directory, all files in the directory are downloaded. If it is a file, then that file is downloaded. Args: location (str)...
372,486
def delete(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() meta = getattr(self.object, ) self.object.delete() messages.success( request, _(u).format( meta.verb...
Processes deletion of the specified instance. :param request: the request instance. :rtype: django.http.HttpResponse.
372,487
def get_log(self, offset, count=10, callback=None): params = {: offset, : count} return self.execute_command(, params, callback=callback)
Retrieve log records from camera. cmd: getLog param: offset: log offset for first record count: number of records to return
372,488
def _build_query_url(self, page = None, verbose = False): query = [] if len(self.filters) > 0: query.append(urlencode(self.filters)) if self.sort: query_str = u"%s=%s" % (u"sort", self.sort) query.append(query_str) if self.sort_by: ...
builds the url to call
372,489
def reboot(self, timeout=1): namespace = System.getServiceType("reboot") uri = self.getControlURL(namespace) self.execute(uri, namespace, "Reboot", timeout=timeout)
Reboot the device
372,490
def select_token(request, scopes=, new=False): @tokens_required(scopes=scopes, new=new) def _token_list(r, tokens): context = { : tokens, : app_settings.ESI_BASE_TEMPLATE, } return render(r, , context=context) return _token_list(request)
Presents the user with a selection of applicable tokens for the requested view.
372,491
def google_storage_url(self, sat): filename = sat[] + return url_builder([self.google, sat[], sat[], sat[], filename])
Returns a google storage url the contains the scene provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :returns: (String) The URL to a google storage file
372,492
def updateUserRole(self, user, role): url = self._url + "/updateuserrole" params = { "f" : "json", "user" : user, "role" : role } return self._post(url=url, param_dict=...
The Update User Role operation allows the administrator of an org anization to update the role of a user within a portal. Inputs: role - Sets the user's role. Roles are the following: org_user - Ability to add items, create groups, and ...
372,493
def _one_projector(args: Dict[str, Any], index: int) -> Union[int, np.ndarray]: num_shard_qubits = args[] shard_num = args[] if index >= num_shard_qubits: return _kth_bit(shard_num, index - num_shard_qubits) return _zero_one_vects(args)[index]
Returns a projector onto the |1> subspace of the index-th qubit.
372,494
def rate_limits(self): if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self.response) return self._rate_limits
Returns a list of rate limit details.
372,495
def read_val(self, key:str) -> Union[List[float],Tuple[List[float],List[float]]]: "Read a hyperparameter `key` in the optimizer dictionary." val = [pg[key] for pg in self.opt.param_groups[::2]] if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val] return val
Read a hyperparameter `key` in the optimizer dictionary.
372,496
def execute_no_results(self, sock_info, generator): if self.bypass_doc_val and sock_info.max_wire_version >= 4: raise OperationFailure("Cannot set bypass_document_validation with" " unacknowledged write concern") coll = self.collection ...
Execute all operations, returning no results (w=0).
372,497
def stop_all(self): pool = Pool(concurrency=3) for node in self.nodes.values(): pool.append(node.stop) yield from pool.join()
Stop all nodes
372,498
def array_type(data_types, field): from sqlalchemy.dialects import postgresql internal_type = field.base_field.get_internal_type() if internal_type in data_types and internal_type != : sub_type = data_types[internal_type](field) if not isinstance(sub_type, (list, tuple)): ...
Allows conversion of Django ArrayField to SQLAlchemy Array. Takes care of mapping the type of the array element.
372,499
def asof_locs(self, where, mask): locs = self.values[mask].searchsorted(where.values, side=) locs = np.where(locs > 0, locs - 1, 0) result = np.arange(len(self))[mask].take(locs) first = mask.argmax() result[(locs == 0) & (where.values < self.values[first])] = -1 ...
Find the locations (indices) of the labels from the index for every entry in the `where` argument. As in the `asof` function, if the label (a particular entry in `where`) is not in the index, the latest index label upto the passed label is chosen and its index returned. If all ...