Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
383,800
def probability_gt(self, x): if self.mean is None: return p = normdist(x=x, mu=self.mean, sigma=self.standard_deviation) return 1-p
Returns the probability of a random variable being greater than the given value.
383,801
def _recv(self): recvd = [] self._lock.acquire() if not self._can_send_recv(): log.warning(, self) self._lock.release() return () while len(recvd) < self.config[]: try: data = self._sock.recv(self.config[]) ...
Take all available bytes from socket, return list of any responses from parser
383,802
def cmp_pkgrevno(package, revno, pkgcache=None): if not pkgcache: y = yum.YumBase() packages = y.doPackageLists() pkgcache = {i.Name: i.version for i in packages[]} pkg = pkgcache[package] if pkg > revno: return 1 if pkg < revno: return -1 return 0
Compare supplied revno with the revno of the installed package. * 1 => Installed revno is greater than supplied arg * 0 => Installed revno is the same as supplied arg * -1 => Installed revno is less than supplied arg This function imports YumBase function if the pkgcache argument is None.
383,803
def _restore(self, builder): builder.with_trashed() return builder.update({builder.get_model().get_deleted_at_column(): None})
The restore extension. :param builder: The query builder :type builder: orator.orm.builder.Builder
383,804
def parse_coach_bsites_inf(infile): bsites_results = [] with open(infile) as pp: lines = list(filter(None, (line.rstrip() for line in pp))) for i in range(len(lines) // 3): bsites_site_dict = {} line1 = lines[i * 3].split() line2 = lines[i * 3 + 1].split() li...
Parse the Bsites.inf output file of COACH and return a list of rank-ordered binding site predictions Bsites.inf contains the summary of COACH clustering results after all other prediction algorithms have finished For each site (cluster), there are three lines: - Line 1: site number, c-score of coa...
383,805
def get_link(self, rel): if rel in self.links: return self.links[rel] raise ResourceNotFound( % rel)
Return link for specified resource
383,806
def multiply(self, a, b): if a is None or b is None: return None m, n, l = len(a), len(b[0]), len(b[0]) if len(b) != n: raise Exception("As row number.") c = [[0 for _ in range(l)] for _ in range(m)] for i, row in enumerate(a): for k, eleA in enumerate(row): if eleA:...
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
383,807
async def generate_waifu_insult(self, avatar): if not isinstance(avatar, str): raise TypeError("type of must be str.") async with aiohttp.ClientSession() as session: async with session.post("https://api.weeb.sh/auto-image/waifu-insult", headers=self.__headers, data={"av...
Generate a waifu insult image. This function is a coroutine. Parameters: avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image Return Type: image data
383,808
def folderitem(self, obj, item, index): uid = api.get_uid(obj) url = api.get_url(obj) title = api.get_title(obj) if self.show_categories_enabled(): category = obj.getCategoryTitle() if category not in self.categories: self.categ...
Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current i...
383,809
def make_slice_key(cls, start_string, size_string): try: start = int(start_string) except ValueError: raise ValueError() if start < 0: raise ValueError( ) try: size = int(size_string) except Val...
Converts the given start and size query parts to a slice key. :return: slice key :rtype: slice
383,810
def ack(self, msg): self.log.info("receiverId <%s> Received: <%s> " % (self.receiverId, msg[])) return stomper.NO_REPONSE_NEEDED
Process the message and determine what to do with it.
383,811
def rec_update(self, other, **third): try: iterator = other.iteritems() except AttributeError: iterator = other self.iter_rec_update(iterator) self.iter_rec_update(third.iteritems())
Recursively update the dictionary with the contents of other and third like dict.update() does - but don't overwrite sub-dictionaries. Example: >>> d = RecursiveDictionary({'foo': {'bar': 42}}) >>> d.rec_update({'foo': {'baz': 36}}) >>> d {'foo': {'baz': 36, 'bar': 42}}
383,812
def get_content(self, key): LOGGER.debug("> Retrieving content from the cache.".format(self.__class__.__name__, key)) return self.get(key)
Gets given content from the cache. Usage:: >>> cache = Cache() >>> cache.add_content(John="Doe", Luke="Skywalker") True >>> cache.get_content("Luke") 'Skywalker' :param key: Content to retrieve. :type key: object :return: Con...
383,813
def ParseFileSystemsStruct(struct_class, fs_count, data): results = [] cstr = lambda x: x.split(b"\x00", 1)[0] for count in range(0, fs_count): struct_size = struct_class.GetSize() s_data = data[count * struct_size:(count + 1) * struct_size] s = struct_class(s_data) s.f_fstypename = cstr(s.f_fs...
Take the struct type and parse it into a list of structs.
383,814
def delmod_cli(argv, alter_logger=True): check_usage(delmod_doc, argv, usageifnoargs=True) if alter_logger: util.logger() cb = util.tools.calibrater() for mspath in argv[1:]: cb.open(b(mspath), addcorr=False, addmodel=False) cb.delmod(otf=True, scr=False) cb.close(...
Command-line access to ``delmod`` functionality. The ``delmod`` task deletes "on-the-fly" model information from a Measurement Set. It is so easy to implement that a standalone function is essentially unnecessary. Just write:: from pwkit.environments.casa import util cb = util.tools.calibrater...
383,815
def finalize_sv(samples, config): by_bam = collections.OrderedDict() for x in samples: batch = dd.get_batch(x) or [dd.get_sample_name(x)] try: by_bam[x["align_bam"], tuple(batch)].append(x) except KeyError: by_bam[x["align_bam"], tuple(batch)] = [x] by_ba...
Combine results from multiple sv callers into a single ordered 'sv' key.
383,816
def _preprocess_data(self, X, Y=None, idxs=None, train=False): C, F = X if issparse(F): F = np.array(F.todense(), dtype=np.float32) if Y is not None: Y = np.array(Y).astype(np.float32) if idxs is None: if Y is not None: retu...
Preprocess the data: 1. Convert sparse matrix to dense matrix. 2. Select subset of the input if idxs exists. :param X: The input data of the model. :type X: pair with candidates and corresponding features :param Y: The labels of input data. :type Y: list or numpy.array ...
383,817
def get_other_keys(self, key, including_current=False): other_keys = [] if key in self: other_keys.extend(self.__dict__[str(type(key))][key]) if not including_current: other_keys.remove(key) return other_keys
Returns list of other keys that are mapped to the same value as specified key. @param key - key for which other keys should be returned. @param including_current if set to True - key will also appear on this list.
383,818
def before(self, value): newq = self.copy() newq.setOp(Query.Op.Before) newq.setValue(value) return newq
Sets the operator type to Query.Op.Before and sets the value to the amount that this query should be lower than. This is functionally the same as doing the lessThan operation, but is useful for visual queries for things like dates. :param value | <variant> ...
383,819
def kfolds(n, k, sz, p_testset=None, seed=7238): trains, tests = split_rand(sz, p_testset, seed) ntrain = len(trains) with np_seed(seed): np.random.shuffle(trains) if n == k: train, valid = trains, trains else: foldsz = ntrain // k itrain = np.ar...
return train, valid [,test] testset if p_testset :param n: :param k: :param sz: :param p_testset: :param seed: :return:
383,820
def _encode_value(self, value): if isinstance(value, (int, float, str, bool, datetime)): return value elif isinstance(value, list): return [self._encode_value(item) for item in value] elif isinstance(value, dict): result = {} for key, item...
Encodes the value such that it can be stored into MongoDB. Any primitive types are stored directly into MongoDB, while non-primitive types are pickled and stored as GridFS objects. The id pointing to a GridFS object replaces the original value. Args: value (object): The obj...
383,821
def _callFunc(session, funcName, password, args): txid = _randomString() sock = session.socket sock.send(bytearray( % txid, )) msg = _getMessage(session, txid) cookie = msg[] txid = _randomString() tohash = (password + cookie).encode() req = { : funcName, : hashlib....
Call custom cjdns admin function
383,822
def _run(self): try: self.worker() except SystemExit as ex: if isinstance(ex.code, int): if ex.code is not None and ex.code != 0: self._shutdown( .format( ...
Run the worker function with some custom exception handling.
383,823
def stitch(network, donor, P_network, P_donor, method=, len_max=sp.inf, len_min=0, label_suffix=): rs name. To insert none of the donor labels, use None. len_max : float Set a length limit on length of new throats method : string (default = ) The method to use when makin...
r''' Stitches a second a network to the current network. Parameters ---------- networK : OpenPNM Network Object The Network to which to donor Network will be attached donor : OpenPNM Network Object The Network to stitch on to the current Network P_network : array_like ...
383,824
def children_sum( self, children,node ): return sum( [self.value(value,node) for value in children] )
Calculate children's total sum
383,825
async def base_combine(source, switch=False, ordered=False, task_limit=None): if task_limit is not None and not task_limit > 0: raise ValueError() async with StreamerManager() as manager: main_streamer = await manager.enter_and_create_task(source) while manage...
Base operator for managing an asynchronous sequence of sequences. The sequences are awaited concurrently, although it's possible to limit the amount of running sequences using the `task_limit` argument. The ``switch`` argument enables the switch mecanism, which cause the previous subsequence to be dis...
383,826
def view_list(self): done = set() ret = [] while len(done) != self.count(): p = self.view_indexes(done) if len(p) > 0: ret.append(p) return ret
return a list of polygon indexes lists for the waypoints
383,827
def cli(ctx, path, renku_home, use_external_storage): ctx.obj = LocalClient( path=path, renku_home=renku_home, use_external_storage=use_external_storage, )
Check common Renku commands used in various situations.
383,828
def parse_cookie(cookie: str) -> Dict[str, str]: cookiedict = {} for chunk in cookie.split(str(";")): if str("=") in chunk: key, val = chunk.split(str("="), 1) else: key, val = str(""), chunk key, val = key.strip(), val.strip() ...
Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. ....
383,829
def _footer(trigger, data, content): footer = EvernoteMgr.set_note_footer(data, trigger) content += footer return content
footer of the note :param trigger: trigger object :param data: data to be used :param content: add the footer of the note to the content :return: content string
383,830
def network_lpf(network, snapshots=None, skip_pre=False): _network_prepare_and_run_pf(network, snapshots, skip_pre, linear=True)
Linear power flow for generic network. Parameters ---------- snapshots : list-like|single snapshot A subset or an elements of network.snapshots on which to run the power flow, defaults to network.snapshots skip_pre: bool, default False Skip the preliminary steps of computing top...
383,831
def sequence_molecular_weight(seq): if in seq: warnings.warn(_nc_warning_str, NoncanonicalWarning) return sum( [residue_mwt[aa] * n for aa, n in Counter(seq).items()]) + water_mass
Returns the molecular weight of the polypeptide sequence. Notes ----- Units = Daltons Parameters ---------- seq : str Sequence of amino acids.
383,832
def overlapped_convolution(bin_template, bin_image, tollerance=0.5, splits=(4, 2)): th, tw = bin_template.shape ih, iw = bin_image.shape hs, ws = splits h = ih // hs w = iw // ws count = numpy.count_nonzero(bin_template) assert count > 0 assert h...
As each of these images are hold only binary values, and RFFT2 works on float64 greyscale values, we can make the convolution more efficient by breaking the image up into :splits: sectons. Each one of these sections then has its greyscale value adjusted and then stacked. We then apply the convolut...
383,833
def sort_descendants(self, attr="name"): node2content = self.get_cached_content(store_attr=attr, container_type=list) for n in self.traverse(): if not n.is_leaf(): n.children.sort(key=lambda x: str(sorted(node2content[x])))
This function sort the branches of a given tree by considerening node names. After the tree is sorted, nodes are labeled using ascendent numbers. This can be used to ensure that nodes in a tree with the same node names are always labeled in the same way. Note that if duplicated names ar...
383,834
def find_project_dir(): frame = inspect.currentframe() while True: frame = frame.f_back fname = frame.f_globals[] if os.path.basename(fname) == : break return os.path.dirname(fname)
Runs up the stack to find the location of manage.py which will be considered a project base path. :rtype: str|unicode
383,835
def _str_to_windows(self, input_str, window_length, curse_forward): windows = [] i = 0 len_input = len(input_str) while i < len_input: window_text = input_str[i:i+window_length] if self.sanitize_input: windows.append({ ...
Divide an input string to a list of substrings based on window_length and curse_forward values :param input_str: str :param window_length: int :param curse_forward: int :return: list [str]
383,836
def parse_cfgstr_name_options(cfgstr): r import utool as ut cfgname_regex = ut.named_field(, r) subx_regex = r + ut.named_field(, r) + r cfgopt_regex = re.escape(NAMEVARSEP) + ut.named_field(, ) regex_str = cfgname_regex + ( % (subx_regex,)) + ( % (cfgopt_regex,)) match = re.match(regex_st...
r""" Args: cfgstr (str): Returns: tuple: (cfgname, cfgopt_strs, subx) CommandLine: python -m utool.util_gridsearch --test-parse_cfgstr_name_options Example: >>> # ENABLE_DOCTEST >>> from utool.util_gridsearch import * # NOQA >>> import utool as ut ...
383,837
def i18n_system_locale(): log.debug() lc, encoding = locale.getlocale() log.debug(.format(lc=lc, encoding=encoding)) if lc is None: lc, encoding = locale.getdefaultlocale() log.debug(.format(lc=lc, encoding=encoding)) return lc
Return the system locale :return: the system locale (as a string)
383,838
def makeMarkovApproxToNormalByMonteCarlo(x_grid,mu,sigma,N_draws = 10000): random_draws = np.random.normal(loc = mu, scale = sigma, size = N_draws) distance = np.abs(x_grid[:,np.newaxis] - random_draws[np.newaxis,:]) distance_minimizing_index = np.argmin(distance,axis=0) ...
Creates an approximation to a normal distribution with mean mu and standard deviation sigma, by Monte Carlo. Returns a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = numpy.dot(p_vec,...
383,839
def _fill_table_entry(self, row, col): prefix = self._membership_query(row) full_output = self._membership_query(row + col) length = len(commonprefix([prefix, full_output])) self.observation_table[row, col] = full_output[length:]
Fill an entry of the observation table. Args: row (str): The row of the observation table col (str): The column of the observation table Returns: None
383,840
def translify(in_string, strict=True): translit = in_string for symb_in, symb_out in TRANSTABLE: translit = translit.replace(symb_in, symb_out) if strict and any(ord(symb) > 128 for symb in translit): raise ValueError("Unicode string doesn't transliterate completely, " + \ ...
Translify russian text @param in_string: input string @type in_string: C{unicode} @param strict: raise error if transliteration is incomplete. (True by default) @type strict: C{bool} @return: transliterated string @rtype: C{str} @raise ValueError: when string doesn't transliterat...
383,841
def set(self, key, val): key_lower = key.lower() new_vals = key, val vals = self._container.setdefault(key_lower, new_vals) if new_vals is not vals: self._container[key_lower] = [vals[0], vals[1], val]
Sets a header field with the given value, removing previous values. Usage:: headers = HTTPHeaderDict(foo='bar') headers.set('Foo', 'baz') headers['foo'] > 'baz'
383,842
def get_widget_label_for(self, fieldname, default=None): widget = self.get_widget_for(fieldname) if widget is None: return default return widget.label
Lookup the widget of the field and return the label
383,843
def relateObjectLocs(obj, entities, selectF): try: obj = obj.loc except AttributeError: pass try: func = obj.direct2dDistance except AttributeError: raise ValueError("object %s (%s) does not possess and is not a %s"%(obj, type(obj), MapPoint)) try...
calculate the minimum distance to reach any iterable of entities with a loc
383,844
def Brokaw(T, ys, mus, MWs, molecular_diameters, Stockmayers): r cmps = range(len(ys)) MDs = molecular_diameters if not none_and_length_check([ys, mus, MWs, molecular_diameters, Stockmayers]): raise Exception() Tsts = [T/Stockmayer_i for Stockmayer_i in Stockmayers] Sij = [[0 for i in c...
r'''Calculates viscosity of a gas mixture according to mixing rules in [1]_. .. math:: \eta_{mix} = \sum_{i=1}^n \frac{y_i \eta_i}{\sum_{j=1}^n y_j \phi_{ij}} \phi_{ij} = \left( \frac{\eta_i}{\eta_j} \right)^{0.5} S_{ij} A_{ij} A_{ij} = m_{ij} M_{ij}^{-0.5} \left[1 + \frac{M_{...
383,845
def _shrink(v, gamma): pos = v > gamma neg = v < -gamma v[pos] -= gamma v[neg] += gamma v[np.logical_and(~pos, ~neg)] = .0 return v
Soft-shrinkage of an array with parameter gamma. Parameters ---------- v : array Array containing the values to be applied to the shrinkage operator gamma : float Shrinkage parameter. Returns ------- v : array The same inpu...
383,846
def list_logs(self): results = [] for image in self._bucket.list_blobs(): if image.name.endswith(): results.append(image) if len(results) == 0: bot.info("No containers found, based on extension .log") return results
return a list of logs. We return any file that ends in .log
383,847
def get_merge_requests(self): "http://doc.gitlab.com/ce/api/merge_requests.html" g = self.gitlab merges = self.get(g[] + "/projects/" + g[] + "/merge_requests", {: g[], : }, cache=False) return dict([(str(merg...
http://doc.gitlab.com/ce/api/merge_requests.html
383,848
def _get_biallelic_variant(self, variant, info, _check_alleles=True): info = info.iloc[0, :] assert not info.multiallelic self._impute2_file.seek(info.seek) genotypes = self._parse_impute2_line(self._impute2_file.readline()) variant_alleles = variant._encode_a...
Creates a bi-allelic variant.
383,849
def model_returns_t_alpha_beta(data, bmark, samples=2000, progressbar=True): data_bmark = pd.concat([data, bmark], axis=1).dropna() with pm.Model() as model: sigma = pm.HalfCauchy( , beta=1) nu = pm.Exponential(, 1. / 10.) X = data_bmark.iloc[:, 1...
Run Bayesian alpha-beta-model with T distributed returns. This model estimates intercept (alpha) and slope (beta) of two return sets. Usually, these will be algorithm returns and benchmark returns (e.g. S&P500). The data is assumed to be T distributed and thus is robust to outliers and takes tail event...
383,850
def next_event_indexer(all_dates, data_query_cutoff, all_sids, event_dates, event_timestamps, event_sids): validate_event_metadata(event_dates, event_timestamps, event_sids) out = np.full((len...
Construct an index array that, when applied to an array of values, produces a 2D array containing the values associated with the next event for each sid at each moment in time. Locations where no next event was known will be filled with -1. Parameters ---------- all_dates : ndarray[datetime64[...
383,851
def phaseshift_isc(data, pairwise=False, summary_statistic=, n_shifts=1000, tolerate_nans=True, random_state=None): data, n_TRs, n_voxels, n_subjects = _check_timeseries_input(data) observed = isc(data, pairwise=pairwise, summary_statistic=summary_statisti...
Phase randomization for one-sample ISC test For each voxel or ROI, compute the actual ISC and p-values from a null distribution of ISCs where response time series are phase randomized prior to computing ISC. If pairwise, apply phase randomization to each subject and compute pairwise ISCs. If leave-...
383,852
def _set_ipv6_gateway_address(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("ipv6_gw_addr",ipv6_gateway_address.ipv6_gateway_address, yang_name="ipv6-gateway-address", rest_name="gateway-address", parent=self, is_container=, user_ordere...
Setter method for ipv6_gateway_address, mapped from YANG variable /interface_vlan/interface/ve/ipv6/ipv6_anycast_gateway/ipv6_gateway_address (list) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_gateway_address is considered as a private method. Backends looking to po...
383,853
def close(self, signalnum=None, frame=None): self._running = False self._log_debug("Closing all tail objects") self._active = False for fid in self._tails: self._tails[fid].close() for n in range(0,self._number_of_consumer_processes): if self._pro...
Closes all currently open Tail objects
383,854
def ListRecursivelyViaWalking(top): for dir_path, _, filenames in tf.io.gfile.walk(top, topdown=True): yield (dir_path, (os.path.join(dir_path, filename) for filename in filenames))
Walks a directory tree, yielding (dir_path, file_paths) tuples. For each of `top` and its subdirectories, yields a tuple containing the path to the directory and the path to each of the contained files. Note that unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlobbing, this does not list subdirectories...
383,855
def is_valid_ipv6(ip_str): try: socket.inet_pton(socket.AF_INET6, ip_str) except socket.error: return False return True
Check the validity of an IPv6 address
383,856
def install(self): with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_primary_button().click()
Confirm add-on install.
383,857
def parse_hstring(hs): name, value, comment = yield_three( [val.strip().strip("/'.join(comment) return name, value, comment
Parse a single item from the telescope server into name, value, comment.
383,858
def updateAltHistory(self): self.altHist.append(self.relAlt) self.timeHist.append(self.relAltTime) histLim = 10 currentTime = time.time() point = 0 for i in range(0,len(self.timeHist)): if (self.timeHist[i] > (currentTime - 10.0)): ...
Updates the altitude history plot.
383,859
def make_plus_fields(obj): fields = standard_fields.get(obj[], dict()) return _make_plus_helper(obj, fields)
Add a '+' to the key of non-standard fields. dispatch to recursive _make_plus_helper based on _type field
383,860
def build_fred(self): encoder = Encoder(data=self.dataset, config=self.model_config) decoder = Decoder(data=self.dataset, config=self.model_config, encoder=encoder) return EncoderDecoder(config=self.model_config, encoder=encoder, decoder=decoder, num_gpus=self.num_gpus) ...
Build a flat recurrent encoder-decoder dialogue model
383,861
def GetNetworkAddressWithTime(self): if self.port is not None and self.host is not None and self.Version is not None: return NetworkAddressWithTime(self.host, self.port, self.Version.Services) return None
Get a network address object. Returns: NetworkAddressWithTime: if we have a connection to a node. None: otherwise.
383,862
def infer(self, sensations, stats=None, objname=None): self.setLearning(False) prevLoc = [None] * self.numColumns numFeatures = len(sensations[0]) for sensation in xrange(numFeatures): for col in xrange(self.numColumns): assert numFeatures == len(sensations[col]) location, f...
Attempt to recognize the object given a list of sensations. You may use :meth:`getCurrentClassification` to extract the current object classification from the network :param sensations: Array of sensations, where each sensation is composed of displacement vector and feature SDR for e...
383,863
def get_channel_id(self): soup = BeautifulSoup( self.get_channel_page(), "lxml" ) channel_id = soup.find_all( "span", { "class": "channel-header-subscription-button-container" } ) channel_id = channel_id...
Fetches id :return: id of youtube channel
383,864
def _render_extended_error_message_list(self, extended_error): messages = [] if isinstance(extended_error, dict): if ( in extended_error and extended_error[].startswith()): for msg in extended_error[]: message_id = msg[] ...
Parse the ExtendedError object and retruns the message. Build a list of decoded messages from the extended_error using the message registries. An ExtendedError JSON object is a response from the with its own schema. This function knows how to parse the ExtendedError object and, using a...
383,865
def __print_step_by_console(self, step): step_list = step.split(u) for s in step_list: self.logger.by_console(u % repr(s).replace("u", ""))
print the step by console if the show variable is enabled :param step: step text
383,866
def hexdump(logger, s, width=16, skip=True, hexii=False, begin=0, highlight=None): r s = _flat(s) return .join(hexdump_iter(logger, StringIO(s), width, skip, hexii, begin, ...
r""" Return a hexdump-dump of a string. Arguments: logger(FastLogger): Logger object s(str): The data to hexdump. width(int): The number of characters per line skip(bool): Set to True, if repeated lines should be replaced by a "*" hexii(bool): Set to True, if a hexii-dum...
383,867
def set_dm(self, num): if self.data_model_num == 3: self.btn1a.Enable() else: self.btn1a.Disable() global pmag_gui_dialogs if self.data_model_num == 2: pmag_gui_dialogs = pgd2 wx.CallAfter(self.get_wd_dat...
Make GUI changes based on data model num. Get info from WD in appropriate format.
383,868
def resubmit(self, indices_or_msg_ids=None, subheader=None, block=None): block = self.block if block is None else block if indices_or_msg_ids is None: indices_or_msg_ids = -1 if not isinstance(indices_or_msg_ids, (list,tuple)): indices_or_msg_ids = [indices_or_m...
Resubmit one or more tasks. in-flight tasks may not be resubmitted. Parameters ---------- indices_or_msg_ids : integer history index, str msg_id, or list of either The indices or msg_ids of indices to be retrieved block : bool Whether to wait for the r...
383,869
def connect_async(self, connection_id, connection_string, callback): if callback is not None: callback(connection_id, self.id, False, "connect command is not supported in device adapter")
Asynchronously connect to a device Args: connection_id (int): A unique identifier that will refer to this connection connection_string (string): A DeviceAdapter specific string that can be used to connect to a device using this DeviceAdapter. callback (callab...
383,870
def strlen(self, name): with self.pipe as pipe: return pipe.strlen(self.redis_key(name))
Return the number of bytes stored in the value of the key :param name: str the name of the redis key :return: Future()
383,871
def _uneven_transform_deriv_shape(systematic_utilities, alt_IDs, rows_to_alts, shape_params, output_array=None, *args, **kwargs): natura...
Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is formed by the dot product of the design matrix with the vector o...
383,872
def mfpt(T, target, origin=None, tau=1, mu=None): r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind=) target = _types.ensure_int_vector(target) origin = _types.ensure_int_vector_or_None(origin) if _issparse(T): if origin is None: t_tau = sparse.mean_fi...
r"""Mean first passage times (from a set of starting states - optional) to a set of target states. Parameters ---------- T : ndarray or scipy.sparse matrix, shape=(n,n) Transition matrix. target : int or list of int Target states for mfpt calculation. origin : int or list of int...
383,873
def destroy_venv(env_path, venvscache=None): logger.debug("Destroying virtualenv at: %s", env_path) shutil.rmtree(env_path, ignore_errors=True) if venvscache is not None: venvscache.remove(env_path)
Destroy a venv.
383,874
def create(self, validated_data): if self.context.get() \ and self.context.get(): validated_data.update({ self.context.get(): self.context.get()}) instance = self.Meta.model(**validated_data) instance.full_clean() instance....
This is a standard method called indirectly by calling 'save' on the serializer. This method expects the 'parent_field' and 'parent_instance' to be included in the Serializer context.
383,875
def _encrypt(self): from M2Crypto import BIO, SMIME, X509 plaintext = % self.cert_id for name, field in self.fields.items(): value = None if name in self.initial: value = self.initial[name] elif field.initial is not None: ...
Use your key thing to encrypt things.
383,876
def from_boto_instance(cls, instance): return cls( name=instance.tags.get(), private_ip=instance.private_ip_address, public_ip=instance.ip_address, instance_type=instance.instance_type, instance_id=instance.id, hostname=instance.dn...
Loads a ``HostEntry`` from a boto instance. :param instance: A boto instance object. :type instance: :py:class:`boto.ec2.instanceInstance` :rtype: :py:class:`HostEntry`
383,877
def clear_decimal_value(self, label): if label not in self.my_osid_object_form._my_map[]: raise NotFound() del self.my_osid_object_form._my_map[][label]
stub
383,878
def setup(self, data_manager): self._data_manager = data_manager if self._data_manager: self._dal = self._data_manager.get_dal() else: self._dal = None for key, service in self._services.items(): service.setup(self._data_manager)
Hook to setup this service with a specific DataManager. Will recursively setup sub-services.
383,879
def _has_actions(self, event): event_actions = self._aconfig.get(event) return event_actions is None or bool(event_actions)
Check if a notification type has any enabled actions.
383,880
def find_any_reports(self, usage_page = 0, usage_id = 0): items = [ (HidP_Input, self.find_input_reports(usage_page, usage_id)), (HidP_Output, self.find_output_reports(usage_page, usage_id)), (HidP_Feature, self.find_feature_reports(usage_page, usage_id)),...
Find any report type referencing HID usage control/data item. Results are returned in a dictionary mapping report_type to usage lists.
383,881
def errReceived(self, data): if self.stderr: self.stderr.write(data) if self.kill_on_stderr: self.transport.loseConnection() raise RuntimeError( "Received stderr output from slave Tor process: " + data.decode() )
:api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API
383,882
def rgb_to_xy(self, red, green, blue): point = self.color.get_xy_point_from_rgb(red, green, blue) return (point.x, point.y)
Converts red, green and blue integer values to approximate CIE 1931 x and y coordinates.
383,883
def is_tensor_final(self, tensor_name): tensor = self._name_to_tensor(tensor_name) return tensor in self._final_tensors
Whether a tensor is a final output of the computation. Args: tensor_name: a string, name of a tensor in the graph. Returns: a boolean indicating whether the tensor was a final output.
383,884
def pct_decode(s): if s is None: return None elif not isinstance(s, unicode): s = str(s) else: s = s.encode() return PERCENT_CODE_SUB(lambda mo: chr(int(mo.group(0)[1:], 16)), s)
Return the percent-decoded version of string s. >>> pct_decode('%43%6F%75%63%6F%75%2C%20%6A%65%20%73%75%69%73%20%63%6F%6E%76%69%76%69%61%6C') 'Coucou, je suis convivial' >>> pct_decode('') '' >>> pct_decode('%2525') '%25'
383,885
def rulefor(self, addr): return self.rule.subgraph.node[self.rule.makeaddress(addr)][ ]
Return the rule object for an address from our deps graph.
383,886
def _init_datastores(): global _DATASTORES array = settings.DATASTORES for config in array: cls = _lookup(config[]) ds = _get_datastore(cls, DataStore, config) _DATASTORES.append(ds) legacy_settings = getattr(settings, , None) if legacy_settings is not None: warn...
Initialize all datastores.
383,887
def clip_by_global_norm_per_ctx(self, max_norm=1.0, param_names=None): assert self.binded and self.params_initialized and self.optimizer_initialized num_ctx = len(self._exec_group.grad_arrays[0]) grad_array_per_ctx = [[] for i in range(num_ctx)] assert(param_names is not None) ...
Clips gradient norm. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. The method is first used in `[ICML2013] On the difficulty of training recurrent neural networks` Note that the gradients...
383,888
def check_format(self, sm_format): if sm_format not in SyncMapFormat.ALLOWED_VALUES: self.print_error(u"Sync map format is not allowed" % (sm_format)) self.print_info(u"Allowed formats:") self.print_generic(u" ".join(SyncMapFormat.ALLOWED_VALUES)) return...
Return ``True`` if the given sync map format is allowed, and ``False`` otherwise. :param sm_format: the sync map format to be checked :type sm_format: Unicode string :rtype: bool
383,889
def format_price(price, currency=): if int(price) == price: return .format(currency, int(price)) return .format(currency, price)
Format the price to have the appropriate currency and digits.. :param price: The price amount. :param currency: The currency for the price. :return: A formatted price string, i.e. '$10', '$10.52'.
383,890
def canonical_chrom_sorted(in_chroms): if len(in_chroms) == 0: return [] chr_prefix = False mt = False if in_chroms[0].startswith(): in_chroms = [x.lstrip() for x in in_chroms] chr_prefix = True if in in_chroms: in_chroms[in_chroms.index()] = mt = True ...
Sort a list of chromosomes in the order 1..22, X, Y, M/MT :param list in_chroms: Input chromosomes :return: Sorted chromosomes :rtype: list[str]
383,891
def _context_menu_make(self, pos): menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
Reimplement the IPython context menu
383,892
def ID_colored_tube(color): tubing_data_path = os.path.join(os.path.dirname(__file__), "data", "3_stop_tubing.txt") df = pd.read_csv(tubing_data_path, delimiter=) idx = df["Color"] == color return df[idx][].values[0] * u.mm
Look up the inner diameter of Ismatec 3-stop tubing given its color code. :param color: Color of the 3-stop tubing :type color: string :returns: Inner diameter of the 3-stop tubing (mm) :rtype: float :Examples: >>> from aguaclara.research.peristaltic_pump import ID_colored_tube >>> from ...
383,893
async def set_topic_channel(self, channel): data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["topic_id"] = channel.id datatools.write_data(data) self.topicchannel = channel await self.set_topic(self.topic) await client.se...
Set the topic channel for this server
383,894
def import_locations(self, data): self._data = data if hasattr(data, ): data = data.read().split() elif isinstance(data, list): pass elif isinstance(data, basestring): data = open(data).read().split() else: raise TypeError(...
Parse `GNU miscfiles`_ cities data files. ``import_locations()`` returns a list containing :class:`City` objects. It expects data files in the same format that `GNU miscfiles`_ provides, that is:: ID : 1 Type : City Population : 210700 ...
383,895
def section(title, bar=OVERLINE, strm=sys.stdout): width = utils.term.width printy(bold(title.center(width))) printy(bold((bar * width)[:width]))
Helper function for testing demo routines
383,896
def GetFileObject(self, data_stream_name=): if data_stream_name: return None return resolver.Resolver.OpenFileObject( self.path_spec, resolver_context=self._resolver_context)
Retrieves the file-like object. Args: data_stream_name (Optional[str]): name of the data stream, where an empty string represents the default data stream. Returns: FileIO: a file-like object or None if not available.
383,897
def build_signature(self, user_api_key, user_secret, request): path = request.get_full_path() sent_signature = request.META.get( self.header_canonical()) signature_headers = self.get_headers_from_signature(sent_signature) unsigned = self.build_dict_to_sign(request, s...
Return the signature for the request.
383,898
def join(input_files, output_file): final_features = [] for file in input_files: with open(file) as f: feat_collection = geojson.load(f) final_features += feat_collection[] feat_collection[] = final_features with open(output_file, ) as f: geojson...
Join geojsons into one. The spatial reference system of the output file is the same as the one of the last file in the list. Args: input_files (list): List of file name strings. output_file (str): Output file name.
383,899
def process(self, salt_data, token, opts): log.debug(, threading.current_thread()) log.debug(salt_data[]) log.debug(salt_data) parts = salt_data[].split() if len(parts) < 2: return if parts[1] == : log.debug() if par...
Process events and publish data