Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
381,700
def handle_truncated_response(callback, params, entities): results = {} for entity in entities: results[entity] = [] while True: try: marker_found = False response = callback(**params) for entity in entities: if entity in response: ...
Handle truncated responses :param callback: :param params: :param entities: :return:
381,701
def parse_cctop_full(infile): parser = etree.XMLParser(ns_clean=True) with open(infile, ) as f: tree = etree.fromstring(f.read(), parser) all_info = [] if tree.find() is not None: for r in tree.find().findall(): region_start = int(r.attrib[]) region_end = i...
Parse a CCTOP XML results file and return a list of the consensus TM domains in the format:: [(1, inside_outside_or_tm), (2, inside_outside_or_tm), ...] Where the first value of a tuple is the sequence residue number, and the second is the predicted location with the valu...
381,702
def unsubscribe(self, tag, match_type=None): if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.remove([tag, match_func]) old_events = self.pending_events self.pending_events = [] for evt in old_events: ...
Un-subscribe to events matching the passed tag.
381,703
def _get_files(extension, path): files = [] for file in os.listdir(path): if file.endswith(extension): files.append(os.path.join(path, file)) return sorted(files)
Returns a sorted list of all of the files having the same extension under the same directory :param extension: the extension of the data files such as 'gdm' :param path: path to the folder containing the files :return: sorted list of files
381,704
def serialize_to_string( root_processor, value, indent=None ): if not _is_valid_root_processor(root_processor): raise InvalidRootProcessor() state = _ProcessorState() state.push_location(root_processor.element_path) root = root_processor.serialize(value,...
Serialize the value to an XML string using the root processor. :return: The serialized XML string. See also :func:`declxml.serialize_to_file`
381,705
def write_to_file(self): with open(, ) as output: output.write( + + + + ) previous_commits = 0 for week in self.sorted_weeks: if str(self.commits[week]) != previous_commit...
Writes the weeks with associated commits to file.
381,706
def infer_namespace(ac): namespaces = infer_namespaces(ac) if not namespaces: return None if len(namespaces) > 1: raise BioutilsError("Multiple namespaces possible for {}".format(ac)) return namespaces[0]
Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infe...
381,707
def get_id(self): if self._id is None: self._id = self.inspect(refresh=False)["Id"] return self._id
get unique identifier of this container :return: str
381,708
def update_contents(self, contents, mime_type): import hashlib import time new_size = len(contents) self.mime_type = mime_type if mime_type == : self.contents = contents.encode() else: self.contents = contents old_hash = self.h...
Update the contents and set the hash and modification time
381,709
def gaussian_filter(self, sigma=2, order=0): from scipy.ndimage.filters import gaussian_filter return self.map(lambda v: gaussian_filter(v, sigma, order), value_shape=self.value_shape)
Spatially smooth images with a gaussian filter. Filtering will be applied to every image in the collection. Parameters ---------- sigma : scalar or sequence of scalars, default = 2 Size of the filter size as standard deviation in pixels. A sequence is interprete...
381,710
def tokens_required(scopes=, new=False): def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): token = _check_callback(request) if token and new: tokens = Token.objects...
Decorator for views to request an ESI Token. Accepts required scopes as a space-delimited string or list of strings of scope names. Can require a new token to be retrieved by SSO. Returns a QueryDict of Tokens.
381,711
def _fetch_access_token(self, url, data): logger.info() res = self._http.post( url=url, data=data ) try: res.raise_for_status() except requests.RequestException as reqe: raise WeChatClientException( errcode=...
The real fetch access token
381,712
def xtqx(self): if self.__xtqx is None: self.log("xtqx") self.__xtqx = self.jco.T * (self.obscov ** -1) * self.jco self.log("xtqx") return self.__xtqx
get the normal matrix attribute. Create the attribute if it has not yet been created Returns ------- xtqx : pyemu.Matrix
381,713
def positions(self, reverse=False): def Posgen(reverse): if reverse: lastrootsib = self.last_sibling_position(self.root) current = self.last_decendant(lastrootsib) while current is not None: yield current ...
returns a generator that walks the positions of this tree in DFO
381,714
def add_init_files(path, zip_handler): paths = path.split() paths = paths[:len(paths) - 1] for sub_path in paths: for root, dirs, files in os.walk(sub_path): for file_to_zip in [x for x in files if in x]: filename = os.path.join(root, file_to_zip) zi...
adds init files to the included folder :param path: str
381,715
def create_volume(self, availability_zone, size=None, snapshot_id=None): params = {"AvailabilityZone": availability_zone} if ((snapshot_id is None and size is None) or (snapshot_id is not None and size is not None)): raise ValueError("Please provide either size or snapsh...
Create a new volume.
381,716
def parent(self) -> Optional[]: if self.start.depth == 1 and (self.end is None or self.end.depth <= 1): return None else: if self.start.depth > 1 and (self.end is None or self.end.depth == 0): return CtsReference("{0}{1}".format( ".".j...
Parent of the actual URN, for example, 1.1 for 1.1.1 :rtype: CtsReference
381,717
def create_table( self, parent, table_id, table, initial_splits=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "create_table" not in self._inner_api_c...
Creates a new table in the specified instance. The table can be created with a full set of initial column families, specified in the request. Example: >>> from google.cloud import bigtable_admin_v2 >>> >>> client = bigtable_admin_v2.BigtableTableAdminClient()...
381,718
def save(self, record_key, record_data, overwrite=True, secret_key=): labunittests1473719695.2165067.json title = % self.__class__.__name__ input_fields = { : record_key, : secret_key } for key, value in input_fields.items():...
a method to create a record in the collection folder :param record_key: string with name to assign to record (see NOTES below) :param record_data: byte data for record body :param overwrite: [optional] boolean to overwrite records with same name :param secret_key: [optional] string...
381,719
def free_memory(cls, exclude=None): annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__ exclude = () if exclude is None else exclude for annotation_cls in list(annotations_in_memory.keys()): if issubclass(annotation_cls, exclude): continue ...
Free global annotation memory.
381,720
def load_generated_checkers(cls, args): for gen in cls._get_generator_plugins(): checkers = gen.get_checkers(args) cls.checkers.update(checkers)
Load checker classes from generator plugins
381,721
def logistic_map(x, steps, r=4): r for _ in range(steps): x = r * x * (1 - x) yield x
r""" Generates a time series of the logistic map. Characteristics and Background: The logistic map is among the simplest examples for a time series that can exhibit chaotic behavior depending on the parameter r. For r between 2 and 3, the series quickly becomes static. At r=3 the first bifurcation poi...
381,722
def main(): if len(sys.argv) < 3: usage() rgname = sys.argv[1] vmss = sys.argv[2] try: with open() as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") ...
Main routine.
381,723
def run(juttle, deployment_name, program_name=None, persist=False, token_manager=None, app_url=defaults.APP_URL): headers = token_manager.get_access_token_headers() data_url = get_juttle_data_url(deployment_name, app_url=app_url, ...
run a juttle program through the juttle streaming API and return the various events that are part of running a Juttle program which include: * Initial job status details including information to associate multiple flowgraphs with their individual outputs (sinks): { "status":...
381,724
def RdatasetsBM(database,host=rbiomart_host): biomaRt = importr("biomaRt") ensemblMart=biomaRt.useMart(database, host=host) print(biomaRt.listDatasets(ensemblMart))
Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing
381,725
def ls(self): tree = self.ls_tree() return [t.get() for t in tree if t.get()]
Return a list of *all* files & dirs in the repo. Think of this as a recursive `ls` command from the root of the repo.
381,726
def get_lonlatalt(self, utc_time): (pos_x, pos_y, pos_z), (vel_x, vel_y, vel_z) = self.get_position( utc_time, normalize=True) lon = ((np.arctan2(pos_y * XKMPER, pos_x * XKMPER) - astronomy.gmst(utc_time)) % (2 * np.pi)) lon = np.where(lon > np.pi, lon - np....
Calculate sublon, sublat and altitude of satellite. http://celestrak.com/columns/v02n03/
381,727
def visible_object_groups(self): return (i for (i, l) in enumerate(self.layers) if l.visible and isinstance(l, TiledObjectGroup))
Return iterator of object group indexes that are set 'visible' :rtype: Iterator
381,728
def list_joined_groups(self, user_alias=None): xml = self.api.xml(API_GROUP_LIST_JOINED_GROUPS % (user_alias or self.api.user_alias)) xml_results = xml.xpath() results = [] for item in xml_results: try: icon = item.xpath()[0] link = it...
已加入的小组列表 :param user_alias: 用户名,默认为当前用户名 :return: 单页列表
381,729
def log(self, string): self.log_data.append(string) if self.log_function is None: print(string) else: self.log_function(string)
appends input string to log file and sends it to log function (self.log_function) Returns:
381,730
def get_name(obj, setting_name=): nickname = obj.get_nickname() romanized_first_name = obj.get_romanized_first_name() romanized_last_name = obj.get_romanized_last_name() non_romanized_first_name = obj.get_non_romanized_first_name() non_romanized_last_name = obj.get_non_romanized_last_name() ...
Returns the correct order of the name according to the current language.
381,731
def serialize_dict(self, attr, dict_type, **kwargs): serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data( value, dict_...
Serialize a dictionary of objects. :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. :param bool required: Whether the objects in the dictionary must not be None or empty. :rtype: dict
381,732
def _build_layers(self, inputs, num_outputs, options): hiddens = options.get("fcnet_hiddens") activation = get_activation_fn(options.get("fcnet_activation")) with tf.name_scope("fc_net"): i = 1 last_layer = inputs for size in hiddens: ...
Process the flattened inputs. Note that dict inputs will be flattened into a vector. To define a model that processes the components separately, use _build_layers_v2().
381,733
def isID(self, elem, attr): if elem is None: elem__o = None else: elem__o = elem._o if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlIsID(self._o, elem__o, attr__o) return ret
Determine whether an attribute is of type ID. In case we have DTD(s) then this is done if DTD loading has been requested. In the case of HTML documents parsed with the HTML parser, then ID detection is done systematically.
381,734
def _get_encoder_data_shapes(self, bucket_key: int, batch_size: int) -> List[mx.io.DataDesc]: return [mx.io.DataDesc(name=C.SOURCE_NAME, shape=(batch_size,) + self.input_size, layout=C.BATCH_MAJOR_IMAGE)]
Returns data shapes of the encoder module. :param bucket_key: Maximum input length. :param batch_size: Batch size. :return: List of data descriptions.
381,735
def check_auth(email, password): try: user = User.get(User.email == email) except User.DoesNotExist: return False return password == user.password
Check if a username/password combination is valid.
381,736
def _pip_search(stdout, stderr): result = {} lines = to_text_string(stdout).split() while in lines: lines.remove() for line in lines: if in line: parts = line.split() name = parts[0].strip() description =...
Callback for pip search.
381,737
def parse_request(self): self.command = None self.request_version = version = self.default_request_version self.close_connection = 1 requestline = str(self.raw_requestline, ) requestline = requestline.rstrip() self.requestline = requestline words = requ...
Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back.
381,738
def get_lsf_status(): status_count = {: 0, : 0, : 0, : 0, : 0, : 0} try: subproc = subprocess.Popen([], stdout=subprocess.PIPE, ...
Count and print the number of jobs in various LSF states
381,739
def SVGdocument(): "Create default SVG document" import xml.dom.minidom implementation = xml.dom.minidom.getDOMImplementation() doctype = implementation.createDocumentType( "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" ) document= implementation.createDocument(None, "sv...
Create default SVG document
381,740
def dateof(tag_name, tags): for tag in tags: if tag[] == tag_name: commit = read_url(tag[][]) return parse_timestamp(commit[][][]) return None
Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.
381,741
def register_parser(self, type, parser, **meta): try: self.registered_formats[type][] = parser except KeyError: self.registered_formats[type] = {: parser} if meta: self.register_meta(type, **meta)
Registers a parser of a format. :param type: The unique name of the format :param parser: The method to parse data as the format :param meta: The extra information associated with the format
381,742
def home_mode_status(self, **kwargs): api = self._api_info[] payload = dict({ : api[], : , : api[], : self._sid }, **kwargs) response = self._get_json_with_retry(api[], payload) return response[][]
Returns the status of Home Mode
381,743
def all(cls, client, **kwargs): max_date = kwargs[] if in kwargs else None max_fetches = \ kwargs[] if in kwargs else None url = params = {} data = client.get(url, params=params) results = data["results"] if is_max_date_gt(max_date, resul...
fetch all option positions
381,744
def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT): return get_attribute(module_name, class_name)(*args, **kwargs)
Create an object instance of the given class from the given module. Args and kwargs are passed to the constructor. This mimics the following code: .. code-block:: python from module import class return class(*args, **kwargs) :param module_name: module name :param class_name: clas...
381,745
def pivot(self,binned=True): if binned: wave = self.binwave else: wave = self.wave countmulwave = self(wave)*wave countdivwave = self(wave)/wave num = self.trapezoidIntegration(wave,countmulwave) den = self.trapezoidIntegration(wave,coun...
Calculate :ref:`pivot wavelength <pysynphot-formula-pivwv>` of the observation. .. note:: This is the calculation performed when ETC invokes ``calcphot``. Parameters ---------- binned : bool Use binned dataset for calculations. Otherwise, use native dat...
381,746
def main(): parser = argparse.ArgumentParser() parser.add_argument(, help=) parser.add_argument(, help=) parser.add_argument(, help=) parser.add_argument(, action=, default=[ , ...
Given an input whl file and target version, create a copy of the whl with that version. This is accomplished via string replacement in files matching a list of globs. Pass the optional `--glob` argument to add additional globs: ie `--glob='thing-to-match*.txt'`.
381,747
async def main(): client = Client(BMAS_ENDPOINT) response = await client(bma.node.summary) print(response) salt = getpass.getpass("Enter your passphrase (salt): ") password = getpass.getpass("Enter your password: ") key = SigningKey.from_credentials(salt, passwo...
Main code
381,748
def activate_status_output_overall_status(self, **kwargs): config = ET.Element("config") activate_status = ET.Element("activate_status") config = activate_status output = ET.SubElement(activate_status, "output") overall_status = ET.SubElement(output, "overall-status") ...
Auto Generated Code
381,749
def parse_time(timestring): timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() dt = datetime.utcnow().strptime(found[], pattern) dt = datetime.combine(date.today(), d...
Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object.
381,750
def get_list(self, url=None, callback=None, limit=100, **data): url = url or str(self) data = dict(((k, v) for k, v in data.items() if v)) all_data = [] if limit: data[] = min(limit, 100) while url: response = self.http.get(url, params=data, auth=...
Get a list of this github component :param url: full url :param Comp: a :class:`.Component` class :param callback: Optional callback :param limit: Optional number of items to retrieve :param data: additional query data :return: a list of ``Comp`` objects with data
381,751
def _handle_successor(self, job, successor, successors): state = successor all_successor_states = successors addr = job.addr pw = None job.successor_status[state] = "" new_state = state.copy() suc_jumpkind = state.history.jumpkind suc...
Returns a new CFGJob instance for further analysis, or None if there is no immediate state to perform the analysis on. :param CFGJob job: The current job.
381,752
def getKwAsDict(self, kw): self.getKw(kw) return self.str2dict(self.confstr)
return keyword configuration as a dict Usage: rdict = getKwAsDict(kw)
381,753
def get_order_detail(self, code): if code is None or is_str(code) is False: error_str = ERROR_STR_PREFIX + "the type of code param is wrong" return RET_ERROR, error_str query_processor = self._get_sync_query_processor( OrderDetail.pack_req, OrderDetail.unpa...
查询A股Level 2权限下提供的委托明细 :param code: 股票代码,例如:'HK.02318' :return: (ret, data) ret == RET_OK data为1个dict,包含以下数据 ret != RET_OK data为错误字符串 {‘code’: 股票代码 ‘Ask’:[ order_num, [order_volume1, order_volume2] ] ‘Bid’: [ order_num, [...
381,754
def calculate_rate(phone_number, address_country_code=None, address_exception=None): if not phone_number: raise ValueError() if not isinstance(phone_number, str_cls): raise ValueError() phone_number = phone_number.strip() phone_number = re.sub(, , phone_number) if not phone_...
Calculates the VAT rate based on a telephone number :param phone_number: The string phone number, in international format with leading + :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from...
381,755
def _Rforce(self, R, z, phi=0, t=0): if not self.isNonAxi and phi is None: phi= 0. r, theta, phi = bovy_coords.cyl_to_spher(R,z,phi) dr_dR = nu.divide(R,r); dtheta_dR = nu.divide(z,r**2); dphi_dR = 0 return self._computeforceArray(dr_dR, dtheta_dR, dphi_dR, ...
NAME: _Rforce PURPOSE: evaluate the radial force at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: radial force at (R,z, phi) HISTORY: 2016-...
381,756
def _set_attributes_on_managed_object(self, managed_object, attributes): for attribute_name, attribute_value in six.iteritems(attributes): object_type = managed_object._object_type if self._attribute_policy.is_attribute_applicable_to_object_type( attribute_na...
Given a kmip.pie object and a dictionary of attributes, attempt to set the attribute values on the object.
381,757
def do_capture(parser, token): bits = token.split_contents() t_as = t_silent = var = silent = False num_bits = len(bits) if len(bits) > 4: raise TemplateSyntaxError(" node supports parameters.") elif num_bits == 4: t_name, t_as, var, t_silent = bits ...
Capture the contents of a tag output. Usage: .. code-block:: html+django {% capture %}..{% endcapture %} # output in {{ capture }} {% capture silent %}..{% endcapture %} # output in {{ capture }} only {% capture as varname %}..{% endcapture %} # o...
381,758
def parameters_to_segments(origins, vectors, parameters): origins = np.asanyarray(origins, dtype=np.float64) vectors = np.asanyarray(vectors, dtype=np.float64) parameters = np.asanyarray(parameters, dtype=np.float64) segments = np.hstack((origins + vectors * parameters[:, :1], ...
Convert a parametric line segment representation to a two point line segment representation Parameters ------------ origins : (n, 3) float Line origin point vectors : (n, 3) float Unit line directions parameters : (n, 2) float Start and end distance pairs for each line ...
381,759
def _remote_connection(server, opts, argparser_): global CONN if opts.timeout is not None: if opts.timeout < 0 or opts.timeout > 300: argparser_.error( % opts.timeout) if opts.mock_server: CONN = FakedWBEMConnection( default_namespace=opts.names...
Initiate a remote connection, via PyWBEM. Arguments for the request are part of the command line arguments and include user name, password, namespace, etc.
381,760
def load_vocab(self, vocab_name, **kwargs): log.setLevel(kwargs.get("log_level", self.log_level)) vocab = self.get_vocab(vocab_name , **kwargs) if vocab[] in self.loaded: if self.loaded_times.get(vocab[], datetime.datetime(2001,1,1)).timestamp() \ ...
loads a vocabulary into the defintion triplestore args: vocab_name: the prefix, uri or filename of a vocabulary
381,761
def average_precision(truth, recommend): if len(truth) == 0: if len(recommend) == 0: return 1. return 0. tp = accum = 0. for n in range(recommend.size): if recommend[n] in truth: tp += 1. accum += (tp / (n + 1.)) return accum / truth.size
Average Precision (AP). Args: truth (numpy 1d array): Set of truth samples. recommend (numpy 1d array): Ordered set of recommended samples. Returns: float: AP.
381,762
def CaptureFrameLocals(self, frame): variables = {n: self.CaptureNamedVariable(n, v, 1, self.default_capture_limits) for n, v in six.viewitems(frame.f_locals)} nargs = frame.f_code.co_argcount if frame.f_code.co_flags & inspect.C...
Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple.
381,763
def __json_strnum_to_bignum(json_object): for key in (, , , , , , ): if (key in json_object and isinstance(json_object[key], six.text_type)): try: json_object[key] = int(json_object[key]) except ValueError: pass ...
Converts json string numerals to native python bignums.
381,764
def example_lab_to_ipt(): print("=== Simple Example: XYZ->IPT ===") xyz = XYZColor(0.5, 0.5, 0.5, illuminant=) print(xyz) ipt = convert_color(xyz, IPTColor) print(ipt) print("=== End Example ===\n")
This function shows a simple conversion of an XYZ color to an IPT color.
381,765
def render_tile(cells, ti, tj, render, params, metadata, layout, summary): image_size = params["cell_size"] * params["n_tile"] tile = Image.new("RGB", (image_size, image_size), (255,255,255)) keys = cells.keys() for i,key in enumerate(keys): print("cell", i+1, "/", len(keys), end=) cell_image = rende...
Render each cell in the tile and stitch it into a single image
381,766
def get_bins_by_query(self, bin_query): if self._catalog_session is not None: return self._catalog_session.get_catalogs_by_query(bin_query) query_terms = dict(bin_query._query_terms) collection = JSONClientValidated(, ...
Gets a list of ``Bins`` matching the given bin query. arg: bin_query (osid.resource.BinQuery): the bin query return: (osid.resource.BinList) - the returned ``BinList`` raise: NullArgument - ``bin_query`` is ``null`` raise: OperationFailed - unable to complete request raise:...
381,767
def flattennd(d, levels=0, key_as_tuple=True, delim=, list_of_dicts=None): if levels < 0: raise ValueError() new_d = {} flattened = flatten(d, True, delim, list_of_dicts=list_of_dicts) if levels == 0: return flattened for key, value in flattened.items(): ...
get nested dict as {key:dict,...}, where key is tuple/string of all-n levels of nested keys Parameters ---------- d : dict levels : int the number of levels to leave unflattened key_as_tuple : bool whether keys are list of nested keys or delimited string of nested keys delim...
381,768
def display_notes(self): if self.annot is not None: short_xml_file = short_strings(basename(self.annot.xml_file)) self.idx_annotations.setText(short_xml_file) if self.parent.overview.scene is None: self.parent.overview.update() ...
Display information about scores and raters.
381,769
def set_primary_key_auto(self, table): pk = self.get_primary_key(table) if not pk: unique_col = self.get_unique_column(table) if unique_col: self.set_primary_key(table, unique_col) else: ...
Analysis a table and set a primary key. Determine primary key by identifying a column with unique values or creating a new column. :param table: Table to alter :return: Primary Key column
381,770
def copy_folder_content(src, dst): for file in os.listdir(src): file_path = os.path.join(src, file) dst_file_path = os.path.join(dst, file) if os.path.isdir(file_path): shutil.copytree(file_path, dst_file_path) else: shutil.copyfile(file_path, dst_file_pa...
Copy all content in src directory to dst directory. The src and dst must exist.
381,771
def cdsthreads(self): for i in range(self.cpus): threads = Thread(target=self.cds, args=()) threads.setDaemon(True) threads.start() for sample in self.metadata.samples: sample[self.analy...
Determines which core genes from a pre-calculated database are present in each strain
381,772
def get_email_context(self, activation_key): scheme = if self.request.is_secure() else return { : scheme, : activation_key, : settings.ACCOUNT_ACTIVATION_DAYS, : get_current_site(self.request) }
Build the template context used for the activation email.
381,773
def get_middle_point(self): num_rows, num_cols = self.lons.shape mid_row = num_rows // 2 depth = 0 if num_rows & 1 == 1: mid_col = num_cols // 2 if num_cols & 1 == 1: depth = self.depths[mid_r...
Return the middle point of the mesh. :returns: An instance of :class:`~openquake.hazardlib.geo.point.Point`. The middle point is taken from the middle row and a middle column of the mesh if there are odd number of both. Otherwise the geometric mean point of two or four midd...
381,774
def get_suppressions(relative_filepaths, root, messages): paths_to_ignore = set() lines_to_ignore = defaultdict(set) messages_to_ignore = defaultdict(lambda: defaultdict(set)) for filepath in relative_filepaths: abspath = os.path.join(root, filepath) try: file_con...
Given every message which was emitted by the tools, and the list of files to inspect, create a list of files to ignore, and a map of filepath -> line-number -> codes to ignore
381,775
def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None, network_type=, timeout=180, memory=None, max_query_area_size=50*1000*50*1000, custom_osm_filter=None): if custom_osm_filter is None: request_filter = os...
Download OSM ways and nodes within a bounding box from the Overpass API. Parameters ---------- lat_min : float southern latitude of bounding box lng_min : float eastern longitude of bounding box lat_max : float northern latitude of bounding box lng_max : float we...
381,776
def compute_before_after(self): if not self.parsed: self._parse() list_from = self.input_lines list_to = [] last = 0 for e in self.docs_list: start, end = e[] if start <= 0: start, end = -start, -end lis...
Compute the list of lines before and after the proposed docstring changes. :return: tuple of before,after where each is a list of lines of python code.
381,777
def _get_node_column(cls, node, column_name): if not hasattr(node, ): node.set(, {}) if column_name in node.columns: column = node.columns[column_name] else: column = {: column_name, : } node.columns[column_name] = column return ...
Given a ParsedNode, add some fields that might be missing. Return a reference to the dict that refers to the given column, creating it if it doesn't yet exist.
381,778
def get_active_project_path(self): active_project_path = None if self.current_active_project: active_project_path = self.current_active_project.root_path return active_project_path
Get path of the active project
381,779
def child_allocation(self): sum = Decimal(0) if self.classes: for child in self.classes: sum += child.child_allocation else: sum = self.allocation return sum
The sum of all child asset classes' allocations
381,780
def get_index_by_alias(self, alias): try: info = self.es.indices.get_alias(name=alias) return next(iter(info.keys())) except elasticsearch.exceptions.NotFoundError: return alias
Get index name for given alias. If there is no alias assume it's an index. :param alias: alias name
381,781
def strings(self, otherchar=None): string = [ otherchar if char == fsm.anything_else else char for char in string ] yield "".join(string)
Each time next() is called on this iterator, a new string is returned which will the present lego piece can match. StopIteration is raised once all such strings have been returned, although a regex with a * in may match infinitely many strings.
381,782
def get_element_name(parent, ns): name = parent.find( + ns + ) if name is not None and name.text is not None: return name.text return ""
Get element short name.
381,783
def get_config_groups(self, groups_conf, groups_pillar_name): log.debug(, ret_groups) return ret_groups
get info from groups in config, and from the named pillar todo: add specification for the minion to use to recover pillar
381,784
def _clean(self, rmConnetions=True, lockNonExternal=True): if self._interfaces: for i in self._interfaces: i._clean(rmConnetions=rmConnetions, lockNonExternal=lockNonExternal) else: self._sigInside = self._sig del sel...
Remove all signals from this interface (used after unit is synthesized and its parent is connecting its interface to this unit)
381,785
def getMetricDetails(self, metricLabel): try: metricIndex = self.__metricLabels.index(metricLabel) except IndexError: return None return self.__metrics[metricIndex].getMetric()
Gets detailed info about a given metric, in addition to its value. This may including any statistics or auxilary data that are computed for a given metric. :param metricLabel: (string) label of the given metric (see :class:`~nupic.frameworks.opf.metrics.MetricSpec`) :returns: (dict) of met...
381,786
def _parse_group(self, group_name, group): if type(group) == dict: hostnames_in_group = set() fo...
Parse a group definition from a dynamic inventory. These are top-level elements which are not '_meta(data)'.
381,787
def frets_to_NoteContainer(self, fingering): res = [] for (string, fret) in enumerate(fingering): if fret is not None: res.append(self.get_Note(string, fret)) return NoteContainer(res)
Convert a list such as returned by find_fret to a NoteContainer.
381,788
def _assemble_active_form(self, stmt): act_agent = Agent(stmt.agent.name, db_refs=stmt.agent.db_refs) act_agent.activity = ActivityCondition(stmt.activity, True) activates = stmt.is_active relation = get_causal_edge(stmt, activates) self._add_nodes_edges(stmt.agent, act_...
Example: p(HGNC:ELK1, pmod(Ph)) => act(p(HGNC:ELK1), ma(tscript))
381,789
def connectQ2Q(self, fromAddress, toAddress, protocolName, protocolFactory, usePrivateCertificate=None, fakeFromDomain=None, chooser=None): if chooser is None: chooser = lambda x: x and [x[0]] def onSecureConnection(protocol): if fa...
Connect a named protocol factory from a resource@domain to a resource@domain. This is analagous to something like connectTCP, in that it creates a connection-oriented transport for each connection, except instead of specifying your credentials with an application-level (username, ...
381,790
def get(self): return tuple([(x.name(), x.get()) for x in self._generators])
Retrieve the most recent value generated
381,791
def report(self, event, metadata=None, block=None): if self._sender.is_terminated: self._notify(logging.ERROR, consts.LOG_MSG_REPORT_AFTER_TERMINATION) return False if isinstance(event, (dict,) + py2to3.basestring): formatted_event = self._...
Reports an event to Alooma by formatting it properly and placing it in the buffer to be sent by the Sender instance :param event: A dict / string representing an event :param metadata: (Optional) A dict with extra metadata to be attached to the event :param bl...
381,792
def network_security_group_delete(name, resource_group, **kwargs): result = False netconn = __utils__[](, **kwargs) try: secgroup = netconn.network_security_groups.delete( resource_group_name=resource_group, network_security_group_name=name ) secgroup.wai...
.. versionadded:: 2019.2.0 Delete a network security group within a resource group. :param name: The name of the network security group to delete. :param resource_group: The resource group name assigned to the network security group. CLI Example: .. code-block:: bash salt-call ...
381,793
def _delete(self, state=None): mutation_val = data_v2_pb2.Mutation.DeleteFromRow() mutation_pb = data_v2_pb2.Mutation(delete_from_row=mutation_val) self._get_mutations(state).append(mutation_pb)
Helper for :meth:`delete` Adds a delete mutation (for the entire row) to the accumulated mutations. ``state`` is unused by :class:`DirectRow` but is used by subclasses. :type state: bool :param state: (Optional) The state that is passed along to :...
381,794
def p(self, value, event): assert isinstance(value, bool) ptrue = self.cpt[event_values(event, self.parents)] return if_(value, ptrue, 1 - ptrue)
Return the conditional probability P(X=value | parents=parent_values), where parent_values are the values of parents in event. (event must assign each parent a value.) >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625}) >>> bn.p(False, {'Burglary': False, 'Earthquake': True})...
381,795
def configure(self, options, conf): super(LeakDetectorPlugin, self).configure(options, conf) if options.leak_detector_level: self.reporting_level = int(options.leak_detector_level) self.report_delta = options.leak_detector_report_delta self.patch_mock = options.leak_...
Configure plugin.
381,796
def lock(self): self.update() self.execute_operations(False) self._lock = True return self
Prepare the installer for locking only.
381,797
def downgrade(): op.drop_column(, ) op.drop_column(, ) op.drop_column(, ) op.drop_column(, ) op.drop_column(, ) op.drop_column(, )
Downgrade database.
381,798
def solve_gamlasso(self, lam): weights = lam / (1 + self.gamma * np.abs(self.beta[self.trails[::2]] - self.beta[self.trails[1::2]])) s = self.solve_gfl(u) self.steps.append(s) return self.beta
Solves the Graph-fused gamma lasso via POSE (Taddy, 2013)
381,799
def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)): if isinstance(orb, (list, tuple)): tle1, tle2 = orb orb = Orbital("mysatellite", line1=tle1, line2=tle2) pos, vel = orb.get_position(times, normalize=False) vectors = sgeom.vectors(pos, vel, *rpy) ...
Compute cartesian coordinates of the pixels in instrument scan.