Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
8,700
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation=): xyz_x = color.xyz_x xyz_y = color.xyz_y xyz_z = color.xyz_z orig_illum = color.illuminant targ_illum = targ_illum.lower() observer = color.observer adaptation = adaptation.lower() color.xyz_x, color.xyz_y...
Convenience function to apply an adaptation directly to a Color object.
8,701
def generate_apsara_log_config(json_value): input_detail = json_value[] output_detail = json_value[] config_name = json_value[] logSample = json_value.get(, ) logstore_name = output_detail[] endpoint = output_detail.get(, ) log_path = input_detail[] ...
Generate apsara logtail config from loaded json value :param json_value: :return:
8,702
def xmlrpc_task_done(self, result): (task_id, task_results) = result del self.scheduled_tasks[task_id] self.task_store.update_results(task_id, task_results) self.results += 1 return True
Take the results of a computation and put it into the results list.
8,703
def _set_digraph_b(self, char): self.has_digraph_b = True self.active_vowel_ro = di_b_lt[char][0] self.active_dgr_b_info = di_b_lt[char]
Sets the second part of a digraph.
8,704
def aspirate(self, volume: float = None, location: Union[types.Location, Well] = None, rate: float = 1.0) -> : self._log.debug("aspirate {} from {} at {}" .format(volume, location if location else...
Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location If only a volume is passed, the pipette will aspirate from its current position. If only a location is passed, :py:meth:`aspirate` will default to its :py:attr:`max_volume`. :param vo...
8,705
def update(self, y=None, inplace=False, **kwargs): kwargs.update({: kwargs.pop(, self.k)}) kwargs.update({: kwargs.pop(, self.pct)}) kwargs.update({: kwargs.pop(, self._truncated)}) if inplace: self._update(y, **kwargs) else: new = copy.deepcopy(s...
Add data or change classification parameters. Parameters ---------- y : array (n,1) array of data to classify inplace : bool whether to conduct the update in place or to return a copy estimated fro...
8,706
def toto(arch_name, comment=, clear=False, read_comment=False, list_members=False, time_show=False): if comment and clear: clingon.RunnerError("You cannot specify --comment and --clear together") z = None if not os.path.isfile(arch_name): print "Creating archive", arch_name ...
Small utility for changing comment in a zip file without changing the file modification datetime.
8,707
def perform_command(self): if self.has_option([u"--list-parameters"]): return self.print_parameters() if len(self.actual_arguments) < 2: return self.print_help() container_path = self.actual_arguments[0] output_directory_path = self.actual_arguments[1] ...
Perform command and return the appropriate exit code. :rtype: int
8,708
def add_node(self,node): if not isinstance(node, CondorDAGNode): raise CondorDAGError, "Nodes must be class CondorDAGNode or subclass" if not isinstance(node.job(), CondorDAGManJob): node.set_log_file(self.__log_file_path) self.__nodes.append(node) if self.__integer_node_names: no...
Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being written. @param node: CondorDAGNo...
8,709
def _api_item_history(self, plugin, item, nb=0): return self._api_itemvalue(plugin, item, history=True, nb=int(nb))
Glances API RESTful implementation. Return the JSON representation of the couple plugin/history of item HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error
8,710
def withdraw(self, amount): pg = self.usr.getPage("http://www.neopets.com/bank.phtml") try: results = pg.find(text = "Account Type:").parent.parent.parent.find_all("td", align="center") self.balance = results[1].text.replace(" NP", "") except Exception: ...
Withdraws specified neopoints from the user's account, returns result Parameters: amount (int) -- Amount of neopoints to withdraw Returns bool - True if successful, False otherwise Raises notEnoughBalance
8,711
def query(self, sql, parameters=None): try: self._cursor.execute(sql, parameters) except psycopg2.Error as err: self._incr_exceptions() raise err finally: self._incr_executions() return results.Results(self._cursor)
A generator to issue a query on the server, mogrifying the parameters against the sql statement. Results are returned as a :py:class:`queries.Results` object which can act as an iterator and has multiple ways to access the result data. :param str sql: The SQL statement :param di...
8,712
def push(self, value: Union[int, bytes]) -> None: if len(self.values) > 1023: raise FullStack() validate_stack_item(value) self.values.append(value)
Push an item onto the stack.
8,713
def _remove_from_world(self): self.on_remove_from_world() self._extensions = {} self._disable_forum_observation() self._world = None self._id = None
Clear all the internal data the token needed while it was part of the world. Note that this method doesn't actually remove the token from the world. That's what World._remove_token() does. This method is just responsible for setting the internal state of the token being removed.
8,714
def _setAttributes(self, attributes): atd = self.attribute_typecode atd_list = formatted_attribute_list = [] if not attributes: return formatted_attribute_list atd_list.append() idx = 0 while(idx < len(attributes)): a = attributes...
parameters attributes -- a flat list of all attributes, from this list all items in attribute_typecode_dict will be generated into attrComponents. returns a list of strings representing the attribute_typecode_dict.
8,715
def dst_to_src(self, dst_file): for map in self.mappings: src_uri = map.dst_to_src(dst_file) if (src_uri is not None): return(src_uri) raise MapperError( "Unable to translate destination path (%s) " "into a source URI." % ...
Map destination path to source URI.
8,716
def get_img_tag(self, title=, alt_text=, **kwargs): try: style = [] for key in (, ): if key in kwargs: if isinstance(kwargs[key], (list, tuple, set)): style += list(kwargs[key]) else: ...
Build a <img> tag for the image with the specified options. Returns: an HTML fragment.
8,717
def ContainsKey(self, public_key): return self.ContainsKeyHash(Crypto.ToScriptHash(public_key.encode_point(True), unhex=True))
Test if the wallet contains the supplied public key. Args: public_key (edcsa.Curve.point): a public key to test for its existance. e.g. KeyPair.PublicKey Returns: bool: True if exists, False otherwise.
8,718
def isSelectionPositionValid(self, selPos: tuple): if selPos is None: return False if len(selPos) != 4: return False check1 = self.isPositionValid(*selPos[:2]) check2 = self.isPositionValid(*selPos[2:]) if check1 and check2: return Tru...
Return **True** if the start- and end position denote valid positions within the document. |Args| * ``selPos`` (**tuple**): tuple with four integers. |Returns| **bool**: **True** if the positions are valid; **False** otherwise. |Raises| * **None**
8,719
def get_health_events(self, recipient): if recipient not in self.addresses_events: self.start_health_check(recipient) return self.addresses_events[recipient]
Starts a healthcheck task for `recipient` and returns a HealthEvents with locks to react on its current state.
8,720
def cached_download(url, name): clean_name = os.path.normpath(name) if clean_name != name: raise ValueError("{} is not normalized.".format(name)) for dir_ in iter_data_dirs(): path = os.path.join(dir_, name) if os.path.exists(path): return path dir_ = next(it...
Download the data at a URL, and cache it under the given name. The file is stored under `pyav/test` with the given name in the directory :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of: - the current virtualenv - ``/usr/local/share`` - ``/usr/local/lib`` - ``/usr/share`` - `...
8,721
def _write_error_batch_wait(future, batch, database, measurement, measurements): if not future.done(): ioloop.IOLoop.current().add_timeout( ioloop.IOLoop.current().time() + 0.025, _write_error_batch_wait, future, batch, database, measurement, ...
Invoked by the IOLoop, this method checks if the HTTP request future created by :meth:`_write_error_batch` is done. If it's done it will evaluate the result, logging any error and moving on to the next measurement. If there are no measurements left in the `measurements` argument, it will consider the ba...
8,722
def _activity_import_doc(self, time_doc, activities): batch_updates = [time_doc] td_start = time_doc[] activities = filter(lambda act: (act[0] < td_start and act[1] in time_doc), activities) creation_fi...
Import activities for a single document into timeline.
8,723
def byteorder_isnative(byteorder): if byteorder in (, sys.byteorder): return True keys = {: , : } return keys.get(byteorder, byteorder) == keys[sys.byteorder]
Return if byteorder matches the system's byteorder. >>> byteorder_isnative('=') True
8,724
def calculate_leaf_paths(self): reverse_xref = {} leaves = set() for v in self.value.values(): if v.leaf: leaves.add(v) for xref in v.value_xref: reverse_xref.setdefault(xref, []).append(v.ident) for leaf in leaves: ...
Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
8,725
def update_text(self): self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
Write the current text, and check for any new text changes. This also updates the elapsed time.
8,726
def gcm_send_message(registration_id, data, encoding=, **kwargs): messenger = GCMMessenger(registration_id, data, encoding=encoding, **kwargs) return messenger.send_plain()
Standalone method to send a single gcm notification
8,727
def consume(self, data): if not self._started: self.fire(JSONStreamer.DOC_START_EVENT) self._started = True self._file_like.write(data) try: self._parser.parse(self._file_like) except YajlError as ye: raise JSONStreamerException(ye...
Takes input that must be parsed Note: Attach all your listeners before calling this method Args: data (str): input json string
8,728
def run_filter_radia(job, bams, radia_file, univ_options, radia_options, chrom): job.fileStore.logToMaster( % (univ_options[], chrom)) work_dir = job.fileStore.getLocalTempDir() input_files = { : bams[], : bams[], : bams[], : bams[], : bams[], : bams[], ...
This module will run filterradia on the RNA and DNA bams. ARGUMENTS 1. bams: REFER ARGUMENTS of run_radia() 2. univ_options: REFER ARGUMENTS of run_radia() 3. radia_file: <JSid of vcf generated by run_radia()> 3. radia_options: REFER ARGUMENTS of run_radia() 4. chrom: REFER ARGUMENTS of run_rad...
8,729
def find_all(self, predicate): for _nid, entry in self._registry.items(): if predicate(entry): yield entry
Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool.
8,730
def master_event(type, master=None): event_map = {: , : , : , : } if type == and master is not None: return .format(event_map.get(type), master) return event_map.get(type, None)
Centralized master event function which will return event type based on event_map
8,731
def remove_optional(annotation: type): origin = getattr(annotation, , None) args = getattr(annotation, , ()) if origin == Union and len(args) == 2 and args[1] == type(None): return args[0] else: return annotation
Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away.
8,732
def node_to_text(self, node, prev_node_hint=None): if node is None: return "" if node.isNodeType(latexwalker.LatexCharsNode): if not self.strict_latex_spaces[] and len(node.chars.strip()) == 0: ...
Return the textual representation of the given `node`. If `prev_node_hint` is specified, then the current node is formatted suitably as following the node given in `prev_node_hint`. This might affect how much space we keep/discard, etc.
8,733
def show_quickref(self): from IPython.core.usage import quick_reference self.main.help.show_plain_text(quick_reference)
Show IPython Cheat Sheet
8,734
def run_opt(self, popsize, numgen, processors, plot=False, log=False, **kwargs): self._params[] = popsize self._params[] = numgen self._params[] = processors self._params[] = plot self._params[] = log self._params.update(**kwargs) ...
Runs the optimizer. :param popsize: :param numgen: :param processors: :param plot: :param log: :param kwargs: :return:
8,735
def parse_csv(self, infile, delimiter=",", decimal_sep="."): "Parse template format csv file and create elements dict" keys = (,,,,,,,, ,,,,, ,,, ) self.elements = [] self.pg_no = 0 if not PY3K: f = open(infile, ) else: f = ...
Parse template format csv file and create elements dict
8,736
def merge(revision, branch_label, message, list_revisions=): alembic_command.merge( config=get_config(), revisions=list_revisions, message=message, branch_label=branch_label, rev_id=revision )
Merge two revision together, create new revision file
8,737
def get_containers(self): images = {} for x in self._docker.images.list(filters={"label": "org.inginious.grading.name"}): try: title = x.labels["org.inginious.grading.name"] created = datetime.strptime(x.attrs[][:-4], "%Y-%m-%dT%H:%M:%S.%f")...
:return: a dict of available containers in the form { "name": { #for example, "default" "id": "container img id", # "sha256:715c5cb5575cdb2641956e42af4a53e69edf763ce701006b2c6e0f4f39b68dd3" "created": 12345678 # cre...
8,738
def _verify_docker_image_size(self, image_name): shell_call([, , image_name]) try: image_size = subprocess.check_output( [, , , image_name]).strip() image_size = int(image_size) except (ValueError, subprocess.CalledProcessError) as e: logging.error(, e) return False ...
Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is within the limits, False otherwise.
8,739
def default(self, statement: Statement) -> Optional[bool]: if self.default_to_shell: if not in self.exclude_from_history: self.history.append(statement) return self.do_shell(statement.command_and_args) else: err_msg = self.default_error.form...
Executed when the command given isn't a recognized command implemented by a do_* method. :param statement: Statement object with parsed input
8,740
def get_pr_review_status(pr: PullRequestDetails) -> Any: url = ("https://api.github.com/repos/{}/{}/pulls/{}/reviews" "?access_token={}".format(pr.repo.organization, pr.repo.name, pr.pull_id, ...
References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
8,741
def submit_combine(basename, readers, job_ids=None, project_name=None): sub = PmidSubmitter(basename, readers, project_name) sub.job_list = job_ids sub.submit_combine() return sub
Submit a batch job to combine the outputs of a reading job. This function is provided for backwards compatibility. You should use the PmidSubmitter and submit_combine methods.
8,742
def patch( target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs ): getter, attribute = _get_target(target) return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs )
`patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with a `MagicMock`...
8,743
def invert_affine_mat44(mat): inverted = Matrix44() for i in range(3): for j in range(3): inverted.data[i][j] = mat.data[j][i] for row in range(3): inverted.data[3][row] = ( -inverted.data[0][row] * mat.data[3][0] + -inverted.data[1][row]...
Assumes there is only rotate, translate, and uniform scale componenets to the matrix.
8,744
def getReadLengths(reads, gapChars): gapChars = set(gapChars) result = {} for read in reads: result[read.id] = len(read) - sum( character in gapChars for character in read.sequence) return result
Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values.
8,745
def codegen(lang, i, schema_metadata, loader ): j = schema.extend_and_specialize(i, loader) gen = None if lang == "python": gen = PythonCodeGen(sys.stdout) elif lang == "java": gen = Java...
Generate classes with loaders for the given Schema Salad description.
8,746
def _split_generators(self, dl_manager): url = _DL_URLS[self.builder_config.name] data_dirs = dl_manager.download_and_extract(url) path_to_dataset = os.path.join(data_dirs, tf.io.gfile.listdir(data_dirs)[0]) train_a_path = os.path.join(path_to_dataset, "trainA") train_b_path = os.path.join(pa...
Returns SplitGenerators.
8,747
def process_bool_arg(arg): if isinstance(arg, bool): return arg elif isinstance(arg, basestring): if arg.lower() in ["true", "1"]: return True elif arg.lower() in ["false", "0"]: return False
Determine True/False from argument
8,748
def get_var_dict_from_ctx(ctx: commands.Context, prefix: str = ): raw_var_dict = { : ctx.author, : ctx.bot, : ctx.channel, : ctx, : discord.utils.find, : discord.utils.get, : ctx.guild, : ctx.message, : ctx.message } return {f: v...
Returns the dict to be used in REPL for a given Context.
8,749
def exportPreflibFile(self, fileName): elecType = self.getElecType() if elecType != "soc" and elecType != "toc" and elecType != "soi" and elecType != "toi": print("ERROR: printing current type to preflib format is not supported") exit() rever...
Exports a preflib format file that contains all the information of the current Profile. :ivar str fileName: The name of the output file to be exported.
8,750
def get_spot_value(self, assets, field, dt, data_frequency): assets_is_scalar = False if isinstance(assets, (AssetConvertible, PricingDataAssociable)): assets_is_scalar = True else: try: iter(assets) except Ty...
Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. The asset or assets whose data is desired. field : {'open', 'high', ...
8,751
def new_table_graphicFrame(cls, id_, name, rows, cols, x, y, cx, cy): graphicFrame = cls.new_graphicFrame(id_, name, x, y, cx, cy) graphicFrame.graphic.graphicData.uri = GRAPHIC_DATA_URI_TABLE graphicFrame.graphic.graphicData.append( CT_Table.new_tbl(rows, cols, cx, cy) ...
Return a ``<p:graphicFrame>`` element tree populated with a table element.
8,752
def reply_topic(self, topic_id, content): data = { : content, : self._request.cookies.get() } url = % topic_id r = self.request(url, , data=data) j = r.json() if j[] == 0: return j[][][]
小组回帖 :return: 帖子 id 或 ``None``
8,753
def get_host_health_temperature_sensors(self, data=None): data = self.get_host_health_data(data) d = data[][][] if not isinstance(d, list): d = [d] return d
Get the health Temp Sensor report. :param: the data to retrieve from the server, defaults to None. :returns: the dictionary containing the temperature sensors information. :raises: IloConnectionError if failed connecting to the iLO. :raises: IloError, on an error from iLO.
8,754
def register_actions(self, shortcut_manager): assert isinstance(shortcut_manager, ShortcutManager) self.__shortcut_manager = shortcut_manager for controller in list(self.__child_controllers.values()): if controller not in self.__action_registered_controllers: ...
Register callback methods for triggered actions in all child controllers. :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
8,755
def nmap_discover(): rs = RangeSearch() rs_parser = rs.argparser arg = argparse.ArgumentParser(parents=[rs_parser], conflict_handler=) arg.add_argument(, metavar=, \ help=, \ type=str, choices=[, ]) arguments, nmap_args = arg.parse_known_args() tag = None if arguments.t...
This function retrieves ranges from jackal Uses two functions of nmap to find hosts: ping: icmp / arp pinging of targets lookup: reverse dns lookup
8,756
def _get_labels_right(self, validate=None): labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_right) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" ...
Get all labels of the right dataframe.
8,757
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): assert wait_for_completion is True storage_group_oid = uri_parms[0] storage_group_uri = + storage_group_oid try: storage_group = hmc.lookup_by_uri(storage_group...
Operation: Add Candidate Adapter Ports to an FCP Storage Group.
8,758
def visit_exec(self, node, parent): newnode = nodes.Exec(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.body, newnode), _visit_or_none(node, "globals", self, newnode), _visit_or_none(node, "locals", self, newnode), ) r...
visit an Exec node by returning a fresh instance of it
8,759
def is_confusable(string, greedy=False, preferred_aliases=[]): preferred_aliases = [a.upper() for a in preferred_aliases] outputs = [] checked = set() for char in string: if char in checked: continue checked.add(char) char_alias = alias(char) if char_alia...
Checks if ``string`` contains characters which might be confusable with characters from ``preferred_aliases``. If ``greedy=False``, it will only return the first confusable character found without looking at the rest of the string, ``greedy=True`` returns all of them. ``preferred_aliases=[]`` can ...
8,760
def step(self, **args): if self.sequenceType == None: raise AttributeError() if in args: if args[]: self.setContext() del args[] elif self.initContext: self.setContext() ...
SRN.step() Extends network step method by automatically copying hidden layer activations to the context layer.
8,761
def find(entity, **kwargs): try: typedfields = entity.typed_fields() except AttributeError: typedfields = iterfields(entity.__class__) matching = [x for x in typedfields if _matches(x, kwargs)] return matching
Return all TypedFields found on the input `Entity` that were initialized with the input **kwargs. Example: >>> find(myentity, multiple=True, type_=Foo) Note: TypedFields.__init__() can accept a string or a class as a type_ argument, but this method expects a class. Args: ...
8,762
def arraymax(X,Y): Z = np.zeros((len(X),), int) A = X <= Y B = Y < X Z[A] = Y[A] Z[B] = X[B] return Z
Fast "vectorized" max function for element-wise comparison of two numpy arrays. For two numpy arrays `X` and `Y` of equal length, return numpy array `Z` such that:: Z[i] = max(X[i],Y[i]) **Parameters** **X** : numpy array Numpy array; `len(X) = len(Y)`. ...
8,763
def server_extensions_handshake(requested, supported): accepts = {} for offer in requested: name = offer.split(";", 1)[0].strip() for extension in supported: if extension.name == name: accept = extension.accept(offer) if accept is True: ...
Agree on the extensions to use returning an appropriate header value. This returns None if there are no agreed extensions
8,764
def rpc(ctx, call, arguments, api): try: data = list(eval(d) for d in arguments) except: data = arguments ret = getattr(ctx.bitshares.rpc, call)(*data, api=api) print_dict(ret)
Construct RPC call directly \b You can specify which API to send the call to: uptick rpc --api assets You can also specify lists using uptick rpc get_objects "['2.0.0', '2.1.0']"
8,765
def shell_context_processor(self, func: Callable) -> Callable: self.shell_context_processors.append(func) return func
Add a shell context processor. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.shell_context_processor def additional_context(): return context
8,766
def exception(self, message, *args, **kwargs): self.logger.exception(message, *args, **kwargs)
Handle exception
8,767
def analysis_download(self, webid, type, run=None, file=None): if file is None: _file = io.BytesIO() else: _file = file data = { : self.apikey, : webid, : type, : run, } response = self._...
Download a resource for an analysis. E.g. the full report, binaries, screenshots. The full list of resources can be found in our API documentation. When `file` is given, the return value is the filename specified by the server, otherwise it's a tuple of (filename, bytes). Parameters: ...
8,768
def limit(self, limit): if limit is None: raise ValueError("Invalid value for `limit`, must not be `None`") if limit > 200: raise ValueError("Invalid value for `limit`, must be a value less than or equal to `200`") if limit < 1: raise ValueError("Inv...
Sets the limit of this ListEmployeeWagesRequest. Maximum number of Employee Wages to return per page. Can range between 1 and 200. The default is the maximum at 200. :param limit: The limit of this ListEmployeeWagesRequest. :type: int
8,769
def _go_to_line(editor, line): b = editor.application.current_buffer b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)
Move cursor to this line in the current buffer.
8,770
def get_json(self, path: str, params: Dict[str, Any], host: str = , session: Optional[requests.Session] = None, _attempt=1) -> Dict[str, Any]: is_graphql_query = in params and in path sess = session if session else self._session try: self.do_sleep() ...
JSON request to Instagram. :param path: URL, relative to the given domain which defaults to www.instagram.com/ :param params: GET parameters :param host: Domain part of the URL from where to download the requested JSON; defaults to www.instagram.com :param session: Session to use, or No...
8,771
def match_hostname(cert, hostname): if not cert: raise ValueError("empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED") try: host_ip = ipaddress.ip_address(six.text_type...
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing.
8,772
def update_metric_by_name(self, metric_name, metric_type, description=None, custom_properties=None, tags=None, **kwargs): data = {: metric_type.upper(), : description or , : custom_properties or {}, : tags or []} resp...
Create or update a metric object Args: metric_name (string): name of metric type (string): metric type, must be one of 'gauge', 'counter', 'cumulative_counter' description (optional[string]): a description custom_properties (optional[d...
8,773
def write_state_file(self): fh = open(, ) state = {} state[] = self.vpc_id state[] = self.sg_id state[] = self.sn_ids state[] = self.instances state["instanceState"] = self.instance_states fh.write(json.dumps(state, indent=4))
Save information that must persist to a file. We do not want to create a new VPC and new identical security groups, so we save information about them in a file between runs.
8,774
def add_node(self, node, weight=1): self._nodes.add(node) self._weights[node] = weight self._hashring = dict() self._sorted_keys = [] self._build_circle()
Adds node to circle and rebuild it.
8,775
def _append_instruction(self, obj, qargs=None): if isinstance(obj, Instruction): chan = None if obj.name == : chan = SuperOp( np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [...
Update the current Operator by apply an instruction.
8,776
def respond_to_SIGHUP(signal_number, frame, logger=None): global restart restart = True if logger: logger.info() raise KeyboardInterrupt
raise the KeyboardInterrupt which will cause the app to effectively shutdown, closing all it resources. Then, because it sets 'restart' to True, the app will reread all the configuration information, rebuild all of its structures and resources and start running again
8,777
def calc_asymptotic_covariance(hessian, fisher_info_matrix): hess_inv = scipy.linalg.inv(hessian) return np.dot(hess_inv, np.dot(fisher_info_matrix, hess_inv))
Parameters ---------- hessian : 2D ndarray. It should have shape `(num_vars, num_vars)`. It is the matrix of second derivatives of the total loss across the dataset, with respect to each pair of coefficients being estimated. fisher_info_matrix : 2D ndarray. It should have a s...
8,778
def _comparison_functions(cls, partial=False): def prerelease_cmp(a, b): if a and b: return identifier_list_cmp(a, b) elif a: return -1 elif b: return 1 else: r...
Retrieve comparison methods to apply on version components. This is a private API. Args: partial (bool): whether to provide 'partial' or 'strict' matching. Returns: 5-tuple of cmp-like functions.
8,779
def follow(user, obj): follow, created = Follow.objects.get_or_create(user, obj) return follow
Make a user follow an object
8,780
def has_plugin(self, name=None, plugin_type=None): if name is None and plugin_type is None: return len(self.plugins) > 0 return name in self.plugins
Check if the manager has a plugin / plugin(s), either by its name, type, or simply checking if the manager has any plugins registered in it. Utilizing the name argument will check if a plugin with that name exists in the manager. Using both the name and plugin_type arguments will check if a plu...
8,781
def predict(self, X): check_rdd(X, (np.ndarray, sp.spmatrix)) if hasattr(self, ): if isinstance(X, ArrayRDD): X = X.unblock() return X.map(lambda x: self._mllib_model.predict(x)) else: rdd = X.map(lambda X: super(SparkKMeans, self).pre...
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : ArrayRDD containi...
8,782
def initialize(self): if not in self._vim.vars: self._vim.vars[] = self._vim.command()
Sets up initial ensime-vim editor settings.
8,783
def _get_cache(self): if not self._cache: self._cache = get_cache(self.app) return self._cache
Return the cache to use for thundering herd protection, etc.
8,784
def resize(self, size=None): if not self.operation.israw(): return size = size or tty.size(self.operation.stdout) if size is not None: rows, cols = size try: self.operation.resize(height=rows, width=cols) except IOError:...
Resize the container's PTY. If `size` is not None, it must be a tuple of (height,width), otherwise it will be determined by the size of the current TTY.
8,785
def _db_upgrade(self, db_name): current_db_version = self._get_db_version() self._execute(db_schema.functions) for i in range(current_db_version, nipap.__db_version__): self._logger.info("Upgrading DB schema:", i, "to", i+1) upgrade_sql = db_schema.upgrade[i-1] ...
Upgrade nipap database schema
8,786
def transformFromNative(obj): obj.isNative = False obj.value = serializeFields(obj.value, NAME_ORDER) return obj
Replace the Name in obj.value with a string.
8,787
def pivot_pandas_to_excel(soup, show_intermediate_breakdown=False, show_total_breakdown=False): col1col2col3indexcol4sumcol4COL1COL2AllROW1ROW2ALL tables = soup.findAll() for table in tables: table.thead.findChildren()[1].decompose() new_body = Tag(name=) bc = 0 ...
pandas style pivot to excel style pivot formatting for outlook/html This function is meant to be provided to the email functionality as a postprocessor. It expects a jupyter or pandas exported html table of a dataframe with the following index: example: # a single pivot pt1 = pd.pivot_table(data, ...
8,788
def load_plugins(self, plugin_path): self.logger.debug(.format(plugin_path)) plugins = {} plugin_dir = os.path.realpath(plugin_path) sys.path.append(plugin_dir) for f in os.listdir(plugin_dir): if f.endswith(".py"): name = f[:-3] ...
Loads plugins from modules in plugin_path. Looks for the config_name property in each object that's found. If so, adds that to the dictionary with the config_name as the key. config_name should be unique between different plugins. :param plugin_path: Path to load plugins from :return: d...
8,789
def execute_code_block(elem, doc): command = select_executor(elem, doc).split() code = elem.text if in elem.attributes or in elem.classes: code = save_plot(code, elem) command.append(code) if in elem.attributes: for arg in elem.attributes[].split(): command.append...
Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of the command.
8,790
async def subscribe( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, subscribe_field_resolver: GraphQLFieldResolver = None, )...
Create a GraphQL subscription. Implements the "Subscribe" algorithm described in the GraphQL spec. Returns a coroutine object which yields either an AsyncIterator (if successful) or an ExecutionResult (client error). The coroutine will raise an exception if a server error occurs. If the client-pr...
8,791
def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm=, **kwargs): t save configuration commands to startup configuration. If False, save configuration to startup confi...
Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configur...
8,792
def sort_projects( self, workflowTags): self.refresh if not isinstance(workflowTags, list): workflowTagsLists = workflowTags.strip().replace(",", "").replace("@", "") workflowTagsLists = workflowTagsLists.split(" ") else: workf...
*order the projects within this taskpaper object via a list of tags* The order of the tags in the list dictates the order of the sort - first comes first* **Key Arguments:** - ``workflowTags`` -- a string of space/comma seperated tags. **Return:** - ``None`` ...
8,793
def iter_subclasses(class_): ensure_class(class_) classes = set() def descend(class_): subclasses = set(class_.__subclasses__()) - classes classes.update(subclasses) return subclasses result = breadth_first(class_, descend) next(result) return result
Iterate over all the subclasses (and subclasses thereof, etc.) of given class. :param class_: Class to yield the subclasses of :return: Iterable of subclasses, sub-subclasses, etc. of ``class_``
8,794
def get_update_status_brok(self): data = {: self.uuid} self.fill_data_brok_from(data, ) return Brok({: + self.my_type + , : data})
Create an update item brok :return: Brok object :rtype: alignak.Brok
8,795
def knx_to_date(knxdata): if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to date") year = knxdata[2] if year >= 90: year += 1900 else: year += 2000 return date(year, knxdata[1], knxdata[0])
Convert a 3 byte KNX data object to a date
8,796
def bowtie_alignment_plot (self): keys = OrderedDict() keys[] = { : , : } keys[] = { : , : } keys[] = { : , : } config = { : , : , : , : } self.add_section( descripti...
Make the HighCharts HTML to plot the alignment rates
8,797
def _get_path(self, file): dir = self._cache_directory() if not os.path.exists(dir): os.makedirs(dir) return os.path.join(dir, file)
Creates the cache directory if it doesn't already exist. Returns the full path to the specified file inside the cache directory.
8,798
def decompressBWT(inputDir, outputDir, numProcs, logger): s original form. While unusual to do, itt care @param numProcs - number of processes we msbwt = MultiStringBWT.CompressedMSBWT() msbwt.loadMsbwt(inputDir, logger) outputFile = np.lib.format.open_memmap(outputDir+, , , (msb...
This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do, it's included in this package for completion purposes. @param inputDir - the directory of the compressed BWT we plan on decompressing @param outputFN - the directory for the output decompressed BWT, it...
8,799
def set_scan_option(self, scan_id, name, value): return self.scan_collection.set_option(scan_id, name, value)
Sets a scan's option to a provided value.