text
stringlengths
78
104k
score
float64
0
0.18
def add_user_to_allow(self, name, user): """Add a user to the given acl allow block.""" # Clear user from both allow and deny before adding if not self.remove_user_from_acl(name, user): return False if name not in self._acl: return False self._acl[name]...
0.005525
def get_tag(self, name): """Return the tag as Tag object.""" res = self.get_request('/tag/' + name) return Tag(cloud_manager=self, **res['tag'])
0.011905
def _get_mapping(self, section): '''mapping will take the section name from a Singularity recipe and return a map function to add it to the appropriate place. Any lines that don't cleanly map are assumed to be comments. Parameters ========== section: the...
0.004634
def image(self, src, title, text): """Rendering a image with title and text. :param src: source link of the image. :param title: title text of the image. :param text: alt text of the image. """ src = escape_link(src) text = escape(text, quote=True) if tit...
0.003221
def visitTripleConstraint(self, ctx: ShExDocParser.TripleConstraintContext): """ tripleConstraint: senseFlags? predicate inlineShapeExpression cardinality? annotation* semanticActions """ # This exists because of the predicate within annotation - if we default to visitchildren, we intercept both ...
0.007477
def pos3(self): ''' Use pos-sc1-sc2 as POS ''' parts = [self.pos] if self.sc1 and self.sc1 != '*': parts.append(self.sc1) if self.sc2 and self.sc2 != '*': parts.append(self.sc2) return '-'.join(parts)
0.007353
def _linearize(cls, inst_list): """ A generator function which performs linearization of the list of instructions; that is, each instruction which should be executed will be yielded in turn, recursing into ``Instructions`` instances that appear in the list. :param inst_l...
0.002813
def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None): """Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples""" project = os.path.basename(projectpath) if self.parent: #pylint: disable=too-many-nested-blocks #We have a parent, inf...
0.010644
def create_js_pay_params(self, **package): """ 签名 js 需要的参数 详情请参考 支付开发文档 :: wxclient.create_js_pay_params( body=标题, out_trade_no=本地订单号, total_fee=价格单位分, notify_url=通知url, spbill_create_ip=建议为支付人ip, ) :param...
0.00267
def set_mode_label_to_keywords_creation(self): """Set the mode label to the Keywords Creation/Update mode.""" self.setWindowTitle(self.keyword_creation_wizard_name) if self.get_existing_keyword('layer_purpose'): mode_name = tr( 'Keywords update wizard for layer <b>{la...
0.003339
def list(self, **kwargs): """Retrieve a list of objects. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): ...
0.00122
async def _sync_revoc(self, rr_id: str, rr_size: int = None) -> None: """ Create revoc registry if need be for input revocation registry identifier; open and cache tails file reader. :param rr_id: revocation registry identifier :param rr_size: if new revocation registry necessar...
0.006678
def _old_epd_diffmags(coeff, fsv, fdv, fkv, xcc, ycc, bgv, bge, mag): ''' This calculates the difference in mags after EPD coefficients are calculated. final EPD mags = median(magseries) + epd_diffmags() ''' return -(coeff[0]*fsv**2. + coeff[1]*fsv + coeff[2]*fdv**2....
0.001035
def _add_references(self, rec): """ Adds the reference to the record """ for ref in self.document.getElementsByTagName('ref'): for ref_type, doi, authors, collaboration, journal, volume, page, year,\ label, arxiv, publisher, institution, unstructured_text,\ ...
0.003757
def show(self, id): """GET /datastores/id: Show a specific item.""" # url('DataStores', id=ID) datastore = meta.Session.query(DataStore).get(id) # do not raise RuntimeError from discover_datasources # if in "test" mode try: datasources = discover_datasources(...
0.003396
def stop(self): """Output Checkstyle XML reports.""" et = ET.ElementTree(self.checkstyle_element) f = BytesIO() et.write(f, encoding='utf-8', xml_declaration=True) xml = f.getvalue().decode('utf-8') if self.output_fd is None: print(xml) else: ...
0.005089
def timer(fun, *a, **k): """ define a timer for a rule function for log and statistic purposes """ @wraps(fun) def timer(*a, **k): start = arrow.now() ret = fun(*a, **k) end = arrow.now() print('timer:fun: %s\n start:%s,end:%s, took [%s]' % ( str(fun), str(sta...
0.002571
def location_path(cls, project, location): """Return a fully-qualified location string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}", project=project, location=location, )
0.007246
def query(self, query, interpolations=None): """ Queries a timeseries table. :param query: The timeseries query. :type query: string :rtype: :class:`TsObject <riak.ts_object.TsObject>` """ return self._client.ts_query(self, query, interpolations)
0.006601
def columnize_commands(self, commands): """List commands arranged in an aligned columns""" commands.sort() width = self.debugger.settings['width'] return columnize.columnize(commands, displaywidth=width, lineprefix=' ')
0.00692
def _init(): ''' Internal switchyard static initialization method. ''' if ApplicationLayer._isinit: return ApplicationLayer._isinit = True ApplicationLayer._to_app = {} ApplicationLayer._from_app = Queue()
0.010909
def uninstall(self, package): """Uninstalls the given package (given in pip's package syntax or a tuple of ('name', 'ver')) from this virtual environment.""" if isinstance(package, tuple): package = '=='.join(package) if not self.is_installed(package): self._write...
0.005085
def _setup(): """Add a variety of default schemes.""" s = str.split if sys.version_info < (3, 0): # noinspection PyUnresolvedReferences s = unicode.split def pop_all(some_dict, some_list): for scheme in some_list: some_dict.pop(scheme) global SCHEMES ...
0.002168
def _sync(self): """Write persistent dictionary to disc.""" _logger.debug("_sync()") self._lock.acquire_write() # TODO: read access is enough? try: if self._loaded: self._dict.sync() finally: self._lock.release()
0.006826
def add_keywords_from_list(self, keyword_list): """To add keywords from a list Args: keyword_list (list(str)): List of keywords to add Examples: >>> keyword_processor.add_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_lis...
0.003711
def timed_connectivity_check(self, event): """Tests internet connectivity in regular intervals and updates the nodestate accordingly""" self.status = self._can_connect() self.log('Timed connectivity check:', self.status, lvl=verbose) if self.status: if not self.old_status: ...
0.006631
def build_filter(filter_or_string, *args, **kwargs): """ Overloaded filter construction. If ``filter_or_string`` is a string we look up it's corresponding class in the filter registry and return it. Otherwise, assume ``filter_or_string`` is an instance of a filter. :return: :class:`~es_fluent.filte...
0.001295
def set(self, key, value, *, section=DataStoreDocumentSection.Data): """ Store a value under the specified key in the given section of the document. This method stores a value into the specified section of the workflow data store document. Any existing value is overridden. Before storing a valu...
0.005917
def _ordereddict2dict(input_ordered_dict): ''' Convert ordered dictionary to a dictionary ''' return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict))
0.005525
def addTerms(self, data, LIMIT=25, _print=True, crawl=False): """ need: label <str> type term, cde, anntation, or relationship <str> options: definition <str> #bug with qutations sup...
0.00571
def hardware_flexport_flexport_type_skip_deconfig(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") flexport = ET.SubElement(hardware, "flexport") id_key = ...
0.004886
def parameter_present(name, db_parameter_group_family, description, parameters=None, apply_method="pending-reboot", tags=None, region=None, key=None, keyid=None, profile=None): ''' Ensure DB parameter group exists and update parameters. name The name for the parameter group. ...
0.003959
def _modifies_cart(func): ''' Decorator that makes the wrapped function raise ValidationError if we're doing something that could modify the cart. It also wraps the execution of this function in a database transaction, and marks the boundaries of a cart operations batch. ''' @functools.wraps(f...
0.00137
def diff(self, source_path='', target_path='', which=-1): """Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_pa...
0.002606
def process_pgp(self, data, name): """ PGP key processing :param data: :param name: :return: """ ret = [] try: data = to_string(data) parts = re.split(r'-{5,}BEGIN', data) if len(parts) == 0: return ...
0.003781
def parse(self, element): r"""Parse xml element. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict """ values = {} for child in element: node = self.get_node(child) subs = self.parse(child) value = subs o...
0.00312
def include(self, **attrs): """Add items to distribution that are named in keyword arguments For example, 'dist.include(py_modules=["x"])' would add 'x' to the distribution's 'py_modules' attribute, if it was not already there. Currently, this method only supports inclusion for...
0.001996
def render_linked_css(self, css_files: Iterable[str]) -> str: """Default method used to render the final css links for the rendered webpage. Override this method in a sub-classed controller to change the output. """ paths = [] unique_paths = set() # type: Set[str] ...
0.002801
def _modify(self, **patch): '''Modify only draft or legacy policies Published policies cannot be modified :raises: OperationNotSupportedOnPublishedPolicy ''' legacy = patch.pop('legacy', False) tmos_ver = self._meta_data['bigip']._meta_data['tmos_version'] self....
0.002837
def email(random=random, *args, **kwargs): """ Return an e-mail address >>> mock_random.seed(0) >>> email(random=mock_random) 'onion@bag-of-heroic-chimps.sexy' >>> email(random=mock_random) 'agatha-incrediblebritches-spam@amazingbritches.click' >>> email(random=mock_random, name="charle...
0.00155
def confd_state_internal_callpoints_authorization_callbacks_registration_type_range_path(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.Sub...
0.007335
def partition_source(src): """Partitions source into a list of `CodePartition`s for import refactoring. """ # In python2, ast.parse(text_string_with_encoding_pragma) raises # SyntaxError: encoding declaration in Unicode string ast_obj = ast.parse(src.encode('UTF-8')) visitor = TopLevelImport...
0.000296
def get_upload_path(instance, filename): """Overriding to store the original filename""" if not instance.name: instance.name = filename # set original filename date = timezone.now().date() filename = '{name}.{ext}'.format(name=uuid4().hex, ext=filename.split...
0.002155
def _store16(ins): """ Stores 2nd operand content into address of 1st operand. store16 a, x => *(&a) = x Use '*' for indirect store on 1st operand. """ output = [] output = _16bit_oper(ins.quad[2]) try: value = ins.quad[1] indirect = False if value[0] == '*': ...
0.000511
def max(self): """ Returns the maximum value of the domain. :rtype: `float` or `np.inf` """ return int(self._max) if not np.isinf(self._max) else self._max
0.010204
def make_response(event): """Make a response from webhook event.""" code, message = event.status response = jsonify(**event.response) response.headers['X-Hub-Event'] = event.receiver_id response.headers['X-Hub-Delivery'] = event.id if message: response.headers['X-Hub-Info'] = message ...
0.002024
def non_empty_lines(path): """ Yield non-empty lines from file at path """ with open(path) as f: for line in f: line = line.strip() if line: yield line
0.004651
def start(self): """Starts watching the path and running the test jobs.""" assert not self.watching def selector(evt): if evt.is_directory: return False path = evt.path if path in self._last_fnames: # Detected a "killing cycle" return False for pattern in self.skip_p...
0.010539
def dispatch(self, packet): """ dispatch: XBee data dict -> None When called, dispatch checks the given packet against each registered callback method and calls each callback whose filter function returns true. """ for handler in self.handlers: if han...
0.003745
def uninstall_bundle(self, bundle): # type: (Bundle) -> None """ Ends the uninstallation of the given bundle (must be called by Bundle) :param bundle: The bundle to uninstall :raise BundleException: Invalid bundle """ if bundle is None: # Do nothing ...
0.002026
def execute(self, run): """ This function executes the tool with a sourcefile with options. It also calls functions for output before and after the run. """ self.output_handler.output_before_run(run) benchmark = self.benchmark memlimit = benchmark.rlimits.get(MEM...
0.001028
def ReleaseTypeEnum(ctx): """Types of Releases.""" return Enum( ctx, all=0, selected=3, sametype=4, notselected=5, inversetype=6, default=Pass )
0.004717
def bin_query(self, table, chrom, start, end): """ perform an efficient spatial query using the bin column if available. The possible bins are calculated from the `start` and `end` sent to this function. Parameters ---------- table : str or table tabl...
0.002632
def player_s(self, sid) : """Returns the full set of data on a player, no filtering""" try: url = self.pubg_url_steam.format(str(sid)) response = requests.request("GET", url, headers=self.headers) return json.loads(response.text) except BaseExcepti...
0.007353
def get_parser(commands): """ Generate argument parser given a list of subcommand specifications. :type commands: list of (str, function, function) :arg commands: Each element must be a tuple ``(name, adder, runner)``. :param name: subcommand :param adder: a function takes ...
0.000826
def git_available(func): """ Check, if a git repository exists in the given folder. """ def inner(*args): os.chdir(APISettings.GIT_DIR) if call(['git', 'rev-parse']) == 0: return func(*args) Shell.fail('There is no git repository!') return exit(1) retur...
0.003058
def vpn_connections(self): """Instance depends on the API version: * 2018-04-01: :class:`VpnConnectionsOperations<azure.mgmt.network.v2018_04_01.operations.VpnConnectionsOperations>` """ api_version = self._get_api_version('vpn_connections') if api_version == '2018-04-01': ...
0.009077
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() return "%s/%s" % (url, name)
0.010152
def get_export( self, export_type, generate=False, wait=False, wait_timeout=None, ): """ Downloads a data export over HTTP. Returns a `Requests Response <http://docs.python-requests.org/en/master/api/#requests.Response>`_ object containing the ...
0.001216
def genInterval(self, month=(), day=(), week=(), weekday=(), hour=(), minute=()): '''Generate list of config dictionarie(s) that represent a interval of time. Used to be passed into add() or r...
0.006598
def _bool_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ op_name = _get_op_name(op, special) def na_op(x, y): try: result = op(x, y) except TypeError: assert not isinstance(y, (list, ...
0.001593
def _example_stock_quote(quote_ctx): """ 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 """ stock_code_list = ["US.AAPL", "HK.00700"] # subscribe "QUOTE" ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.QUOTE) if ret_status != ft.RET_OK: print("%s ...
0.00266
def _get_kwsdag(self, goids, go2obj, **kws_all): """Get keyword args for a GoSubDag.""" kws_dag = {} # Term Counts for GO Term information score tcntobj = self._get_tcntobj(goids, go2obj, **kws_all) # TermCounts or None if tcntobj is not None: kws_dag['tcntobj'] = tc...
0.004498
def is_blocked(self): """:class:`bool`: Checks if the user is blocked. .. note:: This only applies to non-bot accounts. """ r = self.relationship if r is None: return False return r.type is RelationshipType.blocked
0.006944
def simulation(self, ts_length=90, random_state=None): """ Compute a simulated sample path assuming Gaussian shocks. Parameters ---------- ts_length : scalar(int), optional(default=90) Number of periods to simulate for random_state : int or np.random.RandomS...
0.002047
def create_subscription(request): "Shows subscriptions options for a new subscriber." if request.POST: form = NewSubscriptionForm(request.POST) if form.is_valid(): unverified = form.save() body = """Please confirm your email address to subscribe to status updates fr...
0.005456
def apply(self, img, factor=0, **params): """ Args: factor (int): number of times the input will be rotated by 90 degrees. """ return np.ascontiguousarray(np.rot90(img, factor))
0.013575
def _log_board_terrain(self, terrain): """ Tiles are logged counterclockwise beginning from the top-left. See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout. :param terrain: list of catan.board.Terrain objects """ self._logln('terrain: {0}'.fo...
0.00831
def has_regex_namespace_name(self, namespace: str, name: str) -> bool: """Check that the namespace is defined as a regular expression and the name matches it.""" return self.has_regex_namespace(namespace) and self.namespace_to_pattern[namespace].match(name)
0.014652
def loadSVcols(fname, usecols=None, excludecols=None, valuefixer=None, colfixer=None, missingvalues=None, fillingvalues=None, typeinferer=None, **kwargs): """ Load a separated value text file to a list of column arrays. Basically, this function calls loadSVrecs, and transpose...
0.011456
def cast_scalar_indexer(val): """ To avoid numpy DeprecationWarnings, cast float to integer where valid. Parameters ---------- val : scalar Returns ------- outval : scalar """ # assumes lib.is_scalar(val) if lib.is_float(val) and val == int(val): return int(val) ...
0.003021
def get(self, name_or_klass): """ Gets a specific panel instance. :param name_or_klass: Name or class of the panel to retrieve. :return: The specified panel instance. """ if not is_text_string(name_or_klass): name_or_klass = name_or_klass.__name__ for...
0.00365
def newVersion(): """increments version counter in swhlab/version.py""" version=None fname='../swhlab/version.py' with open(fname) as f: raw=f.read().split("\n") for i,line in enumerate(raw): if line.startswith("__counter__"): if version is None: ...
0.018416
def _get_backtrace(self, frames, inspect_packages=False, depth=0): ''' get a nicely formatted backtrace since -- 7-6-12 frames -- list -- the frame_tuple frames to format inpsect_packages -- boolean -- by default, this only prints code of packages that are not in t...
0.011119
def get_model(app_dot_model): """ Returns Django model class corresponding to passed-in `app_dot_model` string. This is helpful for preventing circular-import errors in a Django project. Positional Arguments: ===================== - `app_dot_model`: Django's `<app_name>.<model_name>` syntax...
0.001292
def check_authorization(self): """ Check for the presence of a basic auth Authorization header and if the credentials contained within in are valid. :return: Whether or not the credentials are valid. :rtype: bool """ try: store = self.__config.get('basic_auth') if store is None: return True ...
0.030591
def _load_child_state_models(self, load_meta_data): """Adds models for each child state of the state :param bool load_meta_data: Whether to load the meta data of the child state """ self.states = {} # Create model for each child class child_states = self.state.states ...
0.006667
def destroy_webdriver(driver): """ Destroy a driver """ # This is some very flaky code in selenium. Hence the retries # and catch-all exceptions try: retry_call(driver.close, tries=2) except Exception: pass try: driver.quit() except Exception: pass
0.003155
def edges_dump(self): """Dump the entire contents of the edges table.""" self._flush_edges() for ( graph, orig, dest, idx, branch, turn, tick, extant ) in self.sql('edges_dump'): yield ( self.unpack(graph), self.unpack(orig), ...
0.004132
def string_class(cls): """Define __unicode__ and __str__ methods on the given class in Python 2. The given class must define a __str__ method returning a unicode string, otherwise a TypeError is raised. Under Python 3, the class is returned as is. """ if not PY3: if '__str__' not in cls...
0.00188
def float2dec(ft, decimal_digits): """ Convert float (or int) to Decimal (rounding up) with the requested number of decimal digits. Arguments: ft (float, int): Number to convert decimal (int): Number of digits after decimal point Return: Decimal: Number converted to decima ...
0.001876
def make_encrypted_token(self, key): """Encrypts the payload. Creates a JWE token with the header as the JWE protected header and the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk....
0.004577
def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, *varBinds, **options): """Send SNMP notification. Based on passed parameters, prepares SNMP TRAP or INFORM notification (:RFC:`1905#section-4.2.6`) and schedules its transmission by I/O framework a...
0.001859
def expect_column_value_lengths_to_equal(self, column, value, mostly=None, result_format=None, include_config=False, catch_exceptions=None, ...
0.007715
def reload_including_local(module): """ Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that has acquired the import lock. :param module: the module to reload. """ try: reload(module) except ImportError: ...
0.002099
def action_verify_checksum(self, ids): """Inactivate users.""" try: count = 0 for file_id in ids: f = FileInstance.query.filter_by( id=uuid.UUID(file_id)).one_or_none() if f is None: raise ValueError(_("Canno...
0.002591
def digest(self): """Return final digest value. """ if self._digest is None: if self._buf: self._add_block(self._buf) self._buf = EMPTY ctx = self._blake2s(0, 1, True) for t in self._thread: ctx.update(t.digest()...
0.005141
def store_context(context): """Persist a furious.context.Context object to the datastore by loading it into a FuriousContext ndb.Model. """ logging.debug("Attempting to store Context %s.", context.id) entity = FuriousContext.from_context(context) # TODO: Handle exceptions and retries here. ...
0.002058
def _cast(self, value): """ Cast the specifief value to the type of this setting. """ if self.type != 'text': value = utils.cast(self.TYPES.get(self.type)['cast'], value) return value
0.009132
def _message_to_payload(cls, message): '''Returns a Python object or a ProtocolError.''' try: return json.loads(message.decode()) except UnicodeDecodeError: message = 'messages must be encoded in UTF-8' except json.JSONDecodeError: message = 'invalid J...
0.005168
def item_sectie_adapter(obj, request): """ Adapter for rendering an object of :class: `crabpy.gateway.capakey.Sectie` to json. """ return { 'id': obj.id, 'afdeling': { 'id': obj.afdeling.id, 'naam': obj.afdeling.naam, 'gemeente': { ...
0.001965
def status(self, status: int) -> None: """ 设置响应状态 """ self._status = status self._message = STATUS_CODES[status]
0.013158
def request_signed_by_signing_keys(keyjar, msreq, iss, lifetime, kid=''): """ A metadata statement signing request with 'signing_keys' signed by one of the keys in 'signing_keys'. :param keyjar: A KeyJar instance with the private signing key :param msreq: Metadata statement signing request. A Metad...
0.003755
def t_binaryValue(t): r'[+-]?[0-9]+[bB]' # We must match [0-9], and then check the validity of the binary number. # If we match [0-1], the invalid binary number "2b" would match # 'decimalValue' 2 and 'IDENTIFIER 'b'. if re.search(r'[2-9]', t.value) is not None: msg = _format("Invalid binary...
0.00188
def email(self, comment, content_object, request): """ Overwritten for a better email notification. """ if not self.email_notification: return send_comment_posted(comment, request)
0.008584
def html(self) -> str: """Return string representation of this. Used in start tag of HTML representation of the Element node. """ if self._owner and self.name in self._owner._special_attr_boolean: return self.name else: value = self.value if i...
0.004348
def gradient_factory(name): """Create gradient `Functional` for some ufuncs.""" if name == 'sin': def gradient(self): """Return the gradient operator.""" return cos(self.domain) elif name == 'cos': def gradient(self): """Return the gradient operator.""" ...
0.000565
def logs_sidecars_jobs(job_uuid: str, job_name: str, log_lines: Optional[Union[str, Iterable[str]]]) -> None: """Signal handling for sidecars logs.""" handle_job_logs(job_uuid=job_uuid, job_name=job_name, log_lines=log_lines) ...
0.00216
def main(): """Filters the document AST.""" # pylint: disable=global-statement global PANDOCVERSION global AttrTable # Get the output format and document fmt = args.fmt doc = json.loads(STDIN.read()) # Initialize pandocxnos # pylint: disable=too-many-function-args PANDOCVERSIO...
0.000812
def main(): """ Sends an API AT command to read the lower-order address bits from an XBee Series 1 and looks for a response """ try: # Open serial port ser = serial.Serial('/dev/ttyUSB0', 9600) # Create XBee Series 1 object xbee = XBee(ser) # Send AT packe...
0.001889