Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
351,000
def update_config(self, config): path = self._path() + resp = self._get_resource_root().put(path, data = config_to_json(config)) return json_to_config(resp)
Update the group's configuration. @param config: Dictionary with configuration to update. @return: Dictionary with updated configuration.
351,001
def delete(self, experiment_name): if not experiment_name.startswith(self.__tag_prefix): target_tag = self.__tag_prefix + experiment_name else: target_tag = experiment_name if target_tag not in [t.name for t in self.__repository.tags]: return False ...
Delete an experiment by removing the associated tag. :param experiment_name: the name of the experiment to be deleted :type experiment_name: str :rtype bool :return if deleting succeeded
351,002
def update_shelf(self, shelf_id, shelf_data): shelf_data[] = shelf_id return self._post( , data=shelf_data )
修改货架 :param shelf_id: 货架ID :param shelf_data: 货架详情 :return: 返回的 JSON 数据包
351,003
def lanczos(A, order, x): r try: N, M = np.shape(x) except ValueError: N = np.shape(x)[0] M = 1 x = x[:, np.newaxis] q = np.divide(x, np.kron(np.ones((N, 1)), np.linalg.norm(x, axis=0))) hiv = np.arange(0, order*M, order) V = np.zeros((N, M*order)) ...
r""" TODO short description Parameters ---------- A: ndarray Returns -------
351,004
def get_card_transfer(provider: Provider, deck: Deck, txid: str, debug: bool=False) -> Iterator: s id' rawtx = provider.getrawtransaction(txid, 1) bundle = card_bundler(provider, deck, rawtx) return card_bundle_parser(bundle, debug)
get a single card transfer by it's id
351,005
def get_mac_address_table_output_mac_address_table_mac_state(self, **kwargs): config = ET.Element("config") get_mac_address_table = ET.Element("get_mac_address_table") config = get_mac_address_table output = ET.SubElement(get_mac_address_table, "output") mac_address_tabl...
Auto Generated Code
351,006
def mscs_average(search_term, num_results, api_key, **kwargs): url_list = [] result = {: search_term} MCIS = MicrosoftCognitiveImageSearch(api_key) url_list = MCIS.search(search_term, num_results) result.update(_image_search_average(url_list, **kwargs)) return(result)
Does a Microsoft Cognitive image search to get the average color of the top x results. Arguments search_term: str tearm to search for num_results: int number of results to average api_key: str Microsoft Cognitive API key max_threads: int max number of processes to...
351,007
def warn_deprecated(since, message=, name=, alternative=, pending=False, obj_type=, addendum=): message = _generate_deprecation_message(since, message, name, alternative, pending, obj_type) warnings.warn(message, metpyDeprecation, stacklevel=...
Display deprecation warning in a standard way. Parameters ---------- since : str The release at which this API became deprecated. message : str, optional Override the default deprecation message. The format specifier `%(name)s` may be used for the name of the function, ...
351,008
def process_runner(quantity=1, queue=None, backend=None): queue_kwargs = __get_queue_opts(queue=queue, backend=backend) data = process_queue(quantity=quantity, is_runner=True, **queue_kwargs) for job in data[]: __salt__[job[]](*job[], **job[])
Process queued runners quantity number of runners to process queue queue to insert the runner reference into backend backend that to use for the queue CLI Example: .. code-block:: bash salt-run queue.process_runner salt-run queue.process_runner 5
351,009
def cli_info(self, event): self.log(, self.instance, , self.development, , self.host, , self.port, , self.insecure, , self.frontendtarget)
Provides information about the running instance
351,010
def watermark(img, mark, position=(0, 0), opacity=1, scale=1.0, tile=False, greyscale=False, rotation=0, return_name=False, **kwargs): if opacity < 1: mark = reduce_opacity(mark, opacity) if not isinstance(scale, tuple): scale = determine_scale(scale, img, mark) mark = ...
Adds a watermark to an image
351,011
def write(self, outfname=None): outfname = outfname or self.filename with codecs.open(outfname, , ) as outf: for survey in self.surveys: outf.write(.join(survey._serialize())) outf.write(++) outf.write()
Write or overwrite a `Survey` to the specified .DAT file
351,012
def _translate_stm(self, oprnd1, oprnd2, oprnd3): assert oprnd1.size and oprnd3.size assert oprnd3.size == self._address_size op1_var = self._translate_src_oprnd(oprnd1) op3_var = self._translate_src_oprnd(oprnd3) for i in range(0, oprnd1.size, 8): self._me...
Return a formula representation of a STM instruction.
351,013
def create_analysis_layer(analysis_extent, crs, name): fields = [ create_field_from_definition(analysis_name_field) ] analysis_layer = create_memory_layer( , QgsWkbTypes.PolygonGeometry, crs, fields) analysis_layer.startEditing() feature = QgsFeature() feature.setGeom...
Create the analysis layer. :param analysis_extent: The analysis extent. :type analysis_extent: QgsGeometry :param crs: The CRS to use. :type crs: QgsCoordinateReferenceSystem :param name: The name of the analysis. :type name: basestring :returns: A polygon layer with exposure's crs. ...
351,014
def _py_code_clean(lines, tab, executable): count = 0 allparams = executable.ordered_parameters if type(executable).__name__ == "Function": allparams = allparams + [executable] for p in allparams: value = _py_clean(p, tab) if value is not None: count += ...
Appends all the code lines needed to create the result class instance and populate its keys with all output variables.
351,015
def iter_contributor_statistics(self, number=-1, etag=None): url = self._build_url(, , base_url=self._api) return self._iter(int(number), url, ContributorStats, etag=etag)
Iterate over the contributors list. See also: http://developer.github.com/v3/repos/statistics/ :param int number: (optional), number of weeks to return. Default -1 will return all of the weeks. :param str etag: (optional), ETag from a previous request to the same endpoi...
351,016
def sync_config_devices(obj, newconfig, newdevices, test=False): changes = {} if newconfig is None: newconfig = {} newconfig = dict(list(zip( map(six.text_type, newconfig.keys()), map(six.text_type, newconfig.values()) ))) cck = set(newconfig.keys()) ...
Syncs the given config and devices with the object (a profile or a container) returns a changes dict with all changes made. obj : The object to sync with / or just test with. newconfig: The new config to check with the obj. newdevices: The n...
351,017
def mode(self): mu = self.mean() sigma = self.std() ret_val = math.exp(mu - sigma**2) if math.isnan(ret_val): ret_val = float("inf") return ret_val
Computes the mode of a log-normal distribution built with the stats data.
351,018
def _runAuction(self, gteeOfferPrice, gteeBidPrice, haveQ): pOffers = [offer for offer in self.offers if not offer.reactive] pBids = [bid for bid in self.bids if not bid.reactive] auction = Auction(self.case, pOffers, pBids, self.auctionType, gteeOffe...
Clears an auction to determine the quantity and price for each offer/bid.
351,019
def _report_container_count(self, containers_by_id): m_func = FUNC_MAP[GAUGE][self.use_histogram] per_state_count = defaultdict(int) filterlambda = lambda ctr: not self._is_container_excluded(ctr) containers = list(filter(filterlambda, containers_by_id.values())) for ...
Report container count per state
351,020
def apply_to(self, db: Union[BaseDB, ABC_Mutable_Mapping], apply_deletes: bool = True) -> None: for key, value in self._changes.items(): if value is DELETED: if apply_deletes: try: del db[key] ...
Apply the changes in this diff to the given database. You may choose to opt out of deleting any underlying keys. :param apply_deletes: whether the pending deletes should be applied to the database
351,021
def alt_parser(patterns): from reparse.util import remove_lower_overlapping get_first = lambda items: [i[0] for i in items] get_second = lambda items: [i[1] for i in items] def parse(line): output = [] for pattern in patterns: results = pattern.scan(line) if...
This parser is able to handle multiple different patterns finding stuff in text-- while removing matches that overlap.
351,022
def pos(string, substr, start): string = stypes.stringToCharP(string) substr = stypes.stringToCharP(substr) start = ctypes.c_int(start) return libspice.pos_c(string, substr, start)
Find the first occurrence in a string of a substring, starting at a specified location, searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pos_c.html :param string: Any character string. :type string: str :param substr: Substring to locate in the character string. :type...
351,023
def get_form_help_text(self, path): try: form_help_text = self.get_registration(path).as_form_help_text() except NotRegistered: form_help_text = u"" return form_help_text
Returns text that can be used as form help text for creating email templates.
351,024
def find_html_files(self, destination): for root, dirs, files in os.walk(destination): for f in files: if f.endswith(): yield os.path.join(root, f)
Finds all html files in the given destination.
351,025
def PDC(self): A = self.A() return np.abs(A / np.sqrt(np.sum(A.conj() * A, axis=0, keepdims=True)))
Partial directed coherence. .. math:: \mathrm{PDC}_{ij}(f) = \\frac{A_{ij}(f)} {\sqrt{A_{:j}'(f) A_{:j}(f)}} References ---------- L. A. Baccalá, K. Sameshima. Partial directed coherence: a new concept in neural structure determina...
351,026
def append(self, content, encoding=): if not self.parent.exists: self.parent.create() with open(self._filename, "ab") as output_file: if not is_text(content): Log.error(u"expecting to write unicode only") output_file.write(content.encode(encod...
add a line to file
351,027
def ensure_echo_on(): if not sys.stdin.isatty(): return try: import termios except ImportError: return attributes = termios.tcgetattr(sys.stdin) if not attributes[3] & termios.ECHO: attributes[3] |= termios.ECHO termios.tcsetattr(sys.stdin, termios.T...
Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload.
351,028
def get_matrix_dimensions(filename): stream = None try: stream = open(filename, ) length = len(stream.readlines()) stream.seek(0) width = len(stream.readline().split()) return (length, width) except IOError as err: LOG.info("Something wrong happend whil...
Reads in a matrix file (comma separated) and returns the number of rows and columns. :arg filename, the full path to the file to read.
351,029
def assure_relation(cls, cms_page): try: cms_page.cascadepage except cls.DoesNotExist: cls.objects.create(extended_object=cms_page)
Assure that we have a foreign key relation, pointing from CascadePage onto CMSPage.
351,030
def suggest(self, *replies): chips = [] for r in replies: chips.append({"title": r}) self._messages.append( {"platform": "ACTIONS_ON_GOOGLE", "suggestions": {"suggestions": chips}} ) ...
Use suggestion chips to hint at responses to continue or pivot the conversation
351,031
def cut(self, breaks, labels=None, include_lowest=False, right=True, dig_lab=3): assert_is_type(breaks, [numeric]) if self.ncols != 1: raise H2OValueError("Single-column frame is expected") if self.types[self.names[0]] not in {"int", "real"}: raise H2OValueError("A numeric column is exp...
Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[str] labels: Labels for categorical levels produced. Defaults to set notation of intervals ...
351,032
def envelope(self, instrument): def envelopeFunc(mz): if isinstance(mz, numbers.Number): return ims.spectrum_envelope(self.ptr, instrument.ptr, mz) mzs = _cffi_buffer(mz, ) n = len(mz) buf = _cffi_buffer(n, ) ret = ims.spectrum...
Computes isotopic envelope for a given instrument model :param instrument: instrument model to use :returns: isotopic envelope as a function of mass :rtype: function float(mz: float)
351,033
def validate(self, answer): if answer is None: return False else: if isinstance(self.validator, list): for v in self.validator: if not v.validate(answer): return False return True els...
Validate the answer with our Validator(s) This will support one or more validator classes being applied to this question. If there are multiple, all validators must return True for the answer to be valid.
351,034
def emit(self, name, *args, **kwargs): e = self.__property_events.get(name) if e is None: e = self.__events[name] return e(*args, **kwargs)
Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :class:`Event` to dispatch *args (Optional)...
351,035
async def send_http_response(writer, http_code: int, headers: List[Tuple[str, str]], content: bytes, http_status: str= None ) -> None: if not http_status: ...
generate http response payload and send to writer
351,036
def _compile_all_contracts(self) -> Dict: ret = {} old_working_dir = Path.cwd() chdir(_BASE) def relativise(path): return path.relative_to(_BASE) import_dir_map = [ % (k, relativise(v)) for k, v in self.contracts_source_dirs.items() ...
Compile solidity contracts into ABI and BIN. This requires solc somewhere in the $PATH and also the :ref:`ethereum.tools` python library. The return value is a dict that should be written into contracts.json.
351,037
def data(self, index, role=Qt.DisplayRole): if not index.isValid(): return to_qvariant() if role == Qt.DisplayRole: return self._display_data(index) elif role == Qt.BackgroundColorRole: return to_qvariant(get_color(self._data[index.row()][index...
Return a model data element
351,038
def get_deployment_by_name(self, service_name, deployment_name): _validate_not_none(, service_name) _validate_not_none(, deployment_name) return self._perform_get( self._get_deployment_path_using_name( service_name, deployment_name), Deployment)
Returns configuration information, status, and system properties for a deployment. service_name: Name of the hosted service. deployment_name: The name of the deployment.
351,039
def provisionar(self, equipamentos, vips): code, map = self.submit( { : { : equipamentos}, : { : vips}}, , ) return self.response(code, map, force_list=[, ])
Realiza a inserção ou alteração de um grupo virtual para o sistema de Orquestração de VM. :param equipamentos: Lista de equipamentos gerada pelo método "add_equipamento" da classe "EspecificacaoGrupoVirtual". :param vips: Lista de VIPs gerada pelo método "add_vip" da classe "EspecificacaoGrup...
351,040
def eval(self, command): if self.logger.handlers: self.logger.debug(command.decode()) if self.tcl_script: self.tcl_script.info(command) self.rc = self.tcl_interp.eval(command) if self.logger.handlers: self.logger.debug( + self.rc.decode()) ...
Execute Tcl command. Write the command to tcl script (.tcl) log file. Execute the command. Write the command and the output to general (.txt) log file. :param command: Command to execute. :returns: command raw output.
351,041
def visit_Metadata(self, metadata, *args, **kwargs): result = OrderedDict() put_scalar = lambda name, json_name=None: self.optional_attribute_scalar(result, metadata, name, json_name) put_list = lambda name, json_name=None: self.optional_attribute_list(result, metadata, name, json_name)...
Render GPX Metadata as a single JSON structure.
351,042
def player(self, player_handle): try: url = self.pubg_url + player_handle response = requests.request("GET", url, headers=self.headers) return json.loads(response.text) except BaseException as error: print( + str(error)) raise
Returns the full set of data on a player, no filtering
351,043
def get_stream(self, stream_name: str) -> StreamWrapper: if stream_name not in self._streams: stream_fn_name = .format(stream_name) try: stream_fn = getattr(self._dataset, stream_fn_name) stream_epoch_limit = -1 if self._fixed_epoc...
Get a :py:class:`StreamWrapper` with the given name. :param stream_name: stream name :return: dataset function name providing the respective stream :raise AttributeError: if the dataset does not provide the function creating the stream
351,044
def string_is_url(test_str): parsed = urlparse.urlparse(test_str) return parsed.scheme is not None and parsed.scheme !=
Test to see if a string is a URL or not, defined in this case as a string for which urlparse returns a scheme component >>> string_is_url('somestring') False >>> string_is_url('https://some.domain.org/path') True
351,045
def handle_message(self, message: BaseMessage, responder: Responder, create_task: True): coro = self._handle_message(message, responder) if create_task: loop = asyncio.get_event_loop() loop.create_tas...
Public method to handle a message. It requires: - A message from the platform - A responder from the platform If `create_task` is true, them the task will automatically be added to the loop. However, if it is not, the coroutine will be returned and it will be the respon...
351,046
def _parse_row(row): data = [] labels = HtmlTable._get_row_tag(row, "th") if labels: data += labels columns = HtmlTable._get_row_tag(row, "td") if columns: data += columns return data
Parses HTML row :param row: HTML row :return: list of values in row
351,047
def pca(df, n_components=2, mean_center=False, fcol=None, ecol=None, marker=, markersize=40, threshold=None, label_threshold=None, label_weights=None, label_scores=None, return_df=False, show_covariance_ellipse=False, *args, **kwargs): scores, weights = analysis.pca(df, n_components=n_components, *args, **kwa...
Perform Principal Component Analysis (PCA) from input DataFrame and generate scores and weights plots. Principal Component Analysis is a technique for identifying the largest source of variation in a dataset. This function uses the implementation available in scikit-learn. The PCA is calculated via `analysis.p...
351,048
def get_render_configurations(self, request, **kwargs): data = self.process_form_data(self._get_form_defaults(), kwargs) variable_set = self.get_variable_set(self.service.variable_set.order_by(), data) base_config = ImageConfiguration( extent=data[], size=data[...
Render image interface
351,049
def random_polygon(segments=8, radius=1.0): angles = np.sort(np.cumsum(np.random.random( segments) * np.pi * 2) % (np.pi * 2)) radii = np.random.random(segments) * radius points = np.column_stack( (np.cos(angles), np.sin(angles))) * radii.reshape((-1, 1)) points = np.vstack((points,...
Generate a random polygon with a maximum number of sides and approximate radius. Parameters --------- segments: int, the maximum number of sides the random polygon will have radius: float, the approximate radius of the polygon desired Returns --------- polygon: shapely.geometry.Polygon o...
351,050
def get_file_fullpath(name, dirname=None): if name is None: return None if is_string(name): name = str(name) else: raise RuntimeError() for sep in [, , os.sep]: if sep in name: name = os.path.abspath(na...
Return full path if available.
351,051
def get_plugin_modules(folders, package=, parentpackage=): for folder in folders: for module in loader.get_folder_modules(folder, parentpackage): yield module for module in loader.get_package_modules(package): yield module
Get plugin modules for given folders.
351,052
def best_cat_heuristic_split(self, ind, dep): split = Split(None, None, None, None, 0) min_child_node_size = self.min_child_node_size all_dep = np.unique(dep.arr) if len(all_dep) == 1: split.invalid_reason = InvalidSplitReason.PURE_NODE return split ...
determine best categorical variable split using heuristic methods
351,053
def removed(name, features=None, remove_payload=False, restart=False): ret = {: name, : True, : {}, : } if features is None: features = name.split() if not isinstance(features, list): features = features.split() old = __salt__[]() ...
Remove the windows feature To remove a single feature, use the ``name`` parameter. To remove multiple features, use the ``features`` parameter. Args: name (str): Short name of the feature (the right column in win_servermanager.list_available). This can be a single feature or a ...
351,054
def _pfp__build(self, stream=None, save_offset=False): if stream is not None and save_offset: self._pfp__offset = stream.tell() data = self._pfp__value + utils.binary("\x00") if stream is None: return data else: stream.write(data) ...
Build the String field :stream: TODO :returns: TODO
351,055
def _set_line_eol(src, line): line_ending = _get_eol(src) or os.linesep return line.rstrip() + line_ending
Add line ending
351,056
def drop_columns(self, model, *names, **kwargs): fields = [field for field in model._meta.fields.values() if field.name in names] cascade = kwargs.pop(, True) for field in fields: self.__del_field__(model, field) if field.unique: index_name = make...
Remove fields from model.
351,057
def ngrams(tokens, min_n, max_n): all_ngrams = list() n_tokens = len(tokens) for i in xrange(n_tokens): for j in xrange(i + min_n, min(n_tokens, i + max_n) + 1): all_ngrams.append(" ".join(tokens[i:j])) return all_ngrams
Generates ngrams(word sequences of fixed length) from an input token sequence. tokens is a list of words. min_n is the minimum length of an ngram to return. max_n is the maximum length of an ngram to return. returns a list of ngrams (words separated by a space)
351,058
def ParseOptions(cls, options, output_module): if not isinstance(output_module, shared_4n6time.Shared4n6TimeOutputModule): raise errors.BadConfigObject( ) append = getattr(options, , cls._DEFAULT_APPEND) evidence = cls._ParseStringOption( options, , default_value=cls._DEFAULT_E...
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object is of the wrong type.
351,059
def inertia_tensor(geom, masses): import numpy as np geom = ctr_geom(geom, masses) if geom.shape[0] == 3*masses.shape[0]: masses = masses.repeat(3) tensor = np.zeros((3,3)) for i in range(3): for j in range(i,3): if i == j...
Generate the 3x3 moment-of-inertia tensor. Compute the 3x3 moment-of-inertia tensor for the provided geometry and atomic masses. Always recenters the geometry to the center of mass as the first step. Reference for inertia tensor: [Kro92]_, Eq. (2.26) .. todo:: Replace cite eventually with link t...
351,060
def _iparam_instancename(instancename): if isinstance(instancename, CIMInstanceName): instancename = instancename.copy() instancename.host = None instancename.namespace = None elif instancename is None: pass else: raise TypeEr...
Convert an instance name specified in an operation method into a CIM object that can be passed to imethodcall().
351,061
def delete_ptr_records(self, device, ip_address=None): return self._manager.delete_ptr_records(device, ip_address=ip_address)
Deletes the PTR records for the specified device. If 'ip_address' is supplied, only the PTR records with that IP address will be deleted.
351,062
def _str2datetime(self, datetimestr): if datetimestr is None: raise ValueError( "Parser must be a string or character stream, not NoneType") try: return datetime.strptime( datetimestr, self.default_datetime_template) exce...
Parse datetime from string. If no template matches this string, raise Error. Please go https://github.com/MacHu-GWU/rolex-project/issues submit your datetime string. I 'll update templates asap. This method is faster than :meth:`dateutil.parser.parse`. :param datetimestr: a str...
351,063
def extract(self, html_text: str, strategy: Strategy=Strategy.ALL_TEXT) \ -> List[Extraction]: if html_text: if strategy == Strategy.ALL_TEXT: soup = BeautifulSoup(html_text, ) texts = soup.findAll(text=True) visible_texts = filte...
Extracts text from an HTML page using a variety of strategies Args: html_text (str): html page in string strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_RELAXED, Strategy.MAIN_CONTENT_STRICT]): one of Strategy.ALL_TEXT, Strategy.MAIN_CONTENT_STRICT and Strategy.MAIN_...
351,064
def estimate_completion(self): if self.state != build_states.BUILDING: defer.returnValue(self.completed) avg_delta = yield self.connection.getAverageBuildDuration(self.name) est_completion = self.started + avg_delta defer.returnValue(est_completion)
Estimate completion time for a build. This calls getAverageBuildDuration on the hub for this package. This value is a very rough guess, an average for all completed builds in the system. For now this is better than nothing, but I'm recording a few thoughts here for posterity: ...
351,065
def get_default_value(self): if self.choices: return self.choices[0] value = self.attribute_type() if self.attribute_type is time: value = int(value) elif self.attribute_type is str: value = "A" if self.min_length: if ...
Get a default value of the attribute_type
351,066
def edit_assignment_group(self, course_id, assignment_group_id): path = {} data = {} params = {} path["course_id"] = course_id path["assignment_group_id"] = assignment_group_id self.logger.debug("PUT /api/v1/cour...
Edit an Assignment Group. Modify an existing Assignment Group. Accepts the same parameters as Assignment Group creation
351,067
def _valid_numpy_subdtype(x, numpy_types): for t in numpy_types: assert not np.issubdtype(np.generic, t) return any(np.issubdtype(x.dtype, t) for t in numpy_types)
Is any dtype from numpy_types superior to the dtype of x?
351,068
def create_or_update_table(self, tablename: str, fieldspeclist: FIELDSPECLIST_TYPE, drop_superfluous_columns: bool = False, dynamic: bool = False, compressed: bool =...
- Make table, if it doesn't exist. - Add fields that aren't there. - Warn about superfluous fields, but don't delete them, unless ``drop_superfluous_columns == True``. - Make indexes, if requested.
351,069
def getClass(self, id=None, uri=None, match=None): if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not uri.startswith("http://"): match = uri uri = None ...
get the saved-class with given ID or via other methods... Note: it tries to guess what is being passed.. In [1]: g.getClass(uri='http://www.w3.org/2000/01/rdf-schema#Resource') Out[1]: <Class *http://www.w3.org/2000/01/rdf-schema#Resource*> In [2]: g.getClass(10) Out[2]: <Clas...
351,070
def _validate_pillar_roots(pillar_roots): if not isinstance(pillar_roots, dict): log.warning( ) return {: _expand_glob_path([salt.syspaths.BASE_PILLAR_ROOTS_DIR])} return _normalize_roots(pillar_roots)
If the pillar_roots option has a key that is None then we will error out, just replace it with an empty list
351,071
def maximum_notifiers(self, value): if value is not None: assert type(value) is int, " attribute: type is not !".format("maximum_notifiers", value) assert value > 0, " attribute: need to...
Setter for **self.__maximum_notifiers** attribute. :param value: Attribute value. :type value: int
351,072
def _check_api_limits(gh_session, api_required=250, sleep_time=15): api_rates = gh_session.rate_limit() api_remaining = api_rates[][] api_reset = api_rates[][] logger.debug(, api_remaining) if api_remaining > api_required: return now_time = time.time() time_to_reset = int(api...
Simplified check for API limits If necessary, spin in place waiting for API to reset before returning. See: https://developer.github.com/v3/#rate-limiting
351,073
def update_resources(Cnt): key_list = [, , , , ] path_resources = cs.path_niftypet_local() resources_file = os.path.join(path_resources,) if os.path.isfile(resources_file): f = open(resources_file, ) rsrc = f.read() f.close() i0 = rsrc.find...
Update resources.py with the paths to the new installed apps.
351,074
def data_response(self): d = [] for i in range(self._num_bands): if self._compute_bool[i] is True: d_i = self._imageModel_list[i].data_response if d == []: d = d_i else: d = np.append(d, d_i) ...
returns the 1d array of the data element that is fitted for (including masking) :return: 1d numpy array
351,075
def accept_rpc(self, service, mask, value, method, handler=None, schedule=True): ed against the incoming id, the result of which must mask the param :type mask: int :param value: the result of `routing_id & mask` must match this in order to trigge...
Set a handler for incoming RPCs :param service: the incoming RPC must have this service :type service: anything hash-able :param mask: value to be bitwise-and'ed against the incoming id, the result of which must mask the 'value' param :type mask: int :par...
351,076
def setup(options): sys.path.insert(0, options.gae_lib_path) from dev_appserver import fix_sys_path fix_sys_path()
Grabs the gae_lib_path from the options and inserts it into the first index of the sys.path. Then calls GAE's fix_sys_path to get all the proper GAE paths included. :param options:
351,077
def collect_commands(package_name=None, in_place=False, level=1): commands = {} frame = inspect.stack()[level][0] f_globals = frame.f_globals if package_name is None: package_name = f_globals[].rsplit(, 1)[0] package_paths = [os.path.dirname(f_globals[])] else: ...
Collect commands from package and its subpackages. This replaces the tedium of adding and maintaining a bunch of imports like ``from .xyz import x, y, z`` in modules that are used to collect all of the commands in a package. Args: package_name (str): Package to collect from. If not passed, the...
351,078
def convert_belscript(ctx, input_fn, output_fn): try: ( out_fh, yaml_flag, jsonl_flag, json_flag, ) = bel.nanopub.files.create_nanopubs_fh(output_fn) if yaml_flag or json_flag: docs = [] if re.search("gz$", ...
Convert belscript to nanopubs_bel format This will convert the OpenBEL BELScript file format to nanopub_bel-1.0.0 format. \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, will written as a gzip file If output fn has *.jso...
351,079
def run_subcommand(netgear, args): subcommand = args.subcommand if subcommand == "block_device" or subcommand == "allow_device": return netgear.allow_block_device(args.mac_addr, BLOCK if subcommand == "block_device" else ALLOW) if subcommand == "attached_devices": if args.verbose: ...
Runs the subcommand configured in args on the netgear session
351,080
def _binary_replace(old, new): old_isbin = not __utils__[](old) new_isbin = not __utils__[](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return elif old_isbin: return elif new_isbin: return return
This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined t...
351,081
def _attempt_slice_retry(self, shard_state, tstate): if (shard_state.slice_retries + 1 < parameters.config.TASK_MAX_DATA_PROCESSING_ATTEMPTS): logging.warning( "Slice %s %s failed for the %s of up to %s attempts " "(%s of %s taskqueue execution attempts). " "Will ret...
Attempt to retry this slice. This method may modify shard_state and tstate to prepare for retry or fail. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. Returns: A _TASK_DIRECTIVE enum. RETRY_SLICE if slice should be retried. ...
351,082
def is_human(data, builds=None): def has_build37_contigs(data): for contig in ref.file_contigs(dd.get_ref_file(data)): if contig.name.startswith("GL") or contig.name.find("_gl") >= 0: if contig.name in naming.GMAP["hg19"] or contig.name in naming.GMAP["GRCh37"]: ...
Check if human, optionally with build number, search by name or extra GL contigs.
351,083
def get_dcm_reader(store_metadata=True, header_fields=None): if not store_metadata: return lambda fpath: fpath if header_fields is None: build_dcm = lambda fpath: DicomFile(fpath) else: dicom_header = namedtuple(, header_fields) build_dcm...
Creates a lambda function to read DICOM files. If store_store_metadata is False, will only return the file path. Else if you give header_fields, will return only the set of of header_fields within a DicomFile object or the whole DICOM file if None. :return: function This...
351,084
def tabText(self, tab): if not isinstance(tab, int): tab = self.indexOf(tab) return super(FwTabWidget, self).tabText(tab)
allow index or tab widget instance
351,085
def get_network_interface(name=None, network_interface_id=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} result = _get_network_interface(conn, name, network_interface_id) if in result: ...
Get an Elastic Network Interface. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt myminion boto_ec2.get_network_interface name=my_eni
351,086
def save(self, *args, **kwargs): if not hasattr(self,): if self.received and not self.receivedDate: self.receivedDate = timezone.now() else: if self.received and not self.receivedDate and not self.__receivedDate: self.receivedDat...
This custom save method ensures that a revenue item is not attributed to multiple categories. It also ensures that the series and event properties are always associated with any type of revenue of that series or event.
351,087
def clean_files(files): if isinstance(files, (list, tuple)): for f in files: yield clean_file(f) else: yield clean_file(files)
Generates tuples with a ``file``-like object and a close indicator. This is a generator of tuples, where the first element is the file object and the second element is a boolean which is True if this module opened the file (and thus should close it). Raises ------ OSError : Accessing the given...
351,088
def keypoint_random_flip( image, annos, mask=None, prob=0.5, flip_list=(0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16, 18) ): _prob = np.random.uniform(0, 1.0) if _prob < prob: return image, annos, mask _, width, _ = np.shape(image) image = cv2.flip(image, 1) ma...
Flip an image and corresponding keypoints. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. prob : float, 0 to 1 ...
351,089
def _ta_plot(self,study,periods=14,column=None,include=True,str=,detail=False, theme=None,sharing=None,filename=,asFigure=False,**iplot_kwargs): if in iplot_kwargs: column=iplot_kwargs.pop() if in iplot_kwargs: periods=iplot_kwargs.pop() if in iplot_kwargs: sharing=iplot_kwargs.pop() if in i...
Generates a Technical Study Chart Parameters: ----------- study : string Technical Study to be charted sma - 'Simple Moving Average' rsi - 'R Strength Indicator' periods : int Number of periods column : string Name of the column on which the study will be done include : bool ...
351,090
def propagateClk(obj): clk = obj.clk for u in obj._units: _tryConnect(clk, u, )
Propagate "clk" clock signal to all subcomponents
351,091
def push_dir(path, glob=None, upload_path=None): s minion files cachedir (defaults to ``/var/cache/salt/master/minions/minion-id/files``). It also has a glob for matching specific files using globbing. .. versionadded:: 2014.7.0 Since this feature allows a minion to push files up to the master se...
Push a directory from the minion up to the master, the files will be saved to the salt master in the master's minion files cachedir (defaults to ``/var/cache/salt/master/minions/minion-id/files``). It also has a glob for matching specific files using globbing. .. versionadded:: 2014.7.0 Since thi...
351,092
def rename_register(self, regname, newname): if regname == newname: return if newname in self.qregs or newname in self.cregs: raise DAGCircuitError("duplicate register name %s" % newname) if regname not in self.qregs and regname not in self.cregs: rai...
Rename a classical or quantum register throughout the circuit. regname = existing register name string newname = replacement register name string
351,093
def _cuthill_mckee(vertices, vertices_neighbours): vertices_degrees = {v: sum(itervalues(vertices_neighbours[v])) for v in vertices} peripheral_vertex = min(vertices, key=(lambda v: vertices_degrees[v])) visited = set([peripheral_vertex]) cm_order = [peripheral_vertex] ...
Yield the Cuthill-McKee order for a connected, undirected graph. `Wikipedia <https://en.wikipedia.org/wiki/Cuthill%E2%80%93McKee_algorithm>`_ provides a good introduction to the Cuthill-McKee algorithm. The RCM algorithm attempts to order vertices in a graph such that their adjacency matrix's bandw...
351,094
def get_route(ip): * if __grains__[] == : cmd = .format(ip) out = __salt__[](cmd, python_shell=True) regexp = re.compile(r) m = regexp.search(out.splitlines()[0]) ret = { : ip, : m.group(), : m.group(), : m.group() ...
Return routing information for given destination ip .. versionadded:: 2015.5.3 .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) Added support for OpenBSD .. versionchanged:: 2016.11.4 Added support for AIX CLI Example:: salt '*' net...
351,095
def send_ip(self, ipaddr, apikey): url = self.base_url + "ip-address/report" parameters = {"ip": ipaddr, "apikey": apikey} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = requests.get(url, params=parameters) if response.status_code ==...
Send IP address for list of past malicous domain associations
351,096
def complete_command_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]: for idx, token in enumerate(tokens): if idx >= self._token_start_index: if self._positional_completers: ...
Supports the completion of sub-commands for commands through the cmd2 help command.
351,097
def import_(module_name, backport=False): modules.append(importlib.import_module(sofar)) for i, part in reversed(list(enumerate(parts))): if i == 0: break setattr(modules[i-1], part, modules[i]) return modules[2]
Pass a (potentially dotted) module name of a Python 3 standard library module. This function imports the module compatibly on Py2 and Py3 and returns the top-level module. Example use: >>> http = import_('http.client') >>> http = import_('http.server') >>> urllib = import_('urllib.r...
351,098
def returnModPositions(peptide, indexStart=1, removeModString=): unidmodPositionDict = dict() while peptide.find() != -1: currModification = peptide.split()[1].split()[0] currPosition = peptide.find() - 1 if currPosition == -1: currPosition = 0 currPosition += i...
Determines the amino acid positions of all present modifications. :param peptide: peptide sequence, modifications have to be written in the format "[modificationName]" :param indexStart: returned amino acids positions of the peptide start with this number (first amino acid position = indexStart...
351,099
def newmodel(f, G, y0, name=, modelType=ItoModel): if not issubclass(modelType, Model): raise SimTypeError() if not callable(f) or (G is not None and not callable(G)): raise SimTypeError() if G is not None and f.__globals__ is not G.__globals__: raise SimValueError() ...
Use the functions f and G to define a new Model class for simulations. It will take functions f and G from global scope and make a new Model class out of them. It will automatically gather any globals used in the definition of f and G and turn them into attributes of the new Model. Args: f: cal...