Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
19,900
def set_shell(self, svc_ref): if svc_ref is None: return with self._lock: self._shell_ref = svc_ref self._shell = self._context.get_service(self._shell_ref) if readline is not None: readline.set_complete...
Binds the given shell service. :param svc_ref: A service reference
19,901
def extract_keys(self,key_list): if isinstance(key_list,basestring): key_list = key_list.split() return type(self)([ (k,self[k]) for k in key_list if k in self ])
>>> d = {'a':1,'b':2,'c':3} >>> print d.extract_keys('b,c,d') >>> {'b':2,'c':3} >>> print d.extract_keys(['b','c','d']) >>> {'b':2,'c':3}
19,902
def _validate_action_parameters(func, params): if params is not None: valid_fields = [getattr(fields, f) for f in dir(fields) \ if f.startswith("FIELD_")] for param in params: param_name, field_type = param[], param[] if param_name not in func.__...
Verifies that the parameters specified are actual parameters for the function `func`, and that the field types are FIELD_* types in fields.
19,903
def _migrate_subresource(subresource, parent, migrations): for key, doc in getattr(parent, subresource.parent_key, {}).items(): for migration in migrations[]: instance = migration(subresource(id=key, **doc)) parent._resource[] = unicode(migration.version) instance =...
Migrate a resource's subresource :param subresource: the perch.SubResource instance :param parent: the parent perch.Document instance :param migrations: the migrations for a resource
19,904
def _make_request_with_auth_fallback(self, url, headers=None, params=None): self.log.debug("Request URL and Params: %s, %s", url, params) try: resp = requests.get( url, headers=headers, verify=self._ssl_verify, params=p...
Generic request handler for OpenStack API requests Raises specialized Exceptions for commonly encountered error codes
19,905
def _pretend_to_run(self, migration, method): for query in self._get_queries(migration, method): name = migration.__class__.__name__ self._note( % (name, query))
Pretend to run the migration. :param migration: The migration :type migration: eloquent.migrations.migration.Migration :param method: The method to execute :type method: str
19,906
def send_command(self, command, as_list=False): action = actions.Action({: command, : }, as_list=as_list) return self.send_action(action)
Send a :class:`~panoramisk.actions.Command` to the server:: manager = Manager() resp = manager.send_command('http show status') Return a response :class:`~panoramisk.message.Message`. See https://wiki.asterisk.org/wiki/display/AST/ManagerAction_Command
19,907
def port_bindings(val, **kwargs): validate_ip_addrs = kwargs.get(, True) if not isinstance(val, dict): if not isinstance(val, list): try: val = helpers.split(val) except AttributeError: val = helpers.split(six.text_type(val)) for idx ...
On the CLI, these are passed as multiple instances of a given CLI option. In Salt, we accept these as a comma-delimited list but the API expects a Python dictionary mapping ports to their bindings. The format the API expects is complicated depending on whether or not the external port maps to a differen...
19,908
def run_command(self, cmd, new_prompt=True): if cmd == : self.exit_flag = True self.write() return special_pattern = r"^%s (?:r\)?\"?\run^([a-zA-Z0-9_\.]+)\?$?([a-zA-Z0-9_ \.]+)", cmd) if help_match: cmd ...
Run command in interpreter
19,909
def wrap_as_node(self, func): name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): message = self.get_message_from_call(*args, **kwargs) self.logger.info(, name, message) result = func(message) ...
wrap a function as a node
19,910
def iso8601_datetime(d): if d == values.unset: return d elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date): return d.strftime() elif isinstance(d, str): return d
Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
19,911
def __get_sigmas(self): stack_sigma = {} _stack = self.stack _file_path = os.path.abspath(os.path.dirname(__file__)) _database_folder = os.path.join(_file_path, , self.database) _list_compounds = _stack.keys() for _compound in _list_compounds: _list...
will populate the stack_sigma dictionary with the energy and sigma array for all the compound/element and isotopes
19,912
def pagination_calc(items_count, page_size, cur_page=1, nearby=2): if type(cur_page) == str: cur_page = int(cur_page) if cur_page.isdigit() else 1 elif type(cur_page) == int: if cur_page <= 0: cur_page = 1 else: cur_page = 1 page_count = 1 if page_size ...
:param nearby: :param items_count: count of all items :param page_size: size of one page :param cur_page: current page number, accept string digit :return: num of pages, an iterator
19,913
def _array(group_idx, a, size, fill_value, dtype=None): if fill_value is not None and not (np.isscalar(fill_value) or len(fill_value) == 0): raise ValueError("fill_value must be None, a scalar or an empty " "sequence") order_group_idx ...
groups a into separate arrays, keeping the order intact.
19,914
def process(self): self.modules.sort(key=lambda x: x.priority) for module in self.modules: transforms = module.transform(self.data) transforms.sort(key=lambda x: x.linenum, reverse=True) for transform in transforms: linenum = transform.linen...
This method handles the actual processing of Modules and Transforms
19,915
def shared(self, value, name=None): if type(value) == int: final_value = np.array(value, dtype="int32") elif type(value) == float: final_value = np.array(value, dtype=env.FLOATX) else: final_value = value return theano.shared(final_value, nam...
Create a shared theano scalar value.
19,916
def get_most_distinct_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None): return _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n)
Order the words from `vocab` by "distinctiveness score" (Chuang et al. 2012) from most to least distinctive. Optionally only return the `n` most distinctive words. J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models"
19,917
def add_portal(self, origin, destination, symmetrical=False, **kwargs): if isinstance(origin, Node): origin = origin.name if isinstance(destination, Node): destination = destination.name super().add_edge(origin, destination, **kwargs) if symmetrical: ...
Connect the origin to the destination with a :class:`Portal`. Keyword arguments are the :class:`Portal`'s attributes. Exception: if keyword ``symmetrical`` == ``True``, a mirror-:class:`Portal` will be placed in the opposite direction between the same nodes. It will always appear to ...
19,918
def mark_dead(self, proxy, _time=None): if proxy not in self.proxies: logger.warn("Proxy <%s> was not found in proxies list" % proxy) return if proxy in self.good: logger.debug("GOOD proxy became DEAD: <%s>" % proxy) else: logger.debug("P...
Mark a proxy as dead
19,919
def get_group_hidden(self): for element in self.group_list: if element.form.view_type != : return False return False return True
Determine if the entire group of elements is hidden (decide whether to hide the entire group).
19,920
def execute(self, resource, **kw): params = kw.pop(, {}) json = kw.pop(, None) task = self.make_request( TaskRunFailed, method=, params=params, json=json, resource=resource) timeout = kw.pop(, 5) wait_for_finis...
Execute the task and return a TaskOperationPoller. :rtype: TaskOperationPoller
19,921
def api_reference(root_url, service, version): root_url = root_url.rstrip() if root_url == OLD_ROOT_URL: return .format(service, version) else: return .format(root_url, service, version)
Generate URL for a Taskcluster api reference.
19,922
def get_oauth_access_token(url_base, client_id, client_secret, company_id, user_id, user_type): SAPSuccessFactorsGlobalConfiguration = apps.get_model( , ) global_sap_config = SAPSuccessFactorsGlobalConfiguration.current() url = url_base + global_sap_co...
Retrieves OAuth 2.0 access token using the client credentials grant. Args: url_base (str): Oauth2 access token endpoint client_id (str): client ID client_secret (str): client secret company_id (str): SAP company ID user_id (str): SAP user ID ...
19,923
def print_clusters(fastas, info, ANI): header = [, , , , , , \ , , ] yield header in_cluster = [] for cluster_num, cluster in enumerate(connected_components(ANI)): cluster = sorted([genome_info(genome, info[genome]) \ for genome in cluster], \ ...
choose represenative genome and print cluster information *if ggKbase table is provided, use SCG info to choose best genome
19,924
def _populate_unknown_statuses(set_tasks): visited = set() for task in set_tasks["still_pending_not_ext"]: _depth_first_search(set_tasks, task, visited)
Add the "upstream_*" and "not_run" statuses my mutating set_tasks.
19,925
def get_request_params(self) -> List[ExtensionParameter]: return _build_parameters( self.server_no_context_takeover, self.client_no_context_takeover, self.server_max_window_bits, self.client_max_window_bits, )
Build request parameters.
19,926
def load(self, key, noexpire=None): with self.load_fd(key, noexpire=noexpire) as fd: return fd.read()
Lookup an item in the cache and return the raw content of the file as a string.
19,927
def get_indexed_slices(self, column_parent, index_clause, column_predicate, consistency_level): self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_get_indexed_slices(column_parent, index_clause, column_predicate, consistency_level) return d
Returns the subset of columns specified in SlicePredicate for the rows matching the IndexClause @deprecated use get_range_slices instead with range.row_filter specified Parameters: - column_parent - index_clause - column_predicate - consistency_level
19,928
def inactive_response(self, request): inactive_url = getattr(settings, , ) if inactive_url: return HttpResponseRedirect(inactive_url) else: return self.error_to_response(request, {: _("This user account is marked as inactive.")})
Return an inactive message.
19,929
def _construct_state_machines(self): state_machines = dict() for state_machine in [StateMachineRecomputing(self.logger, self), StateMachineContinuous(self.logger, self), StateMachineDiscrete(self.logger, self), ...
:return: dict in format <state_machine_common_name: instance_of_the_state_machine>
19,930
def apply(self, df): if hasattr(self.definition, ): r = self.definition(df) elif self.definition in df.columns: r = df[self.definition] elif not isinstance(self.definition, string_types): r = pd.Series(self.definition, index=df.index) else: ...
Takes a pd.DataFrame and returns the newly defined column, i.e. a pd.Series that has the same index as `df`.
19,931
def unique(iterable, key=identity): seen = set() for item in iterable: item_key = key(item) if item_key not in seen: seen.add(item_key) yield item
Yields all the unique values in an iterable maintaining order
19,932
def calendar(self, val): self._calendar = val if val is not None and not val.empty: self._calendar_i = self._calendar.set_index("service_id") else: self._calendar_i = None
Update ``self._calendar_i``if ``self.calendar`` changes.
19,933
def load_from_db(self, cache=False): a = {} db_prefs = {p.preference.identifier(): p for p in self.queryset} for preference in self.registry.preferences(): try: db_pref = db_prefs[preference.identifier()] except KeyError: db_pref =...
Return a dictionary of preferences by section directly from DB
19,934
def get_all_targets(self): result = [] for batch in self.batches: result.extend(batch.targets) return result
Returns all targets for all batches of this Executor.
19,935
def put(self, url: StrOrURL, *, data: Any=None, **kwargs: Any) -> : return _RequestContextManager( self._request(hdrs.METH_PUT, url, data=data, **kwargs))
Perform HTTP PUT request.
19,936
def tag_array(events): all_tags = sorted(set(tag for event in events for tag in event.tags)) array = np.zeros((len(events), len(all_tags))) for row, event in enumerate(events): for tag in event.tags: array[row, all_tags.index(tag)] = 1 return array
Return a numpy array mapping events to tags - Rows corresponds to events - Columns correspond to tags
19,937
def _neg_bounded_fun(fun, bounds, x, args=()): if _check_bounds(x, bounds): return -fun(x, *args) else: return np.inf
Wrapper for bounding and taking the negative of `fun` for the Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba. Parameters ---------- fun : callable The objective function to be minimized. `fun(x, *args) -> float` where x is an 1-D array with shape (n,) and...
19,938
def load_metadata_csv(input_filepath): with open(input_filepath) as f: csv_in = csv.reader(f) header = next(csv_in) if in header: tags_idx = header.index() else: raise ValueError() if header[0] == : if header[1] == : m...
Return dict of metadata. Format is either dict (filenames are keys) or dict-of-dicts (project member IDs as top level keys, then filenames as keys). :param input_filepath: This field is the filepath of the csv file.
19,939
def _validate(self, validator, data, key, position=None, includes=None): errors = [] if position: position = % (position, key) else: position = key try: data_item = util.get_value(data, key) except KeyError: return e...
Run through a schema and a data structure, validating along the way. Ignores fields that are in the data structure, but not in the schema. Returns an array of errors.
19,940
def __start_waiting_for_events(self): d rather stay on the safe side, as my experience of threading in Python is limited. Starting ioloop...ioloop is owned by connection %s...re now open for events. self.thread.tell_publisher_to_stop_waiting_for_...
This waits until the whole chain of callback methods triggered by "trigger_connection_to_rabbit_etc()" has finished, and then starts waiting for publications. This is done by starting the ioloop. Note: In the pika usage example, these things are both called inside the run() met...
19,941
async def shutdown(self, container, force=False): p = self._connpool self._connpool = [] self._shutdown = True if self._defaultconn: p.append(self._defaultconn) self._defaultconn = None if self._subscribeconn: p.append(self._subscribec...
Shutdown all connections. Exclusive connections created by get_connection will shutdown after release()
19,942
def toIndex(self, value): if self._isIrNull(value): ret = IR_NULL_STR else: ret = self._toIndex(value) if self.isIndexHashed is False: return ret return md5(tobytes(ret)).hexdigest()
toIndex - An optional method which will return the value prepped for index. By default, "toStorage" will be called. If you provide "hashIndex=True" on the constructor, the field will be md5summed for indexing purposes. This is useful for large strings, etc.
19,943
def status_for_all_orders_in_a_stock(self, stock): url_fragment = .format( stock=stock, venue=self.venue, account=self.account, ) url = urljoin(self.base_url, url_fragment) return self.session.get(url).json()
Status for all orders in a stock https://starfighter.readme.io/docs/status-for-all-orders-in-a-stock
19,944
def predict(self, choosers, alternatives, debug=False): self.assert_fitted() logger.debug(.format(self.name)) choosers, alternatives = self.apply_predict_filters( choosers, alternatives) if len(choosers) == 0: return pd.Series() if len(alternat...
Choose from among alternatives for a group of agents. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. alternatives : pandas.DataFrame Table describing the things from which agents are choosing. ...
19,945
def _get_or_create_uaa(self, uaa): if isinstance(uaa, predix.admin.uaa.UserAccountAuthentication): return uaa logging.debug("Initializing a new UAA") return predix.admin.uaa.UserAccountAuthentication()
Returns a valid UAA instance for performing administrative functions on services.
19,946
def ccor(alt, r, h1, zh): e = (alt - zh) / h1 if(e>70.0): return 1.0 elif (e < -70.0): return exp(r) ex = exp(e) e = r / (1.0 + ex) return exp(e)
/* CHEMISTRY/DISSOCIATION CORRECTION FOR MSIS MODELS * ALT - altitude * R - target ratio * H1 - transition scale length * ZH - altitude of 1/2 R */
19,947
def get_default_config_file(rootdir=None): if rootdir is None: return DEFAULT_CONFIG_FILE for path in CONFIG_FILES: path = os.path.join(rootdir, path) if os.path.isfile(path) and os.access(path, os.R_OK): return path
Search for configuration file.
19,948
def _learn( permanences, rng, activeCells, activeInput, growthCandidateInput, sampleSize, initialPermanence, permanenceIncrement, permanenceDecrement, connectedPermanence): permanences.incrementNonZerosOnOuter( activeCells...
For each active cell, reinforce active synapses, punish inactive synapses, and grow new synapses to a subset of the active input bits that the cell isn't already connected to. Parameters: ---------------------------- @param permanences (SparseMatrix) Matrix of permanences, with cells a...
19,949
def dereference(self, data, host=None): return self.deep_decode(self.deep_encode(data, host), deref=True)
Dereferences RefObjects stuck in the hierarchy. This is a bit of an ugly hack.
19,950
def _apply_replace_backrefs(m, repl=None, flags=0): if m is None: raise ValueError("Match is None!") else: if isinstance(repl, ReplaceTemplate): return repl.expand(m) elif isinstance(repl, (str, bytes)): return _bregex_parse._ReplaceParser().parse(m.re, repl...
Expand with either the `ReplaceTemplate` or compile on the fly, or return None.
19,951
def get_lm_challenge_response(self): if self._negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY and self._ntlm_compatibility < 3: response = ComputeResponse._get_LMv1_with_session_security_response(self._client_challenge) elif 0 <= self._ntlm_compatibility...
[MS-NLMP] v28.0 2016-07-14 3.3.1 - NTLM v1 Authentication 3.3.2 - NTLM v2 Authentication This method returns the LmChallengeResponse key based on the ntlm_compatibility chosen and the target_info supplied by the CHALLENGE_MESSAGE. It is quite different from what is set in the d...
19,952
def load_and_assign_npz_dict(name=, sess=None): if sess is None: raise ValueError("session is None.") if not os.path.exists(name): logging.error("file {} doesn't exist.".format(name)) return False params = np.load(name) if len(params.keys()) != len(set(params.keys())): ...
Restore the parameters saved by ``tl.files.save_npz_dict()``. Parameters ---------- name : str The name of the `.npz` file. sess : Session TensorFlow Session.
19,953
def rename(name, new_name, root=None): * if info(new_name, root=root): raise CommandExecutionError({0}\.format(new_name)) return _chattrib(name, , new_name, , root=root)
Change the username for a named user name User to modify new_name New value of the login name root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.rename name new_name
19,954
def map(self, func): return dict((key, func(value)) for key, value in self.iteritems())
Return a dictionary of the results of func applied to each of the segmentlist objects in self. Example: >>> x = segmentlistdict() >>> x["H1"] = segmentlist([segment(0, 10)]) >>> x["H2"] = segmentlist([segment(5, 15)]) >>> x.map(lambda l: 12 in l) {'H2': True, 'H1': False}
19,955
def list_tables(self, limit=None, start_table=None): result = self.layer1.list_tables(limit, start_table) return result[]
Return a list of the names of all Tables associated with the current account and region. TODO - Layer2 should probably automatically handle pagination. :type limit: int :param limit: The maximum number of tables to return. :type start_table: str :param limit: The name o...
19,956
def create(self, serviceBinding): if not isinstance(serviceBinding, ServiceBindingCreateRequest): if serviceBinding["type"] == "cloudant": serviceBinding = CloudantServiceBindingCreateRequest(**serviceBinding) elif serviceBinding["type"] == "eventstreams": ...
Create a new external service. The service must include all of the details required to connect and authenticate to the external service in the credentials property. Parameters: - serviceName (string) - Name of the service - serviceType (string) - must be either eventst...
19,957
def getDynDnsClientForConfig(config, plugins=None): initparams = {} if "interval" in config: initparams["detect_interval"] = config["interval"] if plugins is not None: initparams["plugins"] = plugins if "updater" in config: for updater_name, updater_options in config["upda...
Instantiate and return a complete and working dyndns client. :param config: a dictionary with configuration keys :param plugins: an object that implements PluginManager
19,958
def loaded_ret(ret, loaded, test, debug, compliance_report=False, opts=None): changes = {} ret[] = loaded[] if in loaded: changes[] = loaded[] if in loaded: changes[] = loaded[] if in loaded: if compliance_report: changes[] = loaded[] if debug and...
Return the final state output. ret The initial state output structure. loaded The loaded dictionary.
19,959
def get_root_families(self): if self._catalog_session is not None: return self._catalog_session.get_root_catalogs() return FamilyLookupSession( self._proxy, self._runtime).get_families_by_ids(list(self.get_root_family_ids()))
Gets the root families in the family hierarchy. A node with no parents is an orphan. While all family ``Ids`` are known to the hierarchy, an orphan does not appear in the hierarchy unless explicitly added as a root node or child of another node. return: (osid.relationship.Famil...
19,960
def get_flux(self, reaction): return self._prob.result.get_value(self._v(reaction))
Get resulting flux value for reaction.
19,961
def create_powerflow_problem(timerange, components): network, snapshots = init_pypsa_network(timerange) for component in components.keys(): network.import_components_from_dataframe(components[component], component) return network, sn...
Create PyPSA network object and fill with data Parameters ---------- timerange: Pandas DatetimeIndex Time range to be analyzed by PF components: dict Returns ------- network: PyPSA powerflow problem object
19,962
def process_amqp_msgs(self): LOG.info() while True: (mtd_fr, hdr_fr, body) = (None, None, None) try: if self.consume_channel: (mtd_fr, hdr_fr, body) = self.consume_channel.basic_get( self._dcnm_queue_name) ...
Process AMQP queue messages. It connects to AMQP server and calls callbacks to process DCNM events, i.e. routing key containing '.cisco.dcnm.', once they arrive in the queue.
19,963
def make_rendition(self, width, height): s aspect ratio width x height -> will make an image potentialy cropped %dx%d%s/%s_%s%s' % ( IMAGE_DIRECTORY, filename, rendition_key, ext ) fd = BytesIO() ...
build a rendition 0 x 0 -> will give master URL only width -> will make a renditions with master's aspect ratio width x height -> will make an image potentialy cropped
19,964
def add_precip_file(self, precip_file_path, interpolation_type=None): self._update_card(, precip_file_path, True) if interpolation_type is None: if not self.project_manager.getCard() \ and not self.project_manager.getCard(): ...
Adds a precip file to project with interpolation_type
19,965
def info(): try: platform_info = {"system": platform.system(), "release": platform.release()} except IOError: platform_info = {"system": "Unknown", "release": "Unknown"} implementation = platform.python_implementation() if implementation == "CPython": implementation_versio...
Generate information for a bug report. Based on the requests package help utility module.
19,966
def _check_uuid_fmt(self): if self.uuid_fmt not in UUIDField.FORMATS: raise FieldValueRangeException( "Unsupported uuid_fmt ({})".format(self.uuid_fmt))
Checks .uuid_fmt, and raises an exception if it is not valid.
19,967
def release(ctx, version): invoke.run("git tag -s {0} -m ".format(version)) invoke.run("git push --tags") invoke.run("python setup.py sdist") invoke.run("twine upload -s dist/PyNaCl-{0}* ".format(version)) session = requests.Session() token = getpass.getpass("Input the Jenkins token: ")...
``version`` should be a string like '0.4' or '1.0'.
19,968
def fromCSV(csvfile,out=None,fieldnames=None,fmtparams=None,conv_func={}, empty_to_None=[]): import csv import time import datetime if out is None: out = os.path.splitext(csvfile)[0]+".pdl" if fieldnames is None: reader = csv.reader(open(csv...
Conversion from CSV to PyDbLite csvfile : name of the CSV file in the file system out : path for the new PyDbLite base in the file system fieldnames : list of field names. If set to None, the field names must be present in the first line of the CSV file fmtparams : the format paramete...
19,969
def index(): accessible_institutes = current_user.institutes if not in current_user.roles: accessible_institutes = current_user.institutes if not accessible_institutes: flash() return redirect(url_for()) LOG.debug(.format(accessible_institutes)) institutes ...
Display the Scout dashboard.
19,970
def refresh(self, only_closed=False): if only_closed: opened = filter(self.__check_port, self.__closed) self.__closed = self.__closed.difference(opened) self.__ports = self.__ports.union(opened) else: ports = self.__closed.union(self.__ports) ...
refresh ports status Args: only_closed - check status only for closed ports
19,971
def _summarize_combined(samples, vkey): validate_dir = utils.safe_makedir(os.path.join(samples[0]["dirs"]["work"], vkey)) combined, _ = _group_validate_samples(samples, vkey, [["metadata", "validate_combine"]]) for vname, vitems in combined.items(): if vname: cur_combined = collecti...
Prepare summarized CSV and plot files for samples to combine together. Helps handle cases where we want to summarize over multiple samples.
19,972
def cleanup(self): current = self.join() if not os.path.exists(current): LOGGER.debug(, current) os.unlink(self.join()) self.current = None try: self._update_current() except PrefixNotFound: if not os.l...
Attempt to set a new current symlink if it is broken. If no other prefixes exist and the workdir is empty, try to delete the entire workdir. Raises: :exc:`~MalformedWorkdir`: if no prefixes were found, but the workdir is not empty.
19,973
def upgrade(*pkgs): libxslt-1.1.0libxslt-1.1.10** cmd = _quietnix() cmd.append() cmd.extend(pkgs) out = _run(cmd) upgrades = [_format_upgrade(s.split(maxsplit=1)[1]) for s in out[].splitlines() if s.startswith()] return [[_strip_quotes(s_) for s_ in s] ...
Runs an update operation on the specified packages, or all packages if none is specified. :type pkgs: list(str) :param pkgs: List of packages to update :return: The upgraded packages. Example element: ``['libxslt-1.1.0', 'libxslt-1.1.10']`` :rtype: list(tuple(str, str)) .. code-block:: ba...
19,974
def interface_lookup(interfaces, hwaddr, address_type): for interface in interfaces.values(): if interface.get() == hwaddr: for address in interface.get(): if address.get() == address_type: return address.get()
Search the address within the interface list.
19,975
def _check_perpendicular_r2_axis(self, axis): min_set = self._get_smallest_set_not_on_axis(axis) for s1, s2 in itertools.combinations(min_set, 2): test_axis = np.cross(s1.coords - s2.coords, axis) if np.linalg.norm(test_axis) > self.tol: op = SymmOp.from_...
Checks for R2 axes perpendicular to unique axis. For handling symmetric top molecules.
19,976
def call_runtime(self): cache = self.gather_cache() chunks = self.get_chunks() interval = self.opts[] recompile = self.opts.get(, 300) r_start = time.time() while True: events = self.get_events() if not events: time.sleep(i...
Execute the runtime
19,977
def dataframe(self, spark, group_by=, limit=None, sample=1, seed=42, decode=None, summaries=None, schema=None, table_name=None): rdd = self.records(spark.sparkContext, group_by, limit, sample, seed, decode, summaries) if not schema: df = rdd.map(lambda d: Row(**d)).toDF() el...
Convert RDD returned from records function to a dataframe :param spark: a SparkSession object :param group_by: specifies a paritition strategy for the objects :param limit: maximum number of objects to retrieve :param decode: an optional transformation to apply to the objects retrieved ...
19,978
def _validate_type(cls, typeobj): if not (hasattr(typeobj, "convert") or hasattr(typeobj, "convert_binary")): raise ArgumentError("type is invalid, does not have convert or convert_binary function", type=typeobj, methods=dir(typeobj)) if not hasattr(typeobj, "default_formatter"): ...
Validate that all required type methods are implemented. At minimum a type must have: - a convert() or convert_binary() function - a default_formatter() function Raises an ArgumentError if the type is not valid
19,979
def _create_event(instance, action): user = None user_repr = repr(user) if CUSER: user = CuserMiddleware.get_user() user_repr = repr(user) if user is not None and user.is_anonymous: user = None return TrackingEvent.objects.create( action=action, o...
Create a new event, getting the use if django-cuser is available.
19,980
def decode_body(cls, header, f): assert header.packet_type == MqttControlPacketType.pingresp if header.remaining_len != 0: raise DecodeError() return 0, MqttPingresp()
Generates a `MqttPingresp` packet given a `MqttFixedHeader`. This method asserts that header.packet_type is `pingresp`. Parameters ---------- header: MqttFixedHeader f: file Object with a read method. Raises ------ DecodeError ...
19,981
def validate_token(self, request, consumer, token): oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request) oauth_server.verify_request(oauth_request, consumer, token)
Check the token and raise an `oauth.Error` exception if invalid.
19,982
def temp_url(self, duration=120): return self.bucket._boto_s3.meta.client.generate_presigned_url( , Params={: self.bucket.name, : self.name}, ExpiresIn=duration )
Returns a temporary URL for the given key.
19,983
def _init(self): read_values = [] read = self._file.read last = read(1) current = read(1) while last != b and current != b and not \ (last == b and current == b): read_values.append(last) last = current current = read(1...
Read the b"\\r\\n" at the end of the message.
19,984
def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""): try: fileFile = open(fileIndex, ) except IOError: self.repo.printd("Error: Unable to read index file " + self.fileIndex) return None, None count = 1 for line in fileFile: ...
Search the files index using the namedata and returns the filedata
19,985
def getAsKmlGridAnimation(self, session, projectFile=None, path=None, documentName=None, colorRamp=None, alpha=1.0, noDataValue=0.0): timeStampedRasters = self._assembleRasterParams(projectFile, self.rasters) converter = RasterConverter(sqlAlchemyEngineOrSession=session) ...
Retrieve the WMS dataset as a gridded time stamped KML string. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. projectFile(:class:`gsshapy.orm.ProjectFile`): Project file object for the GSSHA project to which the WMS da...
19,986
def disable_snapshots(self, volume_id, schedule_type): return self.client.call(, , schedule_type, id=volume_id)
Disables snapshots for a specific block volume at a given schedule :param integer volume_id: The id of the volume :param string schedule_type: 'HOURLY'|'DAILY'|'WEEKLY' :return: Returns whether successfully disabled or not
19,987
def normalize_weekly(data): if "tblMenu" not in data["result_data"]["Document"]: data["result_data"]["Document"]["tblMenu"] = [] if isinstance(data["result_data"]["Document"]["tblMenu"], dict): data["result_data"]["Document"]["tblMenu"] = [data["result_data"]["Document"]["tblMenu"]] for...
Normalization for dining menu data
19,988
def normalize_name(name): if not name or not isinstance(name, basestring): raise ValueError(+ repr(name)) if len(name) > 1: name = name.lower() if name != and in name: name = name.replace(, ) return canonical_names.get(name, name)
Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to the canonical representation (e.g. "left ctrl") if one is known.
19,989
def nCr(n, r): f = math.factorial return int(f(n) / f(r) / f(n-r))
Calculates nCr. Args: n (int): total number of items. r (int): items to choose Returns: nCr.
19,990
def repl_update(self, config): cfg = config.copy() cfg[] += 1 try: result = self.run_command("replSetReconfig", cfg) if int(result.get(, 0)) != 1: return False except pymongo.errors.AutoReconnect: self.update_server_map(cfg) ...
Reconfig Replicaset with new config
19,991
def _mean_prediction(self, mu, Y, h, t_z): Y_exp = Y.copy() for t in range(0,h): if self.ar != 0: Y_exp_normalized = (Y_exp[-self.ar:][::-1] - self._norm_mean) / self._norm_std new_value = self.predict_new(np.append(1.0, Y_ex...
Creates a h-step ahead mean prediction Parameters ---------- mu : np.ndarray The past predicted values Y : np.ndarray The past data h : int How many steps ahead for the prediction t_z : np.ndarray A vector of (transforme...
19,992
def get_authn_contexts(self): authn_context_nodes = self.__query_assertion() return [OneLogin_Saml2_Utils.element_text(node) for node in authn_context_nodes]
Gets the authentication contexts :returns: The authentication classes for the SAML Response :rtype: list
19,993
def _set_bgp_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 6}, u: {: 4}, u: {: 0...
Setter method for bgp_state, mapped from YANG variable /bgp_state/neighbor/evpn/bgp_state (bgp-states) If this variable is read-only (config: false) in the source YANG file, then _set_bgp_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
19,994
def validateDocument(self, ctxt): if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o ret = libxml2mod.xmlValidateDocument(ctxt__o, self._o) return ret
Try to validate the document instance basically it does the all the checks described by the XML Rec i.e. validates the internal and external subset (if present) and validate the document tree.
19,995
def put_file(client, source_file, destination_file): try: sftp_client = client.open_sftp() sftp_client.put(source_file, destination_file) except Exception as error: raise IpaUtilsException( .format(error) ) finally: with ignored(Exception): ...
Copy file to instance using Paramiko client connection.
19,996
def generate_string_to_sign(date, region, canonical_request): formatted_date_time = date.strftime("%Y%m%dT%H%M%SZ") canonical_request_hasher = hashlib.sha256() canonical_request_hasher.update(canonical_request.encode()) canonical_request_sha256 = canonical_request_hasher.hexdigest() scope = ge...
Generate string to sign. :param date: Date is input from :meth:`datetime.datetime` :param region: Region should be set to bucket region. :param canonical_request: Canonical request generated previously.
19,997
def _get_ids_from_hostname(self, hostname): results = self.list_instances(hostname=hostname, mask="id") return [result[] for result in results]
List VS ids which match the given hostname.
19,998
def _init_map(self): QuestionTextFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) super(QuestionTextAndFilesMixin, self)._init_map()
stub
19,999
def _check_import_source(): path_rel = path = os.path.expanduser(path_rel) if not os.path.isfile(path): try: corpus_importer = CorpusImporter() corpus_importer.import_corpus() except Exception as exc: logger.error(...
Check if tlgu imported, if not import it.