Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
382,800
def flush(self): address = self.remote_address while len(self._batches) > 0: self._socket.sendto(self._batches[0], address) self._batches.popleft() return self
Send buffered metrics in batch requests
382,801
def fetch_raw(self): for results in super(LogQuery, self).execute(): if in results and results[]: yield results[]
Execute the query and return by batches. Optional keyword arguments are passed to Query.execute(). Whether this is real-time or stored logs is dependent on the value of ``fetch_type``. :return: generator of dict results
382,802
def response_handler(msg: Dict[str, str]) -> None: from wdom.document import getElementByWdomId id = msg[] elm = getElementByWdomId(id) if elm: elm.on_response(msg) else: logger.warning(.format(id))
Handle response sent by browser.
382,803
def estimate_noiseperbl(data): datamean = data.mean(axis=2).imag (datameanmin, datameanmax) = rtlib.sigma_clip(datamean.flatten()) good = n.where( (datamean>datameanmin) & (datamean<datameanmax) ) noiseperbl = datamean[good].std() logger.debug( % (100.*len(goo...
Takes large data array and sigma clips it to find noise per bl for input to detect_bispectra. Takes mean across pols and channels for now, as in detect_bispectra.
382,804
def worker(self): fullseqs = self.sample_loci() liters = itertools.product(*self.imap.values()) hashval = uuid.uuid4().hex weights = [] for ridx, lidx in enumerate(liters): a,b,c,d = lidx sub = {} for i in lidx: if self.rma...
Calculates the quartet weights for the test at a random subsampled chunk of loci.
382,805
def from_config(cls, config, name, section_key="score_caches"): sentinel_logger.info("Loading RedisSentinel from config.".format(name)) section = config[section_key][name] kwargs = {k: v for k, v in section.items() if k != "class"} return cls.from_parameters(**kwargs)
score_caches: redis_sentinel: class: ores.score_caches.RedisSentinel prefix: ores-derp ttl: 9001 socket_timeout: 0.1 cluster: mymaster hosts: - localhost:5000 - localhost:5001 ...
382,806
def most_probable_alleles(allele_list): all_alleles = defaultdict() for allele, pvalue in allele_list: allele = re.split(, allele) if len(allele) < 2: continue allele = .join([allele[0], allele[1]]) try: all_alleles[a...
This module accepts a list of tuples of (allele, p_value) pairs. It returns the 2 most probable alleles for that group.
382,807
def package_info(pkg_name): indent = " " for config, _ in _iter_packages(): if pkg_name == config["name"]: print("Package:", pkg_name) print(indent, "Platform:", config["platform"]) print(indent, "Version:", config["version"]) print(indent, "Path:", ...
Prints the information of a package. Args: pkg_name (str): The name of the desired package to get information
382,808
def line(self, plunge, bearing, *args, **kwargs): lon, lat = stereonet_math.line(plunge, bearing) args, kwargs = self._point_plot_defaults(args, kwargs) return self.plot([lon], [lat], *args, **kwargs)
Plot points representing linear features on the axes. Additional arguments and keyword arguments are passed on to `plot`. Parameters ---------- plunge, bearing : number or sequence of numbers The plunge and bearing of the line(s) in degrees. The plunge is measur...
382,809
def variance(numbers, type=): mean = average(numbers) variance = 0 for number in numbers: variance += (mean - number) ** 2 if type == : return variance / len(numbers) else: return variance / (len(numbers) - 1)
Calculates the population or sample variance of a list of numbers. A large number means the results are all over the place, while a small number means the results are comparatively close to the average. Args: numbers: a list of integers or floating point numbers to compare. type: string, ...
382,810
def domain(value, allow_empty = False, allow_ips = False, **kwargs): is_recursive = kwargs.pop(, False) if not value and not allow_empty: raise errors.EmptyValueError( % value) elif not value: return None if not isinstance(value, basestring): ...
Validate that ``value`` is a valid domain name. .. caution:: This validator does not verify that ``value`` **exists** as a domain. It merely verifies that its contents *might* exist as a domain. .. note:: This validator checks to validate that ``value`` resembles a valid domain name....
382,811
def calcTightAnchors(args, d, patches): centerPoint = (int(args.worldSize/2), int(args.worldSize/2)) anchors = [] if patches == 0: pass elif patches == 1: anchors.append(centerPoint) elif patches % 2 == 0: dsout = int((patches-2)//2) + 1 add_anchors(centerPoint...
Recursively generates the number of anchor points specified in the patches argument, such that all patches are d cells away from their nearest neighbors.
382,812
def create_conf_file (self): cmd_obj = self.distribution.get_command_obj("install") cmd_obj.ensure_finalized() data = [] for d in [, , , , , ]: attr = % d if cmd_obj.root: cutoff = len(cmd_obj.r...
Create configuration file.
382,813
def _set_config(c): glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c[]) glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c[]) glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c[]) glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c[]) glfw.glfwWindowHint(glfw.GLFW_ACCUM_RED_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_...
Set gl configuration for GLFW
382,814
def video_in_option(self, param, profile=): if profile == : field = param else: field = .format(profile, param) return utils.pretty( [opt for opt in self.video_in_options.split() if .format(field) in opt][0])
Return video input option. Params: param - parameter, such as 'DayNightColor' profile - 'Day', 'Night' or 'Normal'
382,815
def open(self): if self._rpc is not None: return self._rpc self.load_config() if not config.scgi_url: raise error.UserError("You need to configure a XMLRPC connection, read" " https://pyrocore.readthedocs.io/en/latest/...
Open connection.
382,816
def convert_table(self, markup): for table in re.findall(self.re["html-table"], markup): wiki = table wiki = re.sub(r"<table(.*?)>", "{|\\1", wiki) wiki = re.sub(r"<tr(.*?)>", "|-\\1", wiki) wiki = re.sub(r"<td(.*?)>", "|\\1|", wiki) ...
Subtitutes <table> content to Wikipedia markup.
382,817
def merge(self, schema): for item in schema.attributes.items(): if item[0] in self.attributes: continue self.all.append(item[1]) self.attributes[item[0]] = item[1] for item in schema.elements.items(): if item[0] in self.elements: ...
Merge the contents from the schema. Only objects not already contained in this schema's collections are merged. This is to provide for bidirectional import which produce cyclic includes. @returns: self @rtype: L{Schema}
382,818
def _setup_redis(self): if not self.closed: try: self.logger.debug("Creating redis connection to host " + str(self.settings[])) self.redis_conn = redis.StrictRedis(host=self.settings[], ...
Returns a Redis Client
382,819
def convert_column(data, schemae): ctype = schemae.converted_type if ctype == parquet_thrift.ConvertedType.DECIMAL: scale_factor = Decimal("10e-{}".format(schemae.scale)) if schemae.type == parquet_thrift.Type.INT32 or schemae.type == parquet_thrift.Type.INT64: return [Decimal(u...
Convert known types from primitive to rich.
382,820
def _add_scheme(): lists = [ urllib.parse.uses_relative, urllib.parse.uses_netloc, urllib.parse.uses_query, ] for l in lists: l.append()
urllib.parse doesn't support the mongodb scheme, but it's easy to make it so.
382,821
def get_body_region(defined): scope = defined.get_scope() pymodule = defined.get_module() lines = pymodule.lines node = defined.get_ast() start_line = node.lineno if defined.get_doc() is None: start_line = node.body[0].lineno elif len(node.body) > 1: start_line = node.bo...
Return the start and end offsets of function body
382,822
def delta_crl_distribution_points(self): if self._delta_crl_distribution_points is None: self._delta_crl_distribution_points = [] if self.freshest_crl_value is not None: for distribution_point in self.freshest_crl_value: distribution_point_n...
Returns delta CRL URLs - only applies to complete CRLs :return: A list of zero or more DistributionPoint objects
382,823
def on_train_begin(self, **kwargs:Any)->None: "Initializes the best value." self.best = float() if self.operator == np.less else -float()
Initializes the best value.
382,824
def get_selected_subassistant_path(self, **kwargs): path = [self] previous_subas_list = None currently_searching = self.get_subassistant_tree()[1] while settings.SUBASSISTANT_N_STRING.format(len(path) - 1) in kwargs and \ kwargs[settings.SUBASSISTANT_N_...
Recursively searches self._tree - has format of (Assistant: [list_of_subassistants]) - for specific path from first to last selected subassistants. Args: kwargs: arguments containing names of the given assistants in form of subassistant_0 = 'name', subassistant_1 = 'another_name...
382,825
def _browser_init(self): if self.session: return self.session = requests.Session() headers = {} if self.user_agent: headers[] = self.user_agent self.session.headers.update(headers) if self._auth_method in [None, "", "HTTPBasicAuth"]: ...
Init the browsing instance if not setup :rtype: None
382,826
def readShocks(self): for var_name in self.shock_vars: setattr(self,var_name,getattr(self,var_name+)[self.t_sim,:])
Reads values of shock variables for the current period from history arrays. For each var- iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:]. This method is only ever called if self.read_shocks is True. This can be achieved by using the method makeSho...
382,827
def getFingerprintForExpression(self, body, sparsity=1.0): return self._expressions.resolveExpression(self._retina, body, sparsity)
Resolve an expression Args: body, ExpressionOperation: The JSON encoded expression to be evaluated (required) sparsity, float: Sparsify the resulting expression to this percentage (optional) Returns: Fingerprint Raises: CorticalioException: if the ...
382,828
def ray_triangle_id(triangles, ray_origins, ray_directions, triangles_normal=None, tree=None, multiple_hits=True): triangles = np.asanyarray(triangles, dtype=np.float64) ray_origins = np.asanyarray(ray_origi...
Find the intersections between a group of triangles and rays Parameters ------------- triangles : (n, 3, 3) float Triangles in space ray_origins : (m, 3) float Ray origin points ray_directions : (m, 3) float Ray direction vectors triangles_normal : (n, 3) float Normal ve...
382,829
def register_service(cls, service): logger.debug(.format(service.name)) return local_store.instance.register(service)
Add a service to the thread's StackInABox instance. :param service: StackInABoxService instance to add to the test For return value and errors see StackInABox.register()
382,830
def _import_astorb_to_database( self, astorbDictList): self.log.info() print "Refreshing the orbital elements database table" dbSettings = self.settings["database settings"]["atlasMovers"] insert_list_of_dictionaries_into_database_tables( d...
*import the astorb orbital elements to database* **Key Arguments:** - ``astorbDictList`` -- the astorb database parsed as a list of dictionaries **Return:** - None
382,831
def persist(self): os.makedirs(self.__symbol_folder, exist_ok=True) os.makedirs(self.__aliases_folder, exist_ok=True) os.makedirs(self.__comments_folder, exist_ok=True) for name, sym in self.__symbols.items(): with open(self.__get_pickle_path(self.__symbol_folder, na...
Banana banana
382,832
def thumbnail(self): if self._thumbnail: return self._thumbnail thumbnail = self.meta.get(, [])[0] if thumbnail and isfile(join(self.src_path, thumbnail)): self._thumbnail = url_from_path(join( self.name, get_thumb(self.se...
Path to the thumbnail of the album.
382,833
def parse(self): for line in self.stream: line = line.rstrip() self.nline += 1 if self.SUPYBOT_EMPTY_REGEX.match(line): continue ts, msg = self._parse_supybot_timestamp(line) if self.SUPYBOT_EMPTY_COMMENT_REGEX.match(msg): ...
Parse a Supybot IRC stream. Returns an iterator of dicts. Each dicts contains information about the date, type, nick and body of a single log entry. :returns: iterator of parsed lines :raises ParseError: when an invalid line is found parsing the given stream
382,834
def compact_bucket(db, buck_key, limit): records = db.lrange(str(buck_key), 0, -1) loader = limits.BucketLoader(limit.bucket_class, db, limit, str(buck_key), records, stop_summarize=True) buck_record = msgpack.dumps(dict(bucket=loader.bucket.dehydrate(), ...
Perform the compaction operation. This reads in the bucket information from the database, builds a compacted bucket record, inserts that record in the appropriate place in the database, then removes outdated updates. :param db: A database handle for the Redis database. :param buck_key: A turnstile...
382,835
def fetch(self): soup = self.session.get_results_soup() self.courses = CoursesList(soup)
Fetch this student's courses page. It's recommended to do that when creating the object (this is the default) because the remote sessions are short.
382,836
def hdfFromKwargs(hdf=None, **kwargs): if not hdf: hdf = HDF() for key, value in kwargs.iteritems(): if isinstance(value, dict): for k,v in value.iteritems(): dkey = "%s.%s"%(key,k) args = {dkey:v} hdf...
If given an instance that has toHDF() method that method is invoked to get that object's HDF representation
382,837
def set_confound_pipeline(self, confound_pipeline): self.add_history(inspect.stack()[0][3], locals(), 1) if not os.path.exists(self.BIDS_dir + + confound_pipeline): print() self.get_pipeline_alternatives() else: self.confound_pipeline ...
There may be times when the pipeline is updated (e.g. teneto) but you want the confounds from the preprocessing pipieline (e.g. fmriprep). To do this, you set the confound_pipeline to be the preprocessing pipeline where the confound files are. Parameters ---------- confound_pipeline : ...
382,838
def rest(o) -> Optional[ISeq]: if o is None: return None if isinstance(o, ISeq): s = o.rest if s is None: return lseq.EMPTY return s n = to_seq(o) if n is None: return lseq.EMPTY return n.rest
If o is a ISeq, return the elements after the first in o. If o is None, returns an empty seq. Otherwise, coerces o to a seq and returns the rest.
382,839
def get_coords(x, y, params): n_x = x * 2.0 / params.plane_w * params.plane_ratio - 1.0 n_y = y * 2.0 / params.plane_h - 1.0 mb_x = params.zoom * n_x mb_y = params.zoom * n_y return mb_x, mb_y
Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary). :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Tuple containing the re-mapped coordinates in Man...
382,840
def read_entity(self, entity_id, mount_point=DEFAULT_MOUNT_POINT): api_path = .format( mount_point=mount_point, id=entity_id, ) response = self._adapter.get(url=api_path) return response.json()
Query an entity by its identifier. Supported methods: GET: /auth/{mount_point}/entity/id/{id}. Produces: 200 application/json :param entity_id: Identifier of the entity. :type entity_id: str :param mount_point: The "path" the secret engine was mounted on. :type moun...
382,841
def decompress(images, delete_png=False, delete_json=False, folder=None): if type(images) == str: return decompress([images]) filenames = copy(images) decompressed_images = [] for orig_filename in filenames: debug(.format(orig_filename)) try: filename...
Reverse compression from tif to png and save them in original format (ome.tif). TIFF-tags are gotten from json-files named the same as given images. Parameters ---------- images : list of filenames Image to decompress. delete_png : bool Wheter to delete PNG images. delete_j...
382,842
def add_line_to_file(self, line, filename, expect=None, shutit_pexpect_child=None, match_regexp=None, loglevel=logging.DEBUG): shutit_global.shutit_global_object.yield_to_draw() if isinstance(line, str): lines = [line] elif isinstance(line, list): lines = line match_regexp = None fail = False for ...
Deprecated. Use replace/insert_text instead. Adds line to file if it doesn't exist (unless Force is set, which it is not by default). Creates the file if it doesn't exist. Must be exactly the line passed in to match. Returns True if line(s) added OK, False if not. If you have a lot of non-unique lines to ...
382,843
def listfolder(p): for entry in scandir.scandir(p): if entry.is_dir(): yield entry.name
generator of list folder in the path. folders only
382,844
def handler_view(self, request, resource_name, ids=None): signal_request.send(sender=self, request=request) time_start = time.time() self.update_urls(request, resource_name=resource_name, ids=ids) resource = self.resource_map[resource_name] allowed_http_methods = resour...
Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse
382,845
def psicomputations(variance, Z, variational_posterior, return_psi2_n=False): mu = variational_posterior.mean S = variational_posterior.variance psi0 = (variance*(np.square(mu)+S)).sum(axis=1) Zv = variance * Z psi1 = np.dot(mu,Zv.T) if return_psi2_n: psi2 ...
Compute psi-statistics for ss-linear kernel
382,846
def subscribe(self, sr): if not sr.startswith(): sr = self.subreddit(sr).name data = dict(action=, sr=sr) j = self.post(, , data=data) return assert_truthy(j)
Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: `...
382,847
def resource(self, api_path=None, base_path=, chunk_size=None): if isinstance(self.token, dict): self.session = self._get_oauth_session() return super(OAuthClient, self).resource(api_path, base_path, chunk_size) raise MissingToken("You must set_token() before creating ...
Overrides :meth:`resource` provided by :class:`pysnow.Client` with extras for OAuth :param api_path: Path to the API to operate on :param base_path: (optional) Base path override :param chunk_size: Response stream parser chunk size (in bytes) :return: - :class:`Resource` obj...
382,848
def gen_etree(self): relations_elem = self.gen_relations() header = E() header.append(relations_elem) self.gen_body() tree = E() tree.append(header) body = E() for segment in self.body[]: body.append(segme...
convert an RST tree (DGParentedTree -> lxml etree)
382,849
def repeat(col, n): sc = SparkContext._active_spark_context return Column(sc._jvm.functions.repeat(_to_java_column(col), n))
Repeats a string column n times, and returns it as a new string column. >>> df = spark.createDataFrame([('ab',)], ['s',]) >>> df.select(repeat(df.s, 3).alias('s')).collect() [Row(s=u'ababab')]
382,850
def rename_pool(service, old_name, new_name): validator(value=old_name, valid_type=six.string_types) validator(value=new_name, valid_type=six.string_types) cmd = [, , service, , , , old_name, new_name] check_call(cmd)
Rename a Ceph pool from old_name to new_name :param service: six.string_types. The Ceph user name to run the command under :param old_name: six.string_types :param new_name: six.string_types :return: None
382,851
def register(cls, config={}): if cls.accessor is not None: if cls.instance is None: cls.instance = cls.accessor(config)
This function is basically a shortcut of boot for accessors that have only the config dict argument. Args ---- config (dict): the configuration dictionary
382,852
def service_running(service_name, **kwargs): if init_is_systemd(): return service(, service_name) else: if os.path.exists(_UPSTART_CONF.format(service_name)): try: cmd = [, service_name] for key, value in six.iteritems(kwargs): ...
Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance ...
382,853
def read(self): data = None while True: last_offset = self.tell() try: (chunk, record_type) = self.__try_read_record() if record_type == _RECORD_TYPE_NONE: self.__sync() elif record_type == _RECORD_TYPE_FULL: if data is not None: logging.w...
Reads record from current position in reader. Returns: original bytes stored in a single record.
382,854
def get_subnets_for_net(self, net): try: subnet_list = self.neutronclient.list_subnets(network_id=net) subnet_dat = subnet_list.get() return subnet_dat except Exception as exc: LOG.error("Failed to list subnet net %(net)s, Exc: %(exc)s", ...
Returns the subnets in a network.
382,855
async def get_access_token(consumer_key, consumer_secret, oauth_token, oauth_token_secret, oauth_verifier, **kwargs): client = BasePeonyClient(consumer_key=consumer_key, consumer_secret=consumer_secret, ...
get the access token of the user Parameters ---------- consumer_key : str Your consumer key consumer_secret : str Your consumer secret oauth_token : str OAuth token from :func:`get_oauth_token` oauth_token_secret : str OAuth token secret from :func:`get_oauth_tok...
382,856
def create_pipeline(self, name, description, **kwargs): if not (name and description): return requests.codes.bad_request, None kwargs.update({:name, :description}) new_pl = StreakPipeline(**kwargs) uri = .join([ self.api_uri, self.pipelines_suffix ]) code, r_data = self._req(, uri...
Creates a pipeline with the provided attributes. Args: name required name string kwargs {name, description, orgWide, aclEntries} user specifiable ones only return (status code, pipeline_dict) (as created)
382,857
def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT): start_ms = time.time() * 1000.0 stop_ms = start_ms + (timeout * 1000.0) for x in range(int(timeout * 10)): try: alert = driver.switch_to.alert dummy_variable = alert.text ...
Wait for a browser alert to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.alert when the alert box may not exist yet. @Params driver - the webdriver object (required) timeout - the time to wait for the alert in seconds
382,858
def clearData(self): self._counts = np.zeros_like(self._bins) self.histo.setOpts(height=self._counts)
Clears all histograms (keeps bins)
382,859
def first_time_setup(self): if not self._auto_unlock_key_position(): pw = password.create_passwords()[0] attrs = {: self.keyring} gkr.item_create_sync(self.default_keyring ,gkr.ITEM_GENERIC_SECRET ,self...
First time running Open Sesame? Create keyring and an auto-unlock key in default keyring. Make sure these things don't already exist.
382,860
def sample(self, fraction, seed=None, exact=False): if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) if (fraction > 1 or fraction < 0): raise ValueError( + str(fraction)) if (self.num_rows() == 0 or self.num_columns() == 0): re...
Sample a fraction of the current SFrame's rows. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the number of rows returned is approximately the fraction times the number of rows. ...
382,861
def _str_to_datetime(self, str_value): try: ldt = [int(f) for f in str_value.split()] dt = datetime.datetime(*ldt) except (ValueError, TypeError): return None return dt
Parses a `YYYY-MM-DD` string into a datetime object.
382,862
def render_to_response(self, context, **response_kwargs): response_kwargs[] = return self.response_class( self.convert_context_to_json(context), **response_kwargs )
Returns a JSON response, transforming 'context' to make the payload.
382,863
def execute(self, query, args=None): del self.messages[:] db = self._get_db() if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) if args is not None: query = query % db.literal(args) try: r = None ...
Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as th...
382,864
def x_runtime(f, *args, **kwargs): _t0 = now() r = f(*args, **kwargs) _t1 = now() r.headers[] = .format(Decimal(str(_t1 - _t0))) return r
X-Runtime Flask Response Decorator.
382,865
def _update_resource_view(self, log=False): update = False if in self.data and self._load_from_hdx(, self.data[]): update = True else: if in self.data: resource_views = self.get_all_for_resource(self.data[]) for resource...
Check if resource view exists in HDX and if so, update resource view Returns: bool: True if updated and False if not
382,866
def pseudo_organization(organization, classification, default=None): if organization and classification: raise ScrapeValueError() elif classification: return _make_pseudo_id(classification=classification) elif organization: if isinstance(organization, Organization): ...
helper for setting an appropriate ID for organizations
382,867
def wait_pid(pid, timeout=None, callback=None): def check_timeout(delay): if timeout is not None: if time.time() >= stop_at: if callback: callback(pid) else: raise TimeoutExpired time.sleep(delay) return...
Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expi...
382,868
def call(self): from wx_loader import wx dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default)) if dlg.ShowModal() != wx.ID_OK: return None return dlg.GetValue()
show a value dialog
382,869
def _single_tree_paths(self, tree): skel = tree.consolidate() tree = defaultdict(list) for edge in skel.edges: svert = edge[0] evert = edge[1] tree[svert].append(evert) tree[evert].append(svert) def dfs(path, visited): paths = [] stack = [ (path, visited) ] ...
Get all traversal paths from a single tree.
382,870
def get_module_name(package): distribution = get_distribution(package.DISTRIBUTION_NAME) entry_info = distribution.get_entry_info(package.DIST_GROUP, package.ENTRY_POINT) if not entry_info: raise RuntimeError( "Can't find entry info for distribution: %r (group: %r, entry point: %r)"...
package must have these attributes: e.g.: package.DISTRIBUTION_NAME = "DragonPyEmulator" package.DIST_GROUP = "console_scripts" package.ENTRY_POINT = "DragonPy" :return: a string like: "dragonpy.core.cli"
382,871
def template_subst(template, subs, delims=(, )): subst_text = template for (k,v) in subs.items(): subst_text = subst_text.replace( delims[0] + k + delims[1], v) return subst_text
Perform substitution of content into tagged string. For substitutions into template input files for external computational packages, no checks for valid syntax are performed. Each key in `subs` corresponds to a delimited substitution tag to be replaced in `template` by the entire text of the value...
382,872
def emit(self, action, event, **kwargs): for listener in self._listeners: listener.put_nowait((action, event, kwargs))
Send an event to all the client listening for notifications :param action: Action name :param event: Event to send :param kwargs: Add this meta to the notification (project_id for example)
382,873
def find_document_type_by_name(self, entity_name, active=, match_case=True): all_types = self.get_dictionary() if match_case: filtered = filter( lambda x: x[] == active and x[].find(entity_name) >= 0, all_types) ...
search document types by name and active(Y/N) status :param entity_name: entity name :return:
382,874
def normalize_volume(volume): idAU0paPZOMZchuDv1iDv8typevolumemetadata_languageenkey1value1key2value2key3value3attachmentsida910e1kjdo2d192d1dko1p2kd1209dtypeattachmenturlfsdb:///624bffa8a6f90813b7982d0e5b4c1475ebec40e3metadatadownload_countmimeapplication/jsonnametmp9fyat_notesthis file is awsomesha1624bffa8a6...
convert volume metadata from es to archivant format This function makes side effect on input volume output example:: { 'id': 'AU0paPZOMZchuDv1iDv8', 'type': 'volume', 'metadata': {'_language': 'en', 'key1': ...
382,875
def _set_zoning(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=zoning.zoning, is_container=, presence=False, yang_name="zoning", rest_name="zoning", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensi...
Setter method for zoning, mapped from YANG variable /zoning (container) If this variable is read-only (config: false) in the source YANG file, then _set_zoning is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_zoning() directly.
382,876
def dumps(self, contentType=None, version=None): buf = six.StringIO() ret = self.dump(buf, contentType, version) if ret is None: return buf.getvalue() return (ret[0], ret[1], buf.getvalue())
[OPTIONAL] Identical to :meth:`dump`, except the serialized form is returned as a string representation. As documented in :meth:`dump`, the return value can optionally be a three-element tuple of (contentType, version, data) if the provided content-type should be overridden or enhanced. The default impl...
382,877
def isin_start(elems, line): found = False elems = [elems] if type(elems) is not list else elems for e in elems: if line.lstrip().lower().startswith(e): found = True break return found
Check if an element from a list starts a string. :type elems: list :type line: str
382,878
def get_languages(self): headers, data = self._requester.requestJsonAndCheck( "GET", self.url + "/languages" ) return data
:calls: `GET /repos/:owner/:repo/languages <http://developer.github.com/v3/repos>`_ :rtype: dict of string to integer
382,879
def _get_cache_size(replace=False): if not replace: size = _cached_search_compile.cache_info().currsize else: size = _cached_replace_compile.cache_info().currsize return size
Get size of cache.
382,880
def get_session_identifiers(cls, folder=None, inputfile=None): sessions = [] if inputfile and folder: raise MQ2Exception( ) if folder: if not os.path.isdir(folder): return sessions for root, dirs, files in os.walk(folde...
Retrieve the list of session identifiers contained in the data on the folder or the inputfile. For this plugin, it returns the list of excel sheet available. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inpu...
382,881
def walk_revctrl(dirname=, ff=): file_finder = None items = [] if not ff: distutils.log.error() sys.exit(1) for ep in pkg_resources.iter_entry_points(): if ff == ep.name: distutils.log.info(, ep.name) file_finder = ep.load() finder_items...
Return files found by the file-finder 'ff'.
382,882
def _check_env_vars_set(self, dir_env_var, file_env_var): return ( os.environ.get(file_env_var) is not None or os.environ.get(dir_env_var) is not None )
Check to see if the default cert dir/file environment vars are present. :return: bool
382,883
def _get_subject_uri(self, guid=None): uri = self.uri + if guid: uri += + urllib.quote_plus(guid) return uri
Returns the full path that uniquely identifies the subject endpoint.
382,884
def _get_list(self, key, operation, create=False): return self._get_by_type(key, operation, create, b, [])
Get (and maybe create) a list by name.
382,885
def _init_draw(self): if self.original is not None: self.original.set_data(np.random.random((10, 10, 3))) self.processed.set_data(np.random.random((10, 10, 3)))
Initializes the drawing of the frames by setting the images to random colors. This function is called by TimedAnimation.
382,886
def walkscan(x0, y0, xn=0.25, xp=0.25, yn=0.25, yp=0.25): if xn < 0: raise ValueError("Negative x probabilty must be non-negative") if xp < 0: raise ValueError("Positive x probabilty must be non-negative") if yn < 0: raise ValueError("Negative y probabilty must be non-negative") if yp < 0: ra...
Scan pixels in a random walk pattern with given step probabilities. The random walk will continue indefinitely unless a skip transformation is used with the 'stop' parameter set or a clip transformation is used with the 'abort' parameter set to True. The probabilities are normalized to sum to 1. :param...
382,887
def add(i): r=ck.check_writing({:work[]}) if r[]>0: return r o=i.get(,) r=ck.access({:, :work[], :work[], :}) if r[]>0: return r p=r[] pm=os.path.join(p,cfg[]) pma=os.path.join(p,cfg[]) r=ck.load_text_file({:...
Input: { (repo_uoa) - repo UOA module_uoa - normally should be 'module' already data_uoa - UOA of the module to be created (desc) - module description (license) - module license (cop...
382,888
def df2arff(df, dataset_name, pods_data): def java_simple_date(date_format): date_format = date_format.replace(, ).replace(, ).replace(, ).replace(, ) return date_format.replace(, ).replace(, ).replace(, ).replace(, ) def tidy_field(atr): return str(atr).replace(, ).replace(, )...
Write an arff file from a data set loaded in from pods
382,889
def outliers(df,output_type = ,dtype = ,sensitivity = 1.5): if dtype in (,,,): if not dtype == : df = pd.to_numeric(df,errors = ) quart25, quart75 = percentiles(df,q = [.25,.75]) out_range= sensitivity * (quart75 - quart25) lower_bound,upper_bound = quart25-out_rang...
Returns potential outliers as either a boolean array or a subset of the original. Parameters: df - array_like Series or dataframe to check output_type - string, default 'values' if 'values' is specified, then will output the values in the series that are suspected outliers. Else, a b...
382,890
def Read(self, length): if not self.IsFile(): raise IOError("%s is not a file." % self.pathspec.last.path) available = min(self.size - self.offset, length) if available > 0: try: data = self.fd.read_random(self.offset, available, self.paths...
Read from the file.
382,891
def weight_layers(name, bilm_ops, l2_coef=None, use_top_only=False, do_layer_norm=False, reuse=False): def _l2_regularizer(weights): if l2_coef is not None: return l2_coef * tf.reduce_sum(tf.square(weights)) else: return 0.0 lm_embeddings = bi...
Weight the layers of a biLM with trainable scalar weights to compute ELMo representations. For each output layer, this returns two ops. The first computes a layer specific weighted average of the biLM layers, and the second the l2 regularizer loss term. The regularization terms are also ad...
382,892
def prep_vrn_file(in_file, vcaller, work_dir, somatic_info, writer_class, seg_file=None, params=None): data = somatic_info.tumor_data if not params: params = PARAMS out_file = os.path.join(work_dir, "%s-%s-prep.csv" % (utils.splitext_plus(os.path.basename(in_file))[0], ...
Select heterozygous variants in the normal sample with sufficient depth. writer_class implements write_header and write_row to write VCF outputs from a record and extracted tumor/normal statistics.
382,893
def _send(self, data): if not self._sock: self.connect() self._do_send(data)
Send data to statsd.
382,894
def to_feather(self, fname): from pandas.io.feather_format import to_feather to_feather(self, fname)
Write out the binary feather-format for DataFrames. .. versionadded:: 0.20.0 Parameters ---------- fname : str string file path
382,895
def _label_path_from_index(self, index): label_file = os.path.join(self.data_path, , index + ) assert os.path.exists(label_file), .format(label_file) return label_file
given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file
382,896
def main(): parser = CommandLine() if len(sys.argv)==1: parser.parser.print_help() sys.exit(1) parser.parse() myArgs = parser.args procsPerAssembly = int(myArgs.maxProcs / myArgs.simultaneous) setattr(myArgs, "maxProcs", procsPerAssembly) ...
1. Reads in a meraculous config file and outputs all of the associated config files to $PWD/configs 2. The name of each run and the path to the directory is passed to a multiprocessing core that controls which assemblies are executed and when.
382,897
def _get_resource_type_cls(self, name, resource): if not in resource: raise ResourceTypeNotDefined(name) try: return self.inspect_resources[resource[]] except KeyError: for custom_member in self._custom_member...
Attempts to return troposphere class that represents Type of provided resource. Attempts to find the troposphere class who's `resource_type` field is the same as the provided resources `Type` field. :param resource: Resource to find troposphere class for :return: None: If no cla...
382,898
def _cond_select_value_nonrecur(d,cond_match=None,**kwargs): if( in kwargs): cond_func = kwargs[] else: cond_func = _text_cond if( in kwargs): cond_func_args = kwargs[] else: cond_func_args = [] rslt = {} for key in d: value = d[key] if(cond_f...
d = { "ActiveArea":"50829", "Artist":"315", "AsShotPreProfileMatrix":"50832", "AnalogBalance":"50727", "AsShotICCProfile":"50831", "AsShotProfileName":"50934", "AntiAliasStrength":"50738", ...
382,899
def get_issues(self, repo, keys): key1, key2 = keys key3 = key1[:-1] url = self.base_url + "/api/0/" + repo + "/" + key1 response = self.session.get(url, params=dict(status=)) if not bool(response): error = response.json() code = error[] ...
Grab all the issues