Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
369,100
def from_dict(self, dingos_obj_dict, config_hooks=None, namespace_dict=None, ): if in dingos_obj_dict.keys(): top_level_namespace = (namespace_dict.get(dingos_obj_dict.get(),None),dingos_obj_dict.get()) ...
Convert DingoObjDict to facts and associate resulting facts with this information object.
369,101
def udf(x): x = ctypes.c_double(x) value = ctypes.c_double() libspice.udf_c(x, ctypes.byref(value)) return value.value
No-op routine for with an argument signature matching udfuns. Allways returns 0.0 . https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/udf_c.html :param x: Double precision value, unused. :type x: float :return: Double precision value, unused. :rtype: float
369,102
def _startServiceJobs(self): self.issueQueingServiceJobs() while True: serviceJob = self.serviceManager.getServiceJobsToStart(0) if serviceJob is None: break logger.debug(, serviceJob) self.issueServiceJob(serviceJob)
Start any service jobs available from the service manager
369,103
def _hash_data(hasher, data): _hasher = hasher.copy() _hasher.update(data) return _hasher.finalize()
Generate hash of data using provided hash type. :param hasher: Hasher instance to use as a base for calculating hash :type hasher: cryptography.hazmat.primitives.hashes.Hash :param bytes data: Data to sign :returns: Hash of data :rtype: bytes
369,104
def create_node(participant_id): exp = Experiment(session) try: participant = models.Participant.query.filter_by(id=participant_id).one() except NoResultFound: return error_response(error_type="/node POST no participant found", status=403) if participant.status != "worki...
Send a POST request to the node table. This makes a new node for the participant, it calls: 1. exp.get_network_for_participant 2. exp.create_node 3. exp.add_node_to_network 4. exp.node_post_request
369,105
def dcmdottoang_vel(R,Rdot): w = vee_map(Rdot.dot(R.T)) Omega = vee_map(R.T.dot(Rdot)) return (w, Omega)
Convert a rotation matrix to angular velocity w - angular velocity in inertial frame Omega - angular velocity in body frame
369,106
def _dict_to_stanza(key, stanza): ret = for skey in stanza: if stanza[skey] is True: stanza[skey] = ret += .format(skey, stanza[skey]) return .format(key, ret)
Convert a dict to a multi-line stanza
369,107
def temp_copy_extracted_submission(self): tmp_copy_dir = os.path.join(self.submission_dir, ) shell_call([, , os.path.join(self.extracted_submission_dir), tmp_copy_dir]) return tmp_copy_dir
Creates a temporary copy of extracted submission. When executed, submission is allowed to modify it's own directory. So to ensure that submission does not pass any data between runs, new copy of the submission is made before each run. After a run temporary copy of submission is deleted. Returns: ...
369,108
def create_searchspace(lookup, fastafn, proline_cut=False, reverse_seqs=True, do_trypsinize=True): allpeps = [] for record in SeqIO.parse(fastafn, ): if do_trypsinize: pepseqs = trypsinize(record.seq, proline_cut) else: pepseqs = [record.seq] ...
Given a FASTA database, proteins are trypsinized and resulting peptides stored in a database or dict for lookups
369,109
def parse_changes(): with open() as changes: for match in re.finditer(RE_CHANGES, changes.read(1024), re.M): if len(match.group(1)) != len(match.group(3)): error() date = datetime.datetime.strptime(match.group(4), )...
grab version from CHANGES and validate entry
369,110
def match_qualifier_id(self, qualifier_id, match): self._add_match(, str(qualifier_id), bool(match))
Matches the qualifier identified by the given ``Id``. arg: qualifier_id (osid.id.Id): the Id of the ``Qualifier`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``qualifier_id`` is ``null`` *compliance: man...
369,111
def formfield_for_dbfield(self, db_field, **kwargs): formfield = super().formfield_for_dbfield(db_field, **kwargs) if db_field.name == : formfield.widget = ImageRelatedFieldWidgetWrapper( ImageSelect(), db_field.rel, self.admin_site, can_add_related=True, ...
Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor.
369,112
def columns(self): from .column import Column if self.url is None or self.post_num == 0: return soup = BeautifulSoup(self._session.get(self.url + ).text) column_list = soup.find(, class_=) column_tags = column_list.find_all(, class_=) for column_tag ...
获取用户专栏. :return: 用户专栏,返回生成器 :rtype: Column.Iterable
369,113
def run(self): marker = [ for l in self._stream_delimiter] tf = self._obj[0](*self._obj[1], **self._obj[2]) while not self._stop: l = os.read(self._r, 1) marker.pop(0) marker.append(l) if marker != self._stream_delimiter: ...
Plan: * We read into a fresh instance of IO obj until marker encountered. * When marker is detected, we attach that IO obj to "results" array and signal the calling code (through threading.Event flag) that results are available * repeat until .stop() was called on the thread...
369,114
def get_option(self, key, default=None): if self.synchronizer: return self.extra_opts.get(key, self.synchronizer.options.get(key, default)) return self.extra_opts.get(key, default)
Return option from synchronizer (possibly overridden by target extra_opts).
369,115
def summary_df_from_list(results_list, names, **kwargs): for arr in results_list: assert arr.shape == (len(names),) df = pd.DataFrame(np.stack(results_list, axis=0)) df.columns = names return summary_df(df, **kwargs)
Make a panda data frame of the mean and std devs of each element of a list of 1d arrays, including the uncertainties on the values. This just converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_list: list of 1d numpy arrays Must have same length as n...
369,116
def view_admin_log(): build = g.build log_list = ( models.AdminLog.query .filter_by(build_id=build.id) .order_by(models.AdminLog.created.desc()) .all()) return render_template( , build=build, log_list=log_list)
Page for viewing the log of admin activity.
369,117
def ticket_flag(self, which, new=None): flag = _get_flag(which, TicketFlags) if flag: if not self.capabilities.have_ticket_flag(flag): raise yubikey_base.YubiKeyVersionError( % (which, flag.req_string(self.capabi...
Get or set a ticket flag. 'which' can be either a string ('APPEND_CR' etc.), or an integer. You should ALWAYS use a string, unless you really know what you are doing.
369,118
def fix_jumps(self, row_selected, delta): numrows = self.grid_mission.GetNumberRows() for row in range(numrows): command = self.grid_mission.GetCellValue(row, ME_COMMAND_COL) if command in ["DO_JUMP", "DO_CONDITION_JUMP"]: p1 = int(float(self.grid_mission...
fix up jumps when we add/remove rows
369,119
def run_pyvcf(args): reader = vcf.Reader(filename=args.input_vcf) writer = None start = time.clock() num = 0 for num, r in enumerate(reader): if num % 10000 == 0: print(num, "".join(map(str, [r.CHROM, ":", r.POS])), sep="\t", file=sys.stderr) if writer...
Main program entry point after parsing arguments
369,120
def _acronym_lic(self, license_statement): pat = re.compile(r) if pat.search(license_statement): lic = pat.search(license_statement).group(1) if lic.startswith(): acronym_licence = lic[:4] else: acronym_licence = lic.replace(, ...
Convert license acronym.
369,121
def define_points_grid(self): if self.latlon == False: try: self.dx if self.Quiet == False: print("dx and dy being overwritten -- supply a full grid") except: try: self.dy if self.Quiet == False: print("dx ...
This is experimental code that could be used in the spatialDomainNoGrid section to build a grid of points on which to generate the solution. However, the current development plan (as of 27 Jan 2015) is to have the end user supply the list of points where they want a solution (and/or for it to be provi...
369,122
def activate(self): obj = self.find_paypal_object() if obj.state == enums.BillingPlanState.CREATED: success = obj.activate() if not success: raise PaypalApiError("Failed to activate plan: %r" % (obj.error)) self.get_or_update_from_api_data(obj, always_sync=True) return obj
Activate an plan in a CREATED state.
369,123
def delete(self, pk, **kwargs): pk = unjson(pk) obj = get_obj(self.session, self.table, pk) if self._delete(obj, **kwargs): return {: pk, : obj.__repr__()}
Delete the object by primary_key: .. code-block:: python DBSession.sacrud(Users).delete(1) DBSession.sacrud(Users).delete('1') DBSession.sacrud(User2Groups).delete({'user_id': 4, 'group_id': 2}) JSON support: .. code-block:: python DBSession.s...
369,124
def num_workers(self): size = ctypes.c_int() check_call(_LIB.MXKVStoreGetGroupSize(self.handle, ctypes.byref(size))) return size.value
Returns the number of worker nodes. Returns ------- size :int The number of worker nodes.
369,125
def create_col_nums(): NUM_REPEATS = 2 column_letters = list( string.ascii_uppercase ) + map( .join, itertools.product( string.ascii_uppercase, repeat=NUM_REPEATS ) ) letter_numbers = [] count = 1 for letter in column_letters: ...
Return column numbers and letters that repeat up to NUM_REPEATS. I.e., NUM_REPEATS = 2 would return a list of 26 * 26 = 676 2-tuples.
369,126
def xy_data(xdata, ydata, eydata=None, exdata=None, label=None, xlabel=, ylabel=, \ title=, shell_history=0, xshift=0, yshift=0, xshift_every=1, yshift_every=1, \ coarsen=0, style=None, clear=True, axes=None, xscale=, yscale=, grid=False, \ legend=, legend...
Plots specified data. Parameters ---------- xdata, ydata Arrays (or arrays of arrays) of data to plot eydata=None, exdata=None Arrays of x and y errorbar values label=None String or array of strings for the line labels xlabel='' L...
369,127
def msg(self, msg=None, ret_r=False): s message' if msg or ret_r: self._msg = msg return self return self._msg
code's message
369,128
def verify_server_core(timeout=120, start_delay=90): timestamp = time.time() last_check = time.time() + start_delay - 10 last_delay_notification = time.time() - 10 server_down = True return_val = False timeout += 1 while((time.time()-timestamp) < timeout) and server_down: ...
checks to see if the server_core is running args: delay: will cycle till core is up. timeout: number of seconds to wait
369,129
def process_satellites(self, helper, sess): good_satellites = helper.get_snmp_value(sess, helper, self.oids[]) helper.add_summary("Good satellites: {}".format(good_satellites)) helper.add_metric(label=, value=good_satellites)
check and show the good satellites
369,130
def get_rank(self, member, reverse=False, pipe=None): pipe = self.redis if pipe is None else pipe method = getattr(pipe, if reverse else ) rank = method(self.key, self._pickle(member)) return rank
Return the rank of *member* in the collection. By default, the member with the lowest score has rank 0. If *reverse* is ``True``, the member with the highest score has rank 0.
369,131
def designPrimers(p3_args, input_log=None, output_log=None, err_log=None): sp = subprocess.Popen([pjoin(PRIMER3_HOME, )], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) p3_args.setdefault(, pjoin(PRIMER3_HO...
Return the raw primer3_core output for the provided primer3 args. Returns an ordered dict of the boulderIO-format primer3 output file
369,132
def _start_repl(api): banner = ( .format( testnet= if api.testnet else , uri=api.adapter.get_uri(), ) ) scope_vars = {: api} try: import IPython except I...
Starts the REPL.
369,133
def _spec_to_matches(server_list, server_spec, mode): assert mode in ("uri", "hostname", "hostname_port") def match(server_doc): if mode == "hostname": return server_spec == server_doc["hostname"] elif mode == "hostname_port": return server_spec == "{}:{}".format( ...
mode is in {uri, hostname, hostname_port} A list of matching server docs. Should usually be 0 or 1 matches. Multiple matches are possible though.
369,134
def AddInformationalOptions(self, argument_group): argument_group.add_argument( , , dest=, action=, default=False, help=) argument_group.add_argument( , , dest=, action=, default=False, help=)
Adds the informational options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
369,135
def _canceling_task(self, backend): with self.backend_mutex: self.backends[backend] -= 1 self.task_counter[backend] -= 1
Used internally to decrement `backend`s current and total task counts when `backend` could not be reached.
369,136
def _from_p(self, mode): self._check_modes(("P", "PA")) if not self.palette: raise RuntimeError("Cans alpha overrides data alpha mode = "RGBA" alpha = None elif self.mode.endswith("A"): alpha = self.data.sel(bands="A").data[....
Convert the image from P or PA to RGB or RGBA.
369,137
def get_tuning(instrument, description, nr_of_strings=None, nr_of_courses=None): searchi = str.upper(instrument) searchd = str.upper(description) keys = _known.keys() for x in keys: if (searchi not in keys and x.find(searchi) == 0 or searchi in keys and x == searchi): ...
Get the first tuning that satisfies the constraints. The instrument and description arguments are treated like case-insensitive prefixes. So search for 'bass' is the same is 'Bass Guitar'. Example: >>> tunings.get_tuning('guitar', 'standard') <tunings.StringTuning instance at 0x139ac20>
369,138
def can_proceed(bound_method, check_conditions=True): if not hasattr(bound_method, ): im_func = getattr(bound_method, , getattr(bound_method, )) raise TypeError( % im_func.__name__) meta = bound_method._django_fsm im_self = getattr(bound_method, , getattr(bound_method, )) current_s...
Returns True if model in state allows to call bound_method Set ``check_conditions`` argument to ``False`` to skip checking conditions.
369,139
def decrease_reads_in_units( current_provisioning, units, min_provisioned_reads, log_tag): updated_provisioning = int(current_provisioning) - int(units) min_provisioned_reads = __get_min_reads( current_provisioning, min_provisioned_reads, log_tag) if updated_provisionin...
Decrease the current_provisioning with units units :type current_provisioning: int :param current_provisioning: The current provisioning :type units: int :param units: How many units should we decrease with :returns: int -- New provisioning value :type min_provisioned_reads: int :param min_...
369,140
def setMetadata(self, remote, address, key, value): try: return self.proxies["%s-%s" % (self._interface_id, remote)].setMetadata(address, key, value) except Exception as err: LOG.debug("ServerThread.setMetadata: Exception: %s" % str(err))
Set metadata of device
369,141
def set_content_model(self): if not self.content_model: is_base_class = ( base_concrete_model(ContentTyped, self) == self.__class__) self.content_model = ( None if is_base_class else self.get_content_model_name())
Set content_model to the child class's related name, or None if this is the base class.
369,142
def _set_keychain(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name_of_keychain",keychain.keychain, yang_name="keychain", rest_name="keychain", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=,...
Setter method for keychain, mapped from YANG variable /keychain (list) If this variable is read-only (config: false) in the source YANG file, then _set_keychain is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_keychain() directly.
369,143
def class_check_para(**kw): try: def decorator(f): def new_f(*args): if "accepts" in kw: assert len(args) == len(kw["accepts"]) + 1 arg_types = tuple(map(type, args[1:])) if arg_types != kw["accepts"]: ...
force check accept and return, decorator, @class_check_para(accept=, returns=, mail=) :param kw: :return:
369,144
def from_buffer(self, buf): with self.lock: try: return maybe_decode(magic_buffer(self.cookie, buf)) except MagicException as e: return self._handle509Bug(e)
Identify the contents of `buf`
369,145
def set_app_os_tag(self, os_tag, app_tag, update_os, update_app): update_os = bool(update_os) update_app = bool(update_app) if update_os: self.os_info = _unpack_version(os_tag) if update_app: self.app_info = _unpack_version(app_tag) return [Er...
Update the app and/or os tags.
369,146
def convert_language_code(django_lang): lang_and_country = django_lang.split() try: return .join((lang_and_country[0], lang_and_country[1].upper())) except IndexError: return lang_and_country[0]
Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll" :param django_lang: Django language code as ll-cc :type django_lang: str :return: ISO language code as ll_CC :rtype: str
369,147
def handle_market_close(self, dt, data_portal): completed_session = self._current_session if self.emission_rate == : } ledger = self._ledger ledger.end_of_session(session_ix) self.end_of_session( packet, ...
Handles the close of the given day. Parameters ---------- dt : Timestamp The most recently completed simulation datetime. data_portal : DataPortal The current data portal. Returns ------- A daily perf packet.
369,148
def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]: k_means = KMeans(n_clusters=n_clusters) k_means.fit(points) closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points) return list(map(list, np.array(points)[closest.tolist()]))
Return n_clusters centroids of points
369,149
def ls(args): db = Database(args.db) db.create(exists_ok=True) in_db = {r[0]: r[1] for r in db.fetchall()} table = Table(, ) cols = OrderedDict([ (col, {}) for col in args.args if col in [ , , , , , , ...
lexibank ls [COLS]+ column specification: - license - lexemes - macroareas
369,150
def find_le(a, x): i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
Find rightmost value less than or equal to x.
369,151
def solveConsMarkov(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree,PermGroFac, MrkvArray,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool): s one period problem. IncomeDstn_list : [[np.array]] A length N list of income distributions in each succeeding Markov state. ...
Solves a single period consumption-saving problem with risky income and stochastic transitions between discrete states, in a Markov fashion. Has identical inputs as solveConsIndShock, except for a discrete Markov transitionrule MrkvArray. Markov states can differ in their interest factor, permanent gr...
369,152
def render(self, request, **kwargs): if request.GET.get(): self.render_type = kwargs[] = 1 kwargs[] = self.get_cancel_url() if not self.object: kwargs[] = True return super(FormView, self).render(request, **kwargs)
Renders this view. Adds cancel_url to the context. If the request get parameters contains 'popup' then the `render_type` is set to 'popup'.
369,153
def _get_value(obj, key): if isinstance(obj, (list, tuple)): for item in obj: v = _find_value(key, item) if v is not None: return v return None if isinstance(obj, dict): return obj.get(key) if obj is not None: return getattr(obj, k...
Get a value for 'key' from 'obj', if possible
369,154
def do_connect(self, arg): if self.arm.is_connected(): print(self.style.error(, )) else: try: port = self.arm.connect() print(self.style.success(, {}\.format(port))) except r12.ArmExcept...
Connect to the arm.
369,155
def progress_bar_wrapper(iterable, **kwargs): return tqdm(iterable, **kwargs) if (config.get_option() and not isinstance(iterable, tqdm)) else iterable
Wrapper that applies tqdm progress bar conditional on config settings.
369,156
def export(self, elec_file): elec_file = Path(elec_file) if elec_file.suffix == : sep = elif elec_file.suffix == : sep = with elec_file.open() as f: for one_chan in self.chan: values = ([one_chan.label, ] + ...
Export channel name and location to file. Parameters ---------- elec_file : Path or str path to file where to save csv
369,157
def setup_users_signals(self, ): log.debug("Setting up users page signals.") self.users_user_view_pb.clicked.connect(self.users_view_user) self.users_user_create_pb.clicked.connect(self.create_user)
Setup the signals for the users page :returns: None :rtype: None :raises: None
369,158
def set_terminal_converted(self, attr, repr_value): value = self.converter_registry.convert_from_representation( repr_value, attr.value_type) self.data[attr.repr_name] = value
Converts the given representation value and sets the specified attribute value to the converted value. :param attr: Attribute to set. :param str repr_value: String value of the attribute to set.
369,159
def parseline(line,format): xlat = {:None,:str,:float,:int,:int} result = [] words = line.split() for i in range(len(format)): f = format[i] trans = xlat.get(f,None) if trans: result.append(trans(words[i])) if len(result) == 0: return None if len(result) == 1: return...
\ Given a line (a string actually) and a short string telling how to format it, return a list of python objects that result. The format string maps words (as split by line.split()) into python code: x -> Nothing; skip this word s -> Return this word as a string i -> Return th...
369,160
def free_symbols(self): if self._free_symbols is None: if len(self._vals) == 0: self._free_symbols = self.operand.free_symbols else: dummy_map = {} for sym in self._vals.keys(): dummy_map[sym] = sympy.Dummy() ...
Set of free SymPy symbols contained within the expression.
369,161
def delete_communication_channel_id(self, id, user_id): path = {} data = {} params = {} path["user_id"] = user_id path["id"] = id self.logger.debug("DELETE /api/v1/users/{user_id}/communication_channels/{id} with...
Delete a communication channel. Delete an existing communication channel.
369,162
def string_to_sign(self, http_request): headers_to_sign = self.headers_to_sign(http_request) canonical_headers = self.canonical_headers(headers_to_sign) string_to_sign = .join([http_request.method, http_request.path, ...
Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign.
369,163
def config_string_to_dict(string, result=None): if string is None: return {} pairs = string.split(gc.CONFIG_STRING_SEPARATOR_SYMBOL) return pairs_to_dict(pairs, result)
Convert a given configuration string :: key_1=value_1|key_2=value_2|...|key_n=value_n into the corresponding dictionary :: dictionary[key_1] = value_1 dictionary[key_2] = value_2 ... dictionary[key_n] = value_n :param string string: the configuration string :rtype...
369,164
def captcha_transmit(self, captcha, uuid): self.log() response = { : , : , : b64encode(captcha[].getvalue()).decode() } self.fire(send(uuid, response))
Delayed transmission of a requested captcha
369,165
def hide(self, eid, index=0): elems = None if eid in self.__element_ids: elems = self.__element_ids[eid] elif eid in self.__repeat_ids: elems = self.__repeat_ids[eid] if elems and index < len(elems): elem = elems[index] elem.paren...
Hide the element with the matching eid. If no match, look for an element with a matching rid.
369,166
def list_recent_networks(self) -> List[Network]: most_recent_times = ( self.session .query( Network.name.label(), func.max(Network.created).label() ) .group_by(Network.name) .subquery() ) and_co...
List the most recently created version of each network (by name).
369,167
def create(**data): http_client = HttpClient() response, _ = http_client.post(routes.url(routes.CUSTOMER_RESOURCE), data) return resources.Customer(**response)
Create a customer. :param data: data required to create the customer :return: The customer resource :rtype resources.Customer
369,168
def get_filename(key, message, default=None, history=None): def _validate(string): if not os.path.isfile(string): return return prompt(key, message, default, True, _validate, history)
Like :meth:`prompt`, but only accepts the name of an existing file as an input. :type key: str :param key: The key under which to store the input in the :class:`InputHistory`. :type message: str :param message: The user prompt. :type default: str|None :param default: The offered default ...
369,169
def show_in_external_file_explorer(fnames=None): if not isinstance(fnames, (tuple, list)): fnames = [fnames] for fname in fnames: open_file_in_external_explorer(fname)
Show files in external file explorer Args: fnames (list): Names of files to show.
369,170
def log_once(log_func, msg, *args, **kwargs): if msg not in _LOG_ONCE_SEEN: log_func(msg, *args, **kwargs) _LOG_ONCE_SEEN.add(msg)
Logs a message only once.
369,171
def close(self): if not self._closed: self._closed = True self.client.close()
Closes the connection.
369,172
def search(query=None, catalog=None): if query is None: query = make_query(catalog) if query is None: return [] return api.search(query, catalog=catalog)
Search
369,173
def cross_list(*sequences): result = [[ ]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result
From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html
369,174
def play_game(game, *players): state = game.initial while True: for player in players: move = player(game, state) state = game.result(state, move) if game.terminal_test(state): return game.utility(state, game.to_move(game.initial))
Play an n-person, move-alternating game. >>> play_game(Fig52Game(), alphabeta_player, alphabeta_player) 3
369,175
def _get_pltdotstrs(self, hdrgos_usr, **kws): import datetime import timeit dotstrs_all = [] tic = timeit.default_timer() hdrgo2usrgos, go2obj = self._get_plt_data(hdrgos_usr) for hdrgo, usrgos in hdrgo2usrgos.items(): dotstrs_cur = ...
Plot GO DAGs for each group found under a specfied header GO.
369,176
def add_to_batch(self, batch): for name in self.paths: svg_path = self.paths[name] svg_path.add_to_batch(batch)
Adds paths to the given batch object. They are all added as GL_TRIANGLES, so the batch will aggregate them all into a single OpenGL primitive.
369,177
def get_connections(self, id, connection_name, **args): return self.request( "{0}/{1}/{2}".format(self.version, id, connection_name), args )
Fetches the connections for given object.
369,178
def stop_capture(self, port_number): if not [port["port_number"] for port in self._ports_mapping if port_number == port["port_number"]]: raise NodeError("Port {port_number} doesn{name}{name}' [{id}]: stopping packet capture on port {port_number}".format(name=self.name, ...
Stops a packet capture. :param port_number: allocated port number
369,179
def modsplit(s): if in s: c = s.split() if len(c) != 2: raise ValueError("Syntax error: {s}") return c[0], c[1] else: c = s.split() if len(c) < 2: raise ValueError("Syntax error: {s}") return .join(c[:-1]), c[-1]
Split importable
369,180
def p_obs(self, obs, out=None): if out is None: out = self._output_probabilities[:, obs].T return self._handle_outliers(out) else: if obs.shape[0] == out.shape[0]: np.copyto(out, self._output_probabilities[:, obs].T) e...
Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at ti...
369,181
def softmax(self, params): default_tau = 0.1 if params and type(params) == dict: tau = params.get() try: float(tau) except ValueError: tau = default_tau else: tau = default_tau ...
Run the softmax selection strategy. Parameters ---------- Params : dict Tau Returns ------- int Index of chosen bandit
369,182
def sample(self): self._sampling = True try: if self.is_raw_perf_class and not self._previous_sample: self._current_sample = self._query() self._previous_sample = self._current_sample self._current_sample = self._query() except Timeo...
Compute new samples.
369,183
def format_records(records): formatted = list() for record_ in records: formatted.append(format_record(record_)) return formatted
Serialise multiple records
369,184
def get_typ(self, refobj): enum = cmds.getAttr("%s.type" % refobj) try: return JB_ReftrackNode.types[enum] except IndexError: raise ValueError("The type on the node %s could not be associated with an available type: %s" % (refobj, JB_...
Return the entity type of the given reftrack node See: :data:`MayaRefobjInterface.types`. :param refobj: the reftrack node to query :type refobj: str :returns: the entity type :rtype: str :raises: ValueError
369,185
def asciigraph(self, values=None, max_height=None, max_width=None, label=False): result = border_fill_char = start_ctime = None end_ctime = None if not max_width: max_width = 180 if isinstance(values, dict): time_series_sorted...
Accepts a list of y values and returns an ascii graph Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example.
369,186
def generate_configurations(*, guided=False, fresh_start=False, save=False): if fresh_start: purge_configs() loaded_status, loaded_data = get_config() if loaded_status != CONFIG_VALID: if save: make_config_file(guided=guided) status, config_data = get_config() ...
If a config file is found in the standard locations, it will be loaded and the config data would be retuned. If not found, then generate the data on the fly, and return it
369,187
def remove_prefix(self, args): try: return self.nip.remove_prefix(args.get(), args.get(), args.get()) except (AuthError, NipapError) as exc: self.logger.debug(unicode(exc)) raise Fault(exc.error_code, unicode(exc))
Remove a prefix. Valid keys in the `args`-struct: * `auth` [struct] Authentication options passed to the :class:`AuthFactory`. * `prefix` [struct] Attributes used to select what prefix to remove. * `recursive` [boolean] Wh...
369,188
def extract_features(self, data_frame, pre=): try: magnitude_partial_autocorrelation = self.partial_autocorrelation(data_frame.mag_sum_acc) magnitude_agg_linear = self.agg_linear_trend(data_frame.mag_sum_acc) magnitude_spkt_welch_density = self.spkt_welch_density(dat...
This method extracts all the features available to the Tremor Processor class. :param data_frame: the data frame :type data_frame: pandas.DataFrame :return: amplitude_by_fft, frequency_by_fft, amplitude_by_welch, frequency_by_fft, bradykinesia_amplitude_by_fft, \ ...
369,189
def _dictToAlignments(self, blastDict, read): if (blastDict[] != read.id and blastDict[].split()[0] != read.id): raise ValueError( % (blastDict[], read.id)) alignments = [] getScore = itemget...
Take a dict (made by XMLRecordsReader._convertBlastRecordToDict) and convert it to a list of alignments. @param blastDict: A C{dict}, from convertBlastRecordToDict. @param read: A C{Read} instance, containing the read that BLAST used to create this record. @raise ValueError:...
369,190
def list_available_genomes(provider=None): if provider: providers = [ProviderBase.create(provider)] else: providers = [ProviderBase.create(p) for p in ProviderBase.list_providers()] for p in providers: for row in p.list_available_genomes(): ...
List all available genomes. Parameters ---------- provider : str, optional List genomes from specific provider. Genomes from all providers will be returned if not specified. Returns ------- list with genome names
369,191
def _proxy(self): if self._context is None: self._context = WorkspaceRealTimeStatisticsContext( self._version, workspace_sid=self._solution[], ) return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceRealTimeStatisticsContext for this WorkspaceRealTimeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workspace_r...
369,192
def _internal_kv_get(key): worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: return _local.get(key) return worker.redis_client.hget(key, "value")
Fetch the value of a binary key.
369,193
def from_rdata_list(ttl, rdatas): if len(rdatas) == 0: raise ValueError("rdata list must not be empty") r = None for rd in rdatas: if r is None: r = Rdataset(rd.rdclass, rd.rdtype) r.update_ttl(ttl) first_time = False r.add(rd) return r
Create an rdataset with the specified TTL, and with the specified list of rdata objects. @rtype: dns.rdataset.Rdataset object
369,194
def _get_LMv2_response(user_name, password, domain_name, server_challenge, client_challenge): nt_hash = comphash._ntowfv2(user_name, password, domain_name) lm_hash = hmac.new(nt_hash, (server_challenge + client_challenge)).digest() response = lm_hash + client_challenge return r...
[MS-NLMP] v28.0 2016-07-14 2.2.2.4 LMv2_RESPONSE The LMv2_RESPONSE structure defines the NTLM v2 authentication LmChallengeResponse in the AUTHENTICATE_MESSAGE. This response is used only when NTLM v2 authentication is configured. :param user_name: The user name of the user we ...
369,195
def width(self, value): if self._width != value and \ isinstance(value, (int, float, long)): self._width = value
gets/sets the width
369,196
def reset_tip_tracking(self): self.current_tip(None) self.tip_rack_iter = iter([]) if self.has_tip_rack(): iterables = self.tip_racks if self.channels > 1: iterables = [c for rack in self.tip_racks for c in rack.cols] else: ...
Resets the :any:`Pipette` tip tracking, "refilling" the tip racks
369,197
def extract_fragment(self, iri: str) -> str: fragment = str(iri).rsplit()[-1].split(, 1)[-1].split(, 1)[-1].split(, 1)[-1] return fragment
Pulls only for code/ID from the iri I only add the str() conversion for the iri because rdflib objects need to be converted.
369,198
def run(cls, command, cwd=".", **kwargs): assert isinstance(command, six.string_types) command_result = CommandResult() command_result.command = command use_shell = cls.USE_SHELL if "shell" in kwargs: use_shell = kwargs.pop("shell") if six.P...
Make a subprocess call, collect its output and returncode. Returns CommandResult instance as ValueObject.
369,199
def get_sms_connection(backend=None, fail_silently=False, **kwds): klass = import_string(backend or settings.SMS_BACKEND) return klass(fail_silently=fail_silently, **kwds)
Load an sms backend and return an instance of it. If backend is None (default) settings.SMS_BACKEND is used. Both fail_silently and other keyword arguments are used in the constructor of the backend. https://github.com/django/django/blob/master/django/core/mail/__init__.py#L28