text
stringlengths
78
104k
score
float64
0
0.18
def remove_service(self, service): """Removes the service passed in from the services offered by the current Profile. If the Analysis Service passed in is not assigned to this Analysis Profile, returns False. :param service: the service to be removed from this Analysis Profile :t...
0.00199
def create_node(xml_node: XmlNode, **init_args): '''Creates node from xml node using namespace as module and tag name as class name''' inst_type = get_inst_type(xml_node) init_args['xml_node'] = xml_node inst = create_inst(inst_type, **init_args) if not isinstance(inst, Node): inst = convert...
0.00551
def _query_iterator(cursor, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None): """Return generator through chunked result set""" while True: data = cursor.fetchmany(chunksize) if type(data) == tuple: data = list(data...
0.004918
def resteem(self, identifier): ''' Waits 20 seconds as that is the required amount of time between resteems ''' for num_of_retries in range(default.max_retry): try: self.steem_instance().resteem( identifier, self.mainaccount) ...
0.007236
def _find_volume(name): ''' Find volume by name on minion ''' docker_volumes = __salt__['docker.volumes']()['Volumes'] if docker_volumes: volumes = [v for v in docker_volumes if v['Name'] == name] if volumes: return volumes[0] return None
0.003436
def scp_put(files, remote_path=None, recursive=False, preserve_times=False, saltenv='base', **kwargs): ''' .. versionadded:: 2019.2.0 Transfer files and directories to remote network device. .. note:: This function is only available o...
0.000697
async def ensure_process(self): """ Start the process """ # We don't want multiple requests trying to start the process at the same time # FIXME: Make sure this times out properly? # Invariant here should be: when lock isn't being held, either 'proc' is in state & ...
0.005556
def on_pytoml_dumps(self, pytoml, config, dictionary, **kwargs): """ The `pytoml <https://pypi.org/project/pytoml/>`_ dumps method. :param module pytoml: The ``pytoml`` module :param class config: The instance's config class :param dict dictionary: The dictionary to serialize :r...
0.00335
def split_bits(value, *bits): """ Split integer value into list of ints, according to `bits` list. For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4] """ result = [] for b in reversed(bits): mask = (1 << b) - 1 result.append(value & mask) value = value >> b ...
0.002646
def clear_doc(self, docname): """Remove the data associated with this instance of the domain.""" for fullname, (fn, x) in self.data['objects'].items(): if fn == docname: del self.data['objects'][fullname] for modname, (fn, x, x, x) in self.data['modules'].items(): ...
0.002845
def _init_browser(self): """Open harness web page. Open a quiet chrome which: 1. disables extensions, 2. ignore certificate errors and 3. always allow notifications. """ chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--disable-ext...
0.002075
def OMDict(self, items): """ Convert a dictionary (or list of items thereof) of OM objects into an OM object EXAMPLES:: >>> from openmath import openmath as om >>> from openmath.convert_pickle import PickleConverter >>> converter = PickleConverter() ...
0.006168
def list_evaluation_functions(kind=None): """Get valid word embedding functions names. Parameters ---------- kind : ['similarity', 'analogy', None] Return only valid names for similarity, analogy or both kinds of functions. Returns ------- dict or list: A list of all the va...
0.001715
def diff_dir(dir_cmp, left_path=True): """ A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works recursively. :param dir_cmp: A ``filecmp.dircmp`` object representing the comparison. :param left_path: If ``True``, paths will be relative to dirc...
0.005006
def get_headers(self, instant): """ Build the list of headers needed in order to perform S3 operations. """ headers = {'x-amz-date': _auth_v4.makeAMZDate(instant)} if self.body_producer is None: data = self.data if data is None: data = b"" ...
0.0016
def usable_service(self): """Return a usable service or None if there is none. A service is usable if enough configuration to be able to make a connection is available. If several protocols are usable, MRP will be preferred over DMAP. """ services = self._services ...
0.004008
def _map_arg(arg): """ Return `arg` appropriately parsed or mapped to a usable value. """ # Grab the easy to parse values if isinstance(arg, _ast.Str): return repr(arg.s) elif isinstance(arg, _ast.Num): return arg.n elif isinstance(arg, _ast.Name): name = arg.id ...
0.001724
def to_dict(self): """Return all the details of this MLPipeline in a dict. The dict structure contains all the `__init__` arguments of the MLPipeline, as well as the current hyperparameter values and the specification of the tunable_hyperparameters:: { "prim...
0.001117
def fit(self, X, y=None): """ Fit the clustering model, computing the centers then embeds the centers into 2D space using the embedding method specified. """ with Timer() as self.fit_time_: # Fit the underlying estimator self.estimator.fit(X, y) ...
0.00271
def get_loglevel(level): """ Set log level. >>> assert get_loglevel(2) == logging.WARN >>> assert get_loglevel(10) == logging.INFO """ try: return [logging.DEBUG, logging.INFO, logging.WARN][level] except IndexError: return logging.INFO
0.003559
def on_message(self, message): """Evaluates the function pointed to by json-rpc.""" json_rpc = json.loads(message) logging.log(logging.DEBUG, json_rpc) if self.pool is None: self.pool = multiprocessing.Pool(processes=args.workers) # Spawn a process to protect the se...
0.0033
def create_output_directories(self): """Create output directories for thumbnails and original images.""" check_or_create_dir(self.dst_path) if self.medias: check_or_create_dir(join(self.dst_path, self.settings['thumb_dir'])) if self.medi...
0.004184
def as_machine(self): """Convert to a `Machine` object. `node_type` must be `NodeType.MACHINE`. """ if self.node_type != NodeType.MACHINE: raise ValueError( 'Cannot convert to `Machine`, node_type is not a machine.') return self._origin.Machine(self._...
0.006154
def render(self, cli, layout, is_done=False): """ Render the current interface to the output. :param is_done: When True, put the cursor at the end of the interface. We won't print any changes to this part. """ output = self.output # Enter alternate scree...
0.001656
def in_tree(self, cmd_args): """ if a command is in the tree """ if not cmd_args: return True tree = self try: for datum in cmd_args: tree = tree.get_child(datum) except ValueError: return False return True
0.006536
def Uri(self): """ Constructs the connection URI from name, noSsl and port instance variables. """ return ("%s://%s%s" % (("https", "http")[self._noSsl == True], self._name, (":" + str(self._port), "")[ (((self._noSsl == False) and (self._port == 80)) or ((self._noSsl == True) and (self._port == 443)))]))
0.035144
def simplex_remove_arc(self, t, p, q, min_capacity, cycle): ''' API: simplex_remove_arc(self, p, q, min_capacity, cycle) Description: Removes arc (p,q), updates t, updates flows, where (k,l) is the entering arc. Input: t: tree solution to b...
0.004398
def get_first_property(elt, key, default=None, ctx=None): """Get first property related to one input key. :param elt: first property elt. Not None methods. :param str key: property key to get. :param default: default value to return if key does not exist in elt. properties :param ctx: elt c...
0.001379
def encode_network(root): """Yield ref-containing obj table entries from object network""" def fix_values(obj): if isinstance(obj, Container): obj.update((k, get_ref(v)) for (k, v) in obj.items() if k != 'class_name') fixed_obj = obj ...
0.001605
def predict(self, h=5, intervals=False, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? intervals : boolean (default: False) Whether to return predi...
0.009812
def set_exception(self, exception): """Set the result of the future to the given exception. Args: exception (:exc:`Exception`): The exception raised. """ # Sanity check: A future can only complete once. if self.done(): raise RuntimeError("set_exception ca...
0.004376
def _project_perturbation(perturbation, epsilon, input_image, clip_min=None, clip_max=None): """Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable. """ ...
0.004789
def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None: """Call the given callback when the stream is closed. This mostly is not necessary for applications that use the `.Future` interface; all outstanding ``Futures`` will resolve with a `StreamClosedError` when th...
0.002924
def fraction_correct_pandas(dataframe, x_series, y_series, x_cutoff = 1.0, y_cutoff = 1.0, ignore_null_values = False): '''A little (<6%) slower than fraction_correct due to the data extraction overhead.''' return fraction_correct(dataframe[x_series].values.tolist(), dataframe[y_series].values.tolist(), x_cutof...
0.040506
def delete(self, request, bot_id, id, format=None): """ Delete existing state --- responseMessages: - code: 401 message: Not authenticated """ return super(StateDetail, self).delete(request, bot_id, id, format)
0.007042
def _validate_changeset(self, changeset_id: uuid.UUID) -> None: """ Checks to be sure the changeset is known by the journal """ if not self.journal.has_changeset(changeset_id): raise ValidationError("Changeset not found in journal: {0}".format( str(changeset_i...
0.005935
def generateAPIRootBody(self): ''' Generates the root library api file's body text. The method calls :func:`~exhale.graph.ExhaleRoot.gerrymanderNodeFilenames` first to enable proper internal linkage between reStructuredText documents. Afterward, it calls :func:`~exhale.graph.Ex...
0.004789
def sentence_starts(self): """The list of start positions representing ``sentences`` layer elements.""" if not self.is_tagged(SENTENCES): self.tokenize_sentences() return self.starts(SENTENCES)
0.0131
def _parse_leaves(self, leaves) -> List[Tuple[str, int]]: """Returns a list of pairs (leaf_name, distance)""" return [(self._leaf_name(leaf), 0) for leaf in leaves]
0.011111
def cumsum(item_list, initial=0): """ python cumsum Args: item_list (list): list of numbers or items supporting addition initial (value): initial zero value Returns: list: list of accumulated values References: stackoverflow.com/questions/9258602/elegant-pythonic-cumsu...
0.000949
def attach_temporary_file(self, service_desk_id, filename): """ Create temporary attachment, which can later be converted into permanent attachment :param service_desk_id: str :param filename: str :return: Temporary Attachment ID """ headers = {'X-Atlassian-Token...
0.008357
def _minimize_neldermead( func, x0, args=(), callback=None, xtol=1e-4, ftol=1e-4, maxiter=None, maxfev=None, disp=False, return_all=False, ): # pragma: no cover """ Minimization of scalar function of one or more variables using the Nelder-Mead algorithm. Options...
0.000207
def delete(filething): """Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError """ dsf_file = DSFFile(filething.fileobj) if dsf_file.dsd_chunk.offset_metdata_chunk != 0: id3_location = dsf_file.dsd_chunk.offset_metdata_chunk dsf_fil...
0.00211
def _check_view_permission(self, view): """ :param view: a :class:`ObjectView` class or instance """ security = get_service("security") return security.has_permission(current_user, view.permission, self.obj)
0.008097
def add_data(self, *args): """Add data to signer""" for data in args: self._data.append(to_binary(data))
0.015152
def line(self, x1,y1,x2,y2): "Draw a line" self._out(sprintf('%.2f %.2f m %.2f %.2f l S',x1*self.k,(self.h-y1)*self.k,x2*self.k,(self.h-y2)*self.k))
0.060976
def imag(self): """Imaginary part""" return self.__class__.create(self.term.imag, *self.ranges)
0.018018
def calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args: locator1 (string): Maidenhead Locator, either 4 or 6 characters calc_date (datetime, optional): Starting datetime for th...
0.003323
def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z**2 wPart = np.exp(self.w) q = Quaternion() # Calculate q.w = wPart * np.cos(vecNorm) q.x ...
0.013889
def _get_self_bounds(self): """ Computes the bounds of the object itself (not including it's children) in the form [[lat_min, lon_min], [lat_max, lon_max]]. """ if not self.embed: raise ValueError('Cannot compute bounds of non-embedded GeoJSON.') data = json...
0.001526
def Lexicon(**rules): """Create a dictionary mapping symbols to alternative words. >>> Lexicon(Art = "the | a | an") {'Art': ['the', 'a', 'an']} """ for (lhs, rhs) in rules.items(): rules[lhs] = [word.strip() for word in rhs.split('|')] return rules
0.003559
def call_command(self, cmd, *argv): """ Runs a command. :param cmd: command to run (key at the registry) :param argv: arguments that would be passed to the command """ parser = self.get_parser() args = [cmd] + list(argv) namespace = parser.parse_args(args...
0.005602
def mavfmt(field): '''work out the struct format for a type''' map = { 'float' : 'f', 'double' : 'd', 'char' : 'c', 'int8_t' : 'b', 'uint8_t' : 'B', 'uint8_t_mavlink_version' : 'B', 'int16_t' : 'h', 'uint16_t' : 'H', 'int32_t'...
0.020668
def _parse_day(optval): ''' Parse a --day argument ''' isreq = not optval.startswith('+') if not isreq: optval = optval[1:] try: retnval = [] unit = None for val in optval.split(','): if not val: raise V...
0.001595
def import_transcript_from_fs(edx_video_id, language_code, file_name, provider, resource_fs, static_dir): """ Imports transcript file from file system and creates transcript record in DS. Arguments: edx_video_id (str): Video id of the video. language_code (unicode): Language code of the req...
0.003185
def find_closest_in_list(number, array, direction="both", strictly=False): """ Find the closest number in the array from x. Parameters ---------- number : float The number. array : list The list to look in. direction : str "both" for smaller or greater, "greater" for...
0.002326
def _add_none_handler(validation_callable, # type: Callable none_policy # type: int ): # type: (...) -> Callable """ Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy :param validation_callable: ...
0.003432
def _relativeize(self, filename): """Return the portion of a filename that is 'relative' to the directories in this lookup. """ filename = posixpath.normpath(filename) for dir in self.directories: if filename[0:len(dir)] == dir: return filename[le...
0.005464
def every(self, step, offset=0): """ Create a new collection consisting of every n-th element. :param step: The step size :type step: int :param offset: The start offset :type offset: int :rtype: Collection """ new = [] for position, it...
0.004357
def _indirect_jump_unresolved(self, jump): """ Called when we cannot resolve an indirect jump. :param IndirectJump jump: The unresolved indirect jump. :return: None """ # add a node from this node to UnresolvableJumpTarget or UnresolvalbeCallTarget node, # d...
0.002973
def short_key(): """ Generate a short key. >>> key = short_key() >>> len(key) 5 """ firstlast = list(ascii_letters + digits) middle = firstlast + list('-_') return ''.join(( choice(firstlast), choice(middle), choice(middle), choice(middle), choice(firstlast), ))
0.003135
def critical(self, message, *args, **kwargs): """Log critical event. Compatible with logging.critical signature. """ self.system.critical(message, *args, **kwargs)
0.010204
def get_project_details(project): """ Get details for this user. """ result = [] for datastore in _get_datastores(): value = datastore.get_project_details(project) value['datastore'] = datastore.config['DESCRIPTION'] result.append(value) return result
0.003436
def make_heading_affiliations(self, heading_div): """ Makes the content for the Author Affiliations, displays after the Authors segment in the Heading. Metadata element, content derived from FrontMatter """ #Get all of the aff element tuples from the metadata aff...
0.004617
def removeidfobject(self, idfobject): """Remove an IDF object from the IDF. Parameters ---------- idfobject : EpBunch object The IDF object to remove. """ key = idfobject.key.upper() self.idfobjects[key].remove(idfobject)
0.006873
def write_traceback(logger=None, exc_info=None): """ Write the latest traceback to the log. This should be used inside an C{except} block. For example: try: dostuff() except: write_traceback(logger) Or you can pass the result of C{sys.exc_info()} to the C{e...
0.001709
def createSensorToClassifierLinks(network, sensorRegionName, classifierRegionName): """Create required links from a sensor region to a classifier region.""" network.link(sensorRegionName, classifierRegionName, "UniformLink", "", srcOutput="bucketIdxOut", destInput="b...
0.008224
def can_view(self, user): """ Returns True if user has permission to render this view. At minimum this requires an active staff user. If the required_groups attribute is not empty then the user must be a member of at least one of those groups. If there are no required groups set...
0.002121
def makePickle(self, record): """ Use JSON. """ #ei = record.exc_info #if ei: # dummy = self.format(record) # just to get traceback text into record.exc_text # record.exc_info = None # to avoid Unpickleable error s = '%s%s:%i:%s\n' % (self.prefix, r...
0.015217
def _parseBlockDevice(self, block_device): """ Parse a higher-level view of the block device mapping into something novaclient wants. This should be similar to how Horizon presents it. Required keys: device_name: The name of the device; e.g. vda or xda. source_typ...
0.001392
def assert_checked_checkbox(self, value): """Assert the checkbox with label (recommended), name or id is checked.""" check_box = find_field(world.browser, 'checkbox', value) assert check_box, "Cannot find checkbox '{}'.".format(value) assert check_box.is_selected(), "Check box should be selected."
0.003185
def build_b(self, scattering_fraction=0.01833): """Calculates the total scattering from back-scattering :param scattering_fraction: the fraction of back-scattering to total scattering default = 0.01833 b = ( bb[sea water] + bb[p] ) /0.01833 """ lg.info('Building b with scatteri...
0.009132
def list_queues(self, prefix=None, num_results=None, include_metadata=False, marker=None, timeout=None): ''' Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been ...
0.011923
def _handleDecodeHextileSubrectsColoured(self, block, bg, color, subrects, x, y, width, height, tx, ty, tw, th): """subrects with their own color""" sz = self.bypp + 2 pos = 0 end = len(block) while pos < end: pos2 = pos + self.bypp color = block[pos:pos2]...
0.004511
def ensure_one_opt(opt, parser, opt_list): """ Check that one and only one in the opt_list is defined in opt Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings """ the_one = None for name in...
0.006468
def update_from_dict(self, keywords): """Set properties of metadata using key and value from keywords :param keywords: A dictionary of keywords (key, value). :type keywords: dict """ for key, value in list(keywords.items()): setattr(self, key, value)
0.006579
def create_linked_data_element(self, url, kind, id=None, # pylint: disable=W0622 relation=None, title=None): """ Returns a new linked data element for the given url and kind. :param str url: URL to assign to the linked data element. :param str kind: ki...
0.007013
def match_name(self, in_string, fuzzy=False): """Match a color to a sRGB value. The matching will be based purely on the input string and the color names in the registry. If there's no direct hit, a fuzzy matching algorithm is applied. This method will never fail to return a sRGB value,...
0.005476
def save(self, **edgeArgs) : """Works like Document's except that you must specify '_from' and '_to' vertices before. There's also a links() function especially for first saves.""" if not getattr(self, "_from") or not getattr(self, "_to") : raise AttributeError("You must specify '_f...
0.010601
def bind(self, source=None, destination=None, node=None, edge_title=None, edge_label=None, edge_color=None, edge_weight=None, point_title=None, point_label=None, point_color=None, point_size=None): """Relate data attributes to graph structure and visual representation. To faci...
0.003624
def _update_frozencell(self, frozen): """Updates frozen cell widget Parameters ---------- frozen: Bool or string \tUntoggled iif False """ toggle_state = frozen is not False self.ToggleTool(wx.FONTFLAG_MASK, toggle_state)
0.006897
def add_future( self, future: "Union[Future[_T], concurrent.futures.Future[_T]]", callback: Callable[["Future[_T]"], None], ) -> None: """Schedules a callback on the ``IOLoop`` when the given `.Future` is finished. The callback is invoked with one argument, the ...
0.002778
def divine_format(text): """Guess the format of the notebook, based on its content #148""" try: nbformat.reads(text, as_version=4) return 'ipynb' except nbformat.reader.NotJSONError: pass lines = text.splitlines() for comment in ['', '#'] + _COMMENT_CHARS: metadata, ...
0.002759
def transformString( self, instring ): """Extension to scanString, to modify matching text with modified tokens that may be returned from a parse action. To use transformString, define a grammar and attach a parse action to it that modifies the returned token list. Invoking tra...
0.015794
def get_parent_objects(self, context): """Return all objects of the same type from the parent object """ parent_object = api.get_parent(context) portal_type = api.get_portal_type(context) return parent_object.objectValues(portal_type)
0.007299
def trends_place(self, woeid, exclude=None): """ Returns recent Twitter trends for the specified WOEID. If exclude == 'hashtags', Twitter will remove hashtag trends from the response. """ url = 'https://api.twitter.com/1.1/trends/place.json' params = {'id': woeid}...
0.003012
def build_from_corpus(cls, corpus_generator, target_vocab_size, max_subword_length=20, max_corpus_chars=None, reserved_tokens=None): """Builds a `SubwordTextEncoder` based on the `corpus_generator...
0.006773
async def send(self, metric): """Transform metric to JSON bytestring and send to server. Args: metric (dict): Complete metric to send as JSON. """ message = json.dumps(metric).encode('utf-8') await self.loop.create_datagram_endpoint( lambda: UDPClientProt...
0.005263
def git_clone(git_url, path): """Clone git repository at $git_url to $path.""" if os.path.exists(os.path.join(path, '.git')): # get rid of local repo if it already exists shutil.rmtree(path) os.makedirs(path, exist_ok=True) print('Start cloning from {}…'.format(git_url)) git_proc = ...
0.00106
def skill_configuration(self): # type: () -> SkillConfiguration """Create the skill configuration object using the registered components. """ skill_config = super(StandardSkillBuilder, self).skill_configuration skill_config.api_client = DefaultApiClient() if self...
0.003584
def findinfiles_callback(self): """Find in files callback""" widget = QApplication.focusWidget() if not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_() text = '' try: if widget.has_selected_text(): ...
0.003407
def get_required_arguments_metricnames(self): """ Helper function to get metricname arguments. Notice that it is get_argument"s" variation, which means that this can be repeated. Raises exception if argument is missing. Returns a list of metricname arguments """ try: metricnames = self...
0.010435
def publish(ctx, test=False, force=False, draft=False): """ Publish the project. :param bool test: Publishes to PyPi test server (defaults to False) :param bool force: Skip version check (defaults to False) :param bool draft: Sample publish (has no effect) (defaults to False) """ previous_vers...
0.001932
def get_return_operation_by_id(cls, return_operation_id, **kwargs): """Find ReturnOperation Return single instance of ReturnOperation by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api...
0.006091
def impute_dataframe_zero(df_impute): """ Replaces all ``NaNs``, ``-infs`` and ``+infs`` from the DataFrame `df_impute` with 0s. The `df_impute` will be modified in place. All its columns will be into converted into dtype ``np.float64``. :param df_impute: DataFrame to impute :type df_impute: pandas...
0.004839
def add_xmlid(ctx, record, xmlid, noupdate=False): """ Add a XMLID on an existing record """ try: ref_id, __, __ = ctx.env['ir.model.data'].xmlid_lookup(xmlid) except ValueError: pass # does not exist, we'll create a new one else: return ctx.env['ir.model.data'].browse(ref_id) ...
0.001613
def download_file_job(entry, directory, checksums, filetype='genbank', symlink_path=None): """Generate a DownloadJob that actually triggers a file download.""" pattern = NgdConfig.get_fileending(filetype) filename, expected_checksum = get_name_and_checksum(checksums, pattern) base_url = convert_ftp_url(...
0.002759
def get_introspection_data(cls, tax_benefit_system): """ Get instrospection data about the code of the variable. :returns: (comments, source file path, source code, start line number) :rtype: tuple """ comments = inspect.getcomments(cls) # Handle dynamically ge...
0.004107
def get_owner_names_value(self, obj): """Extract owners' names.""" return [ self._get_user(user) for user in get_users_with_permission(obj, get_full_perm('owner', obj)) ]
0.013761
def parse_fields(fields, as_dict=False): ''' Given a list of fields (or several other variants of the same), return back a consistent, normalized form of the same. To forms are currently supported: dictionary form: dict 'key' is the field name and dict 'value'...
0.000742