text
stringlengths
78
104k
score
float64
0
0.18
def virtual_resource(self): """ Available on a Master Engine only. To get all virtual resources call:: engine.virtual_resource.all() :raises UnsupportedEngineFeature: master engine only :rtype: CreateCollection(VirtualResource) """ resource = create...
0.003591
def convert_optional_traversals_to_compound_match_query( match_query, complex_optional_roots, location_to_optional_roots): """Return 2^n distinct MatchQuery objects in a CompoundMatchQuery. Given a MatchQuery containing `n` optional traverses that expand vertex fields, construct `2^n` different Mat...
0.003581
def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb...
0.003953
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param str...
0.002518
def parse_response(response, return_type): ''' Parse the HTTPResponse's body and fill all the data into a class of return_type. ''' doc = minidom.parseString(response.body) return_obj = return_type() xml_name = return_type._xml_name if hasattr(return_type, '_xml_n...
0.007561
def pipeline_exists(url, pipeline_id, auth, verify_ssl): ''' :param url: (str): the host url in the form 'http://host:port/'. :param pipeline_id: (string) the pipeline identifier :param auth: (tuple) a tuple of username, password :return: (boolean) ''' try: pipeline_status(url, pipel...
0.002342
def require_Gtk(min_version=2): """ Make sure Gtk is properly initialized. :raises RuntimeError: if Gtk can not be properly initialized """ if not _in_X: raise RuntimeError('Not in X session.') if _has_Gtk < min_version: raise RuntimeError('Module gi.repository.Gtk not available...
0.001271
def keep_color(ax=None): ''' Keep the same color for the same graph. Warning: due to the structure of Python iterators I couldn't help but iterate over all the cycle twice. One first time to get the number of elements in the cycle, one second time to stop just before the last. And this still only ...
0.004662
def recompile_all(path): """recursively recompile all .py files in the directory""" import os if os.path.isdir(path): for root, dirs, files in os.walk(path): for name in files: if name.endswith('.py'): filename = os.path.abspath(os.path.join(root, name...
0.002037
def diamond_functions(xx, yy, y_x0, x_y0): """ Method that creates two upper and lower functions based on points xx and yy as well as intercepts defined by y_x0 and x_y0. The resulting functions form kind of a distorted diamond-like structure aligned from point xx to point yy. Schematically : ...
0.005739
def make_cutout(self, data, masked_array=False): """ Create a (masked) cutout array from the input ``data`` using the minimal bounding box of the segment (labeled region). If ``masked_array`` is `False` (default), then the returned cutout array is simply a `~numpy.ndarray`. The...
0.001112
def _value_encode(cls, member, value): """ Internal method used to encode values into the hash. :param member: str :param value: multi :return: bytes """ try: field_validator = cls.fields[member] except KeyError: return cls.valuepa...
0.005222
def _unique_key(job): """Return a key to query our uniqueness mapping system. This makes sure that we use a consistent key between our code and selecting jobs from the table. """ return unique_key(testtype=str(job['testtype']), buildtype=str(job['platform_option']), ...
0.005525
def _get_rsi(cls, df, n_days): """ Calculate the RSI (Relative Strength Index) within N days calculated based on the formula at: https://en.wikipedia.org/wiki/Relative_strength_index :param df: data :param n_days: N days :return: None """ n_day...
0.002002
def as_dict(self): """ Json-serializable dict representation. """ d = {"vasp_version": self.vasp_version, "has_vasp_completed": True, "nsites": len(self.final_structure)} comp = self.final_structure.composition d["unit_cell_formula"] = comp.as_di...
0.000745
def get_checker_names(self): """Get all the checker names that this linter knows about.""" current_checkers = self.get_checkers() return sorted( {check.name for check in current_checkers if check.name != "master"} )
0.011583
def on_comment_posted(sender, comment, request, **kwargs): """ Send email notification of a new comment to site staff when email notifications have been requested. """ content_object = comment.content_object moderator = moderation.get_model_moderator(content_object.__class__) if moderator is No...
0.00361
def _login(self, username="", password=""): """Login to the Server using username/password, empty parameters means an anonymously login Returns True if login sucessful, and False if not. """ self.log.debug("----------------") self.log.debug("Logging in (username: %s)..." ...
0.001848
def _ParseLogLine(self, parser_mediator, structure, key): """Parse a single log line and produce an event object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the structure of tokens...
0.003628
def compile_default_action(self, batch_size: Optional[int] = None) -> Sequence[tf.Tensor]: '''Returns a tuple of tensors representing the default action fluents. Args: batch_size (int): The batch size. Returns: Sequence[tf.Tensor]: A tuple of tensors. ''' ...
0.006202
def ObjectTransitionedEventHandler(obj, event): """Object has been transitioned to an new state """ # only snapshot supported objects if not supports_snapshots(obj): return # default transition entry entry = { "modified": DateTime().ISO(), "action": event.action, } ...
0.001305
def put(self, entity): """Adds an entity to be committed. Ensures the transaction is not marked readonly. Please see documentation at :meth:`~google.cloud.datastore.batch.Batch.put` :type entity: :class:`~google.cloud.datastore.entity.Entity` :param entity: the entity t...
0.003289
def create_store(url, **kw): '''Create a new :class:`Store` for a valid ``url``. :param url: a valid ``url`` takes the following forms: :ref:`Pulsar datastore <store_pulsar>`:: pulsar://user:password@127.0.0.1:6410 :ref:`Redis <store_redis>`:: redis://user:password@1...
0.000787
def post_file(self, uri, body, files, **kwargs): """POST a file""" # requests doesn't actually need us to open the files but we do anyway because # if we don't then the filename isn't preserved, so we assume each string # value is a filepath for key in files.keys(): i...
0.006173
def Refresh(self, location=None): """Reloads the network object to synchronize with cloud representation. >>> clc.v2.Network("f58148729bd94b02ae8b652f5c5feba3").Refresh() GET https://api.ctl.io/v2-experimental/networks/{accountAlias}/{dataCenter}/{Network}?ipAddresses=none|claimed|free|all """ if not locati...
0.028716
def facettupletrees(table, key, start='start', stop='stop', value=None): """ Construct faceted interval trees for the given table, where each node in the tree is a row of the table. """ import intervaltree it = iter(table) hdr = next(it) flds = list(map(text_type, hdr)) assert star...
0.000939
def refitMappings(self): """ Refit (normalize) all of the nsprefix mappings. """ for n in self.branch: n.nsprefixes = {} n = self.node for u, p in self.prefixes.items(): n.addPrefix(p, u)
0.007722
def split_data(iterable, pred): """ Split data from ``iterable`` into two lists. Each element is passed to function ``pred``; elements for which ``pred`` returns True are put into ``yes`` list, other elements are put into ``no`` list. >>> split_data(["foo", "Bar", "Spam", "egg"], lambda t: t.is...
0.001916
def hover(self, locator, params=None, use_js=False, alt_loc=None, alt_params=None): """ Context manager for hovering. Opens and closes the hover. Usage: with self.hover(locator, params): // do something with the hover :param locator: locator tuple o...
0.003956
def loads( s, record_store=None, schema=None, loader=from_json_compatible, record_class=None # deprecated in favor of schema ): """ Create a Record instance from a json serialized dictionary :param s: String with a json-serialized dictionary :param record_s...
0.001622
def WriteGraphSeries(graph_series, label, token = None): """Writes graph series for a particular client label to the DB. Args: graph_series: A series of rdf_stats.Graphs containing aggregated data for a particular report-type. label: Client label by which dat...
0.007752
def validate_widget(widget): """Checks that the given widget contains the required fields""" if not has_valid_id(widget): raise InvalidWidget("%s must contain a valid 'id' attribute" % widget.__name__) if not has_valid_name(widget): raise InvalidWidget("%s must contain a valid 'name' attri...
0.007937
def uuid1mc_from_datetime(dt): """ Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled con...
0.00135
def state_province_region(self, value=None): """Corresponds to IDD Field `state_province_region` Args: value (str): value for IDD Field `state_province_region` if `value` is None it will not be checked against the specification and is assumed to be a missing ...
0.00223
def _with_primary(max_staleness, selection): """Apply max_staleness, in seconds, to a Selection with a known primary.""" primary = selection.primary sds = [] for s in selection.server_descriptions: if s.server_type == SERVER_TYPE.RSSecondary: # See max-staleness.rst for explanation ...
0.001418
def Min(a, axis, keep_dims): """ Min reduction op. """ return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
0.010417
def _get_num_cpus(): """Return the number of CPUs on the system""" # we try to determine num CPUs by using different approaches. # SC_NPROCESSORS_ONLN seems to be the safer and it is also # used by multiprocessing module try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: ...
0.001686
def get_repository_admin_session(self): """Gets the repository administrative session for creating, updating and deleteing repositories. return: (osid.repository.RepositoryAdminSession) - a ``RepositoryAdminSession`` raise: OperationFailed - unable to complete request r...
0.004087
def get_case_groups(adapter, total_cases, institute_id=None, slice_query=None): """Return the information about case groups Args: store(adapter.MongoAdapter) total_cases(int): Total number of cases slice_query(str): Query to filter cases to obtain statistics for. Returns: c...
0.002195
def upload(self, engine, timeout=5, wait_for_finish=False, **kw): """ Upload policy to specific device. Using wait for finish returns a poller thread for monitoring progress:: policy = FirewallPolicy('_NSX_Master_Default') poller = policy.upload('myfirewall', wait_for_fi...
0.003836
def collapse(self, dimensions=None, function=None, spreadfn=None, **kwargs): """Concatenates and aggregates along supplied dimensions Useful to collapse stacks of objects into a single object, e.g. to average a stack of Images or Curves. Args: dimensions: Dimension(s) to co...
0.001943
def create(self, friendly_name, activity_sid=values.unset, attributes=values.unset): """ Create a new WorkerInstance :param unicode friendly_name: String representing user-friendly name for the Worker. :param unicode activity_sid: A valid Activity describing the worker's ...
0.006522
def basekey(self, meta, *args): """Calculate the key to access model data. :parameter meta: a :class:`stdnet.odm.Metaclass`. :parameter args: optional list of strings to prepend to the basekey. :rtype: a native string """ key = '%s%s' % (self.namespace, meta.modelkey) postfix = ':'.join...
0.004739
def open(self): """Implementation of NAPALM method open.""" try: connection = self.transport_class( host=self.hostname, username=self.username, password=self.password, timeout=self.timeout, **self.eapi_kwargs ...
0.003337
def from_dict(self, mapdict): """ Import the attribute map from a dictionary :param mapdict: The dictionary """ self.name_format = mapdict["identifier"] try: self._fro = dict( [(k.lower(), v) for k, v in mapdict["fro"].items()]) except KeyEr...
0.003012
def line(self, value): """The line property. Args: value (int). the property value. """ if value == self._defaults['line'] and 'line' in self._values: del self._values['line'] else: self._values['line'] = value
0.010169
def chat_unfurl( self, *, channel: str, ts: str, unfurls: dict, **kwargs ) -> SlackResponse: """Provide custom unfurl behavior for user-posted URLs. Args: channel (str): The Channel ID of the message. e.g. 'C1234567890' ts (str): Timestamp of the message to add unfur...
0.008487
def render_registered(url_id, remote_info): """ Render template file for the registered user, which has some of the values prefilled. Args: url_id (str): Seeder URL id. remote_info (dict): Informations read from Seeder. Returns: str: Template filled with data. """ r...
0.002012
def get_program_course_keys(self, program_uuid): """ Get a list of the course IDs (not course run IDs) contained in the program. Arguments: program_uuid (str): Program UUID in string form Returns: list(str): List of course keys in string form that are included i...
0.007339
def set_value(self, value): """Set the value in the cache for this query.""" cache, cache_key = self._get_cache_plus_key() cache.set(cache_key, value)
0.011494
def cli(ctx, collections, threads, debug): """ A configurable data and document processing tool. """ ctx.obj = { 'collections': collections, 'debug': debug, 'threads': threads } if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level...
0.002994
def get_all_tags_with_auth(image_name, branch=None): """ Get the tag information using authentication credentials provided by the user. :param image_name: The image name to query :param branch: The branch to filter by :return: A list of Version instances, latest first """ logging.debug(...
0.000282
def start( self, target=None, args=None, kwargs=None, advices=None, exec_ctx=None, ctx=None ): """ Start to proceed this Joinpoint in initializing target, its arguments and advices. Call self.proceed at the end. :param callable target: new target to use in proceeding...
0.00177
def fetch(self): """Fetch the data for the model from Redis and assign the values. :rtype: bool """ raw = yield gen.Task(self._redis_client.get, self._key) if raw: self.loads(base64.b64decode(raw)) raise gen.Return(True) raise gen.Return(False)
0.006289
def task_wait_with_io( meow, heartbeat, polling_interval, timeout, task_id, timeout_exit_code, client=None ): """ Options are the core "task wait" options, including the `--meow` easter egg. This does the core "task wait" loop, including all of the IO. It *does exit* on behalf of the caller. (W...
0.00114
def data_filler_user_agent(self, number_of_rows, conn): '''creates and fills the table with user agent data ''' cursor = conn.cursor() cursor.execute(''' CREATE TABLE user_agent(id TEXT PRIMARY KEY, ip TEXT, countrycode TEXT, useragent TEXT) ''') conn.com...
0.008009
def read_in_config(self): """Vyper will discover and load the configuration file from disk and key/value stores, searching in one of the defined paths. """ log.info("Attempting to read in config file") if self._get_config_type() not in constants.SUPPORTED_EXTENSIONS: ...
0.003697
def execute(self, sensor_graph, scope_stack): """Execute this statement on the sensor_graph given the current scope tree. This adds a single DataStreamer to the current sensor graph Args: sensor_graph (SensorGraph): The sensor graph that we are building or modifying...
0.008746
def GenerateBand(self, band, meta_only=False, cast=False): """Genreate a Band object given band metadata Args: band (dict): dictionary containing metadata for a given band Return: Band : the loaded Band onject""" # Read the band data and add it to dictionary ...
0.005419
def _get_data_info(self, data, file_format): """Support file writing by determiniing data type and other options Parameters ---------- data : pandas object Data to be written file_format : basestring String indicating netCDF3 or netCDF4 Returns ...
0.002818
def fileinfo(path): ''' Return information on a file located on the Moose CLI Example: .. code-block:: bash salt '*' moosefs.fileinfo /path/to/dir/ ''' cmd = 'mfsfileinfo ' + path ret = {} chunknum = '' out = __salt__['cmd.run_all'](cmd, python_shell=False) output = o...
0.000818
def _get_function_name_from_arn(function_arn): """ Given the integration ARN, extract the Lambda function name from the ARN. If there are stage variables, or other unsupported formats, this function will return None. Parameters ---------- function_arn : basestring or Non...
0.005542
def alpha_beta_aligned(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None, out=None): """Calculates annualized alpha and beta. If they are pd.Series, expects returns and fact...
0.000491
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: TaskStatisticsContext for this TaskStatisticsInstance :rtype: twilio.rest.autopilot.v1.assistant....
0.007704
def authorize_ip_permission( self, group_name, ip_protocol, from_port, to_port, cidr_ip): """ This is a convenience function that wraps the "authorize ip permission" functionality of the C{authorize_security_group} method. For an explanation of the parameters, see C{authorize_se...
0.003745
def weblogo(args): """ %prog weblogo [fastafile|fastqfile] Extract base composition for reads """ import numpy as np from jcvi.utils.progressbar import ProgressBar, Percentage, Bar, ETA p = OptionParser(weblogo.__doc__) p.add_option("-N", default=10, type="int", help="...
0.0004
def __get_variance_increase_distance(self, entry): """! @brief Calculates variance increase distance between current and specified clusters. @param[in] entry (cfentry): Clustering feature to which distance should be obtained. @return (double) Variance increase dis...
0.01958
def get_widgets_sorted(self): """Returns the widgets sorted by position.""" result = [] for widget_name, widget in self.get_widgets().items(): result.append((widget_name, widget, widget.position)) result.sort(key=lambda x: x[2]) return result
0.006803
def join_impl(other, join_type, sequence): """ Implementation for join_t :param other: other sequence to join with :param join_type: join type (inner, outer, left, right) :param sequence: first sequence to join with :return: joined sequence """ if join_type == "inner": return inn...
0.001126
def description(cls): """Get a description from the Notes section of the docstring.""" lines = [s.strip() for s in cls.__doc__.splitlines()] note_i = lines.index("Notes") return "\n".join(lines[note_i + 2:])
0.008368
def load_folder_content(folder_path): """ load api/testcases/testsuites definitions from folder. Args: folder_path (str): api/testcases/testsuites files folder. Returns: dict: api definition mapping. { "tests/api/basic.yml": [ {"api": {"def"...
0.004622
def get(self, block=True, timeout=None): '''Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raise...
0.001293
def process_expt(h5_path, inmemory = True, ignorenan = False): """ Assumes h5 file has table called `F_measure` Parameters ---------- h5_path : string path to HDF file containing the experimental data. The file is expected to have been generated from the `repeat_expt` function. ...
0.005307
def load_plugins(builtin=True, others=True): """Load plugins, either builtin, others, or both. """ for entry_point in pkg_resources.iter_entry_points('yolk.plugins'): #LOG.debug("load plugin %s" % entry_point) try: plugin = entry_point.load() except KeyboardInterrupt: ...
0.004981
def updateFGDBfromSDE(fgdb, sde, logger=None): global changes """ fgdb: file geodatabase sde: sde geodatabase connection logger: agrc.logging.Logger (optional) returns: String[] - the list of errors Loops through the file geodatabase feature classes and looks for matches in the SDE dat...
0.001596
def lineage(self, tax_id=None, tax_name=None): """Public method for returning a lineage; includes tax_name and rank """ if not bool(tax_id) ^ bool(tax_name): msg = 'Exactly one of tax_id and tax_name may be provided.' raise ValueError(msg) if tax_name: ...
0.003067
def _check_package(pkg_xml, zipfilename, zf): """ Helper for ``build_index()``: Perform some checks to make sure that the given package is consistent. """ # The filename must patch the id given in the XML file. uid = os.path.splitext(os.path.split(zipfilename)[1])[0] if pkg_xml.get('id') != uid: raise...
0.020649
def has_column_at_position(self, column_name, pos=0): """ :type column_name: str :type pos: int :rtype: bool """ column_name = self._trim_quotes(column_name.lower()) index_columns = [c.lower() for c in self.get_unquoted_columns()] return index_columns.in...
0.005831
def send_video(chat_id, video, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). :param chat_id: Unique identifier for the m...
0.006757
def get(self, name, defval=None): ''' Retrieve a value from the closest scope frame. ''' for frame in reversed(self.frames): valu = frame.get(name, s_common.novalu) if valu != s_common.novalu: return valu task = self.ctors.get(name) ...
0.003929
def render_badge(user): ''' Renders a single user's badge. ''' data = { "user": user, } t = loader.get_template('registrasion/badge.svg') return t.render(data)
0.005291
def append(self,*args,toSection=None,**kwargs): """Append a new section If toSection is None, section is appended to the main section/subs list. Else if toSection is int or (int,int,...), it gets added to the subs (subsection) list of the specified section. *args* and *kwargs* a...
0.015094
def compile_settings(model_path, file_path, ignore_errors=False): ''' a method to compile configuration values from different sources NOTE: method searches the environment variables, a local configuration path and the default values for a jsonmodel object for valid ...
0.002209
def get_user_activity(self, offset=None, limit=None): """Get activity about the user's lifetime activity with Uber. Parameters offset (int) The integer offset for activity results. Default is 0. limit (int) Integer amount of results to return. Max...
0.003215
def add_simple_formatter(self, tag_name, format_string, **kwargs): """ Installs a formatter that takes the tag options dictionary, puts a value key in it, and uses it as a format dictionary to the given format string. """ def _render(name, value, options, parent, context): ...
0.00566
def makePlot(args): """ Make the plot with proper motion performance predictions. The predictions are for the TOTAL proper motion under the assumption of equal components mu_alpha* and mu_delta. :argument args: command line arguments """ gmag=np.linspace(5.7,20.0,101) vminiB1V=vminiFromSpt('B1V') vmin...
0.027563
def safe_re_encode(s, encoding_to, errors="backslashreplace"): """Re-encode str or binary so that is compatible with a given encoding (replacing unsupported chars). We use ASCII as default, which gives us some output that contains \x99 and \u9999 for every character > 127, for easier debugging. (e....
0.004255
async def consume_events(self): ''' begin listening to messages that were entered after starting''' # begin by making sure the channel is created await self.create_channel() # get cursor method def create_cursor(): now = datetime.datetime.utcnow() dummy_id...
0.004566
def _loadColumns(self, record, columnName, value): """ Loads the column information for this tree widget for the given record. :param record | <orb.Table> columnName | <str> value | <variant> """ value = un...
0.005236
def _set_system_utilization(self, v, load=False): """ Setter method for system_utilization, mapped from YANG variable /telemetry/profile/system_utilization (list) If this variable is read-only (config: false) in the source YANG file, then _set_system_utilization is considered as a private method. Ba...
0.00428
def extras_msg(extras): """ Create an error message for extra items or properties. """ if len(extras) == 1: verb = "was" else: verb = "were" return ", ".join(repr(extra) for extra in extras), verb
0.004202
def ProcessSources( self, source_path_specs, storage_writer, resolver_context, processing_configuration, filter_find_specs=None, status_update_callback=None): """Processes the sources. Args: source_path_specs (list[dfvfs.PathSpec]): path specifications of the sources to proces...
0.004795
def s_find_first(pred, first, lst): """Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :return: the first element ...
0.002016
def notify(self, message, duration=3000, notification_clicked_slot=None, message_level="Information", **kwargs): """ Displays an Application notification. :param message: Notification message. :type message: unicode :param duration: Notification display duration. :type d...
0.006718
def close(self): """Closes the record file.""" if not self.is_open: return super(MXIndexedRecordIO, self).close() self.fidx.close()
0.011429
def close(self): """ Close outputs of process. """ self.process.stdout.close() self.process.stderr.close() self.running = False
0.011429
def exit(self): """Close the socket and context""" if self.client is not None: self.client.close() if self.context is not None: self.context.destroy()
0.010101
def write_blockdata(self, x, z, data, compression=COMPRESSION_ZLIB): """ Compress the data, write it to file, and add pointers in the header so it can be found as chunk(x,z). """ if compression == COMPRESSION_GZIP: # Python 3.1 and earlier do not yet support `data = ...
0.005565
def get_version_relationship(ver_str1, ver_str2): """ Comparison of alpine package version numbers. Roughly based on the C code from github.com/apk-tools/version.c but in pure python. :param ver_str1: :param ver_str2: :return: """ # Expect first type to be a digit, per Gentoo spec (used by...
0.002349
def _setup_dmtf_schema(self): """ Install the DMTF CIM schema from the DMTF web site if it is not already installed. This includes downloading the DMTF CIM schema zip file from the DMTF web site and expanding that file into a subdirectory defined by `schema_mof_dir`. Onc...
0.00056