text
stringlengths
78
104k
score
float64
0
0.18
def prepend_http(url): """ Ensure there's a scheme specified at the beginning of a url, defaulting to http:// >>> prepend_http('duckduckgo.com') 'http://duckduckgo.com' """ url = url.lstrip() if not urlparse(url).scheme: return 'http://' + url return url
0.006873
def loadModule(self, modName, **userCtx): """Load and execute MIB modules as Python code""" for mibSource in self._mibSources: debug.logger & debug.FLAG_BLD and debug.logger( 'loadModule: trying %s at %s' % (modName, mibSource)) try: codeObj, sfx ...
0.001613
def j1(x, context=None): """ Return the value of the first kind Bessel function of order 1 at x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j1, (BigFloat._implicit_convert(x),), context, )
0.003774
def parse_tweet(raw_tweet, source, now=None): """ Parses a single raw tweet line from a twtxt file and returns a :class:`Tweet` object. :param str raw_tweet: a single raw tweet line :param Source source: the source of the given tweet :param Datetime now: the current datetime...
0.001443
def main(args, stop=False): """ Arguments parsing, etc.. """ daemon = AMQPDaemon( con_param=getConParams( settings.RABBITMQ_STORAGE_VIRTUALHOST ), queue=settings.RABBITMQ_STORAGE_INPUT_QUEUE, out_exch=settings.RABBITMQ_STORAGE_EXCHANGE, out_key=setting...
0.001721
def present(name, login=None, domain=None, database=None, roles=None, options=None, **kwargs): ''' Checks existance of the named user. If not present, creates the user with the specified roles and options. name The name of the user to manage login If not specified, will be created W...
0.005797
def envelope(**kwargs): """Create OAI-PMH envelope for response.""" e_oaipmh = Element(etree.QName(NS_OAIPMH, 'OAI-PMH'), nsmap=NSMAP) e_oaipmh.set(etree.QName(NS_XSI, 'schemaLocation'), '{0} {1}'.format(NS_OAIPMH, NS_OAIPMH_XSD)) e_tree = ElementTree(element=e_oaipmh) if current_a...
0.000858
def upload_file_sections(self, user_id, section_id, assignment_id): """ Upload a file. Upload a file to a submission. This API endpoint is the first step in uploading a file to a submission as a student. See the {file:file_uploads.html File Upload Documentation} ...
0.006593
def set(self, instance, value, **kw): """ Set Analyses to an AR :param instance: Analysis Request :param value: Single AS UID or a list of dictionaries containing AS UIDs :param kw: Additional keyword parameters passed to the field """ if not isinstance(value, (...
0.003722
def ndto2d(x, axis=-1): """Convert a multi-dimensional array into a 2d array, with the axes specified by the `axis` parameter flattened into an index along rows, and the remaining axes flattened into an index along the columns. This operation can not be properly achieved by a simple reshape operatio...
0.00055
def get_channel_type(channel, framefile): """Find the channel type in a given GWF file **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str`, `~gwpy.detector.Channel` name of data channel to find framefile : `str` path of GWF file in which to search Re...
0.001318
def _GetChromeWebStorePage(self, extension_identifier): """Retrieves the page for the extension from the Chrome store website. Args: extension_identifier (str): Chrome extension identifier. Returns: str: page content or None. """ web_store_url = self._WEB_STORE_URL.format(xid=extension...
0.006107
def Matches(self, file_entry): """Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter, False if not or None if the filter does not apply. """ location = getattr(file_en...
0.005597
def import_locations(self, data, index='WMO'): """Parse NOAA weather station data files. ``import_locations()`` returns a dictionary with keys containing either the WMO or ICAO identifier, and values that are ``Station`` objects that describes the large variety of data exported by NOAA_...
0.001178
def config_string(self): """ Build the storable string corresponding to this configuration object. :rtype: string """ return (gc.CONFIG_STRING_SEPARATOR_SYMBOL).join( [u"%s%s%s" % (fn, gc.CONFIG_STRING_ASSIGNMENT_SYMBOL, self.data[fn]) for fn in sorted(self.d...
0.008086
def unescape(s): """Unescape ASSUAN message (0xAB <-> '%AB').""" s = bytearray(s) i = 0 while i < len(s): if s[i] == ord('%'): hex_bytes = bytes(s[i+1:i+3]) value = int(hex_bytes.decode('ascii'), 16) s[i:i+3] = [value] i += 1 return bytes(s)
0.003195
def packageipa(env, console): """ Package the built app as an ipa for distribution in iOS App Store """ ipa_path, app_path = _get_ipa(env) output_dir = path.dirname(ipa_path) if path.exists(ipa_path): console.quiet('Removing %s' % ipa_path) os.remove(ipa_path) zf = zipfile....
0.001202
def update_target(self, name, current, total): """Updates progress bar for a specified target.""" self.refresh(self._bar(name, current, total))
0.012579
def fetch_and_create_image(self, url, image_title): ''' fetches, creates image object returns tuple with Image object and context dictionary containing request URL ''' context = { "file_url": url, "foreign_title": image_title, } t...
0.002448
def fromSearch(text): """ Generates a regular expression from 'simple' search terms. :param text | <str> :usage |>>> import projex.regex |>>> projex.regex.fromSearch('*cool*') |'^.*cool.*$' |>>> projex.projex.fromSearch('*cool*,*test*')...
0.00578
def write (self, s): """Process text, writing it to the virtual screen while handling ANSI escape codes. """ if isinstance(s, bytes): s = self._decode(s) for c in s: self.process(c)
0.012245
def replicate_global_dbs(cloud_url=None, local_url=None): """ Set up replication of the global databases from the cloud server to the local server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing t...
0.001235
def _printCtrlConf(self): """ get PV value and print out """ if self.ctrlinfo: print("Control configs:") for k, v in sorted(self.ctrlinfo.items(), reverse=True): pv = v['pv'] rval = epics.caget(pv) if rval is None: ...
0.007389
def zremrangebylex(self, name, min, max): """ Remove all elements in the sorted set between the lexicographical range specified by ``min`` and ``max``. Returns the number of elements removed. :param name: str the name of the redis key :param min: int or -inf ...
0.004124
def collections(tag, collectionName, token='', version=''): '''Returns an array of quote objects for a given collection type. Currently supported collection types are sector, tag, and list https://iexcloud.io/docs/api/#collections Args: tag (string); Sector, Tag, or List collectionName (...
0.004373
def _handle_response(response): """Internal helper for handling API responses from the Quoine server. Raises the appropriate exceptions when necessary; otherwise, returns the response. """ if not str(response.status_code).startswith('2'): raise KucoinAPIException(res...
0.004391
def insert( self, obj=None, overwrite=False, partition=None, values=None, validate=True, ): """ Insert into Impala table. Wraps ImpalaClient.insert Parameters ---------- obj : TableExpr or pandas DataFrame overwrite : b...
0.001224
def set_stream(self): """ Sets the download streams """ if not self.auth: raise AccessError("Please use the remote() method to set rsync authorization or use remote(public=True) for public data") elif not self.initial_stream.task: raise AccessError("No files to download....
0.005181
def remove_nio(self, port_number): """ Removes the specified NIO as member of cloud. :param port_number: allocated port number :returns: the NIO that was bound to the allocated port """ if port_number not in self._nios: raise NodeError("Port {} is not alloc...
0.006184
def paintEvent(self, event): """When an area of the window is exposed, we just copy out of the server-side, off-screen pixmap to that area. """ if not self.pixmap: return rect = event.rect() x1, y1, x2, y2 = rect.getCoords() width = x2 - x1 + 1 ...
0.003802
def set(self, oid, value): """Use PySNMP to perform an SNMP SET operation on a single object. :param oid: The OID of the object to set. :param value: The value of the object to set. :raises: SNMPFailure if an SNMP request fails. """ try: results = self.cmd_ge...
0.001698
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes if hasattr(self, 'maximum_allowed_bytes' ) and self.maximum_allowed_b...
0.006977
def replace_template(self, template_content, team_context, template_id): """ReplaceTemplate. [Preview API] Replace template contents :param :class:`<WorkItemTemplate> <azure.devops.v5_1.work_item_tracking.models.WorkItemTemplate>` template_content: Template contents to replace with :para...
0.00443
def base_name_from_image(image): """Extract the base name of the image to use as the 'algorithm name' for the job. Args: image (str): Image name. Returns: str: Algorithm name, as extracted from the image name. """ m = re.match("^(.+/)?([^:/]+)(:[^:]+)?$", image) algo_name = m.g...
0.005495
def serialize(self, sw): '''Serialize the object.''' detail = None if self.detail is not None: detail = Detail() detail.any = self.detail pyobj = FaultType(self.code, self.string, self.actor, detail) sw.serialize(pyobj, typed=False)
0.010067
def _not_in(x, y): """Compute the vectorized membership of ``x not in y`` if possible, otherwise use Python. """ try: return ~x.isin(y) except AttributeError: if is_list_like(x): try: return ~y.isin(x) except AttributeError: pas...
0.002882
def message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
0.010695
def _choose_split_points(cls, sorted_keys, shard_count): """Returns the best split points given a random set of datastore.Keys.""" assert len(sorted_keys) >= shard_count index_stride = len(sorted_keys) / float(shard_count) return [sorted_keys[int(round(index_stride * i))] for i in range(1, s...
0.003012
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) if self.ord != np.inf: rai...
0.005706
def store_meta_data(self, copy_path=None): """Save meta data of the state machine model to the file system This method generates a dictionary of the meta data of the state machine and stores it on the filesystem. :param str copy_path: Optional, if the path is specified, it will be used instead...
0.008535
def install_importer(): """ If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """ logging.debug('install_importer') if not in_venv(): logging.debug('No virtualenv active py:[%s]', sys.executable) r...
0.001057
def _get_model_reference(self, model_id): """Constructs a ModelReference. Args: model_id (str): the ID of the model. Returns: google.cloud.bigquery.model.ModelReference: A ModelReference for a model in this dataset. """ return ModelReference.from_api_repr( {"pro...
0.005013
def _kip(self, cycle_end, mix_thresh, xaxis, sparse): """ *** Should be used with care, therefore has been flagged as a private routine *** This function uses a threshold diffusion coefficient, above which the the shell is considered to be convective, to plot a Kippenhahn...
0.009388
def get(cls, id): ''' Retrieves an object by id. Returns None in case of failure ''' if not id: return None redis = cls.get_redis() key = '{}:{}:obj'.format(cls.cls_key(), id) if not redis.exists(key): return None obj = cls(id=id) obj._...
0.003328
def _extract(self, parselet_node, document, level=0): """ Extract values at this document node level using the parselet_node instructions: - go deeper in tree - or call selector handler in case of a terminal selector leaf """ if self.DEBUG: debug_offs...
0.004413
def create_new_version( self, name, subject, text='', template_id=None, html=None, locale=None, timeout=None ): """ API call to create a new version of a template """ if(html): payload = { 'name': name, ...
0.003138
def parse(data): """ Parse the given ChangeLog data into a list of Hashes. @param [String] data File data from the ChangeLog.md @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...] """ sections = re.compile("^## .+$", re.MULTILINE).s...
0.003431
def cell_px(self, line='', cell=None): """Executes the cell in parallel. Examples -------- :: In [24]: %%px --noblock ....: a = os.getpid() Async parallel execution on engine(s): all In [25]: %%px .....
0.009212
def decode_speech(path, keypath=None, save=False, speech_context=None, sample_rate=44100, max_alternatives=1, language_code='en-US', enable_word_time_offsets=True, return_raw=False): """ Decode speech for a file or folder and return results This function wraps the Google...
0.003573
def ChangePassword(self, password_old, password_new): """ Change the password used to protect the private key. Args: password_old (str): the current password used to encrypt the private key. password_new (str): the new to be used password to encrypt the private key. ...
0.006242
def change_subitem(self, offset=None, max_item_count=None, nom=True): """ Args: * offset - Integer - The positive / negative change to apply to the item. * max_item_count - The maximum number of items available. * nom - None on Max or Min - If max or min number of itemsreac...
0.003915
def load_model( self, the_metamodel, filename, is_main_model, encoding='utf-8', add_to_local_models=True): """ load a single model Args: the_metamodel: the metamodel used to load the model filename: the model to be loaded (if not cached) ...
0.001452
def agg(self, *exprs): """Compute aggregates and returns the result as a :class:`DataFrame`. The available aggregate functions can be: 1. built-in aggregation functions, such as `avg`, `max`, `min`, `sum`, `count` 2. group aggregate pandas UDFs, created with :func:`pyspark.sql.functio...
0.00567
def master_then_spare(data): """Return the provided satellites list sorted as: - alive first, - then spare - then dead satellites. :param data: the SatelliteLink list :type data: list :return: sorted list :rtype: list """ master = [] spare = [] for sd...
0.001938
def distance(tree1, tree2): ''' Calculates the distance between the two trees. @type tree1: list of Views @param tree1: Tree of Views @type tree2: list of Views @param tree2: Tree of Views @return: the distance ''' ################################...
0.004563
async def processClientInBox(self): """ Process the messages in the node's clientInBox asynchronously. All messages in the inBox have already been validated, including signature check. """ while self.clientInBox: m = self.clientInBox.popleft() req,...
0.002706
async def _receive(self, stream_id, pp_id, data): """ Receive data stream -> ULP. """ await self._data_channel_receive(stream_id, pp_id, data)
0.011494
def newidfobject(self, key, aname='', defaultvalues=True, **kwargs): """ Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", ...
0.004563
def get_synset_xml(self,syn_id): """ call cdb_syn with synset identifier -> returns the synset xml; """ http, resp, content = self.connect() params = "" fragment = "" path = "cdb_syn" if self.debug: printf( "cornettodb/views/query_remote_s...
0.025482
def _apply_secure(self, func, permission=None): '''Enforce authentication on a given method/verb''' self._handle_api_doc(func, {'security': 'apikey'}) @wraps(func) def wrapper(*args, **kwargs): if not current_user.is_authenticated: self.abort(401) ...
0.003795
def read(self, fname, psw=None): """Return uncompressed data for archive entry. For longer files using :meth:`RarFile.open` may be better idea. Parameters: fname filename or RarInfo instance psw password to use for extracting. ""...
0.005051
def _get_dvs_link_discovery_protocol(dvs_name, dvs_link_disc_protocol): ''' Returns the dict representation of the DVS link discovery protocol dvs_name The name of the DVS dvs_link_disc_protocl The DVS link discovery protocol ''' log.trace('Building the dict of the DVS \'%s\' l...
0.004255
def get_dataset(self, X, y=None): """Get a dataset that contains the input data and is passed to the iterator. Override this if you want to initialize your dataset differently. Parameters ---------- X : input data, compatible with skorch.dataset.Dataset ...
0.001285
def to_rgba(color, alpha): """ Converts from hex|rgb to rgba Parameters: ----------- color : string Color representation on hex or rgb alpha : float Value from 0 to 1.0 that represents the alpha value. Example: ...
0.002345
def popall(self, key, default=_marker): """Remove all occurrences of key and return the list of corresponding values. If key is not found, default is returned if given, otherwise KeyError is raised. """ found = False identity = self._title(key) ret = [] ...
0.002481
def guid(self, guid): """Determines JSONAPI type for provided GUID""" return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']
0.017964
def read_busiest_week(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find the earliest week with the most trips""" feed = load_raw_feed(path) return _busiest_week(feed)
0.005348
def parents(self, node): """Determine all parents of node in our tree""" return [ parent for parent in getattr( node, 'parents', [] ) if getattr(parent, 'tree', self.TREE) == self.TREE ]
0.01626
def getQueryEngineDescription(self, queryEngine, **kwargs): """See Also: getQueryEngineDescriptionResponse() Args: queryEngine: **kwargs: Returns: """ response = self.getQueryEngineDescriptionResponse(queryEngine, **kwargs) return self._read_dataone...
0.010811
def partitionBy(self, numPartitions, partitionFunc=portable_hash): """ Return a copy of the DStream in which each RDD are partitioned using the specified partitioner. """ return self.transform(lambda rdd: rdd.partitionBy(numPartitions, partitionFunc))
0.010309
def from_dict(d): """ Recreate a KrausModel from the dictionary representation. :param dict d: The dictionary representing the KrausModel. See `to_dict` for an example. :return: The deserialized KrausModel. :rtype: KrausModel """ kraus_ops = [KrausMod...
0.008696
def draw_circle(self, pos, radius, color, fillcolor=None): """ Draw a circle with the given color on the screen and optionally fill it with fillcolor. :param pos: Center of the circle :param radius: Radius :param color: Color for border :param fillcolor: Color for infill...
0.003568
def dump(ra, from_date, with_json=True, latest_only=False, **kwargs): """Dump the remote accounts as a list of dictionaries. :param ra: Remote account to be dumped. :type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]` :returns: Remote accounts serialized to dictionary. :rtype: dict ...
0.002294
def on_config_value_changed(self, config_m, prop_name, info): """Callback when a config value has been changed :param ConfigModel config_m: The config model that has been changed :param str prop_name: Should always be 'config' :param dict info: Information e.g. about the changed config ...
0.006154
def get_mimetype(self, path): ''' Get mimetype of given path calling all registered mime functions (and default ones). :param path: filesystem path of file :type path: str :returns: mimetype :rtype: str ''' for fnc in self._mimetype_functions: ...
0.004598
def setup_opt_parser(): """ Setup the optparser @returns: opt_parser.OptionParser """ #pylint: disable-msg=C0301 #line too long usage = "usage: %prog [options]" opt_parser = optparse.OptionParser(usage=usage) opt_parser.add_option("--version", action='store_true', dest= ...
0.007262
def colorMap(value, name="jet", vmin=None, vmax=None): """Map a real value in range [vmin, vmax] to a (r,g,b) color scale. :param value: scalar value to transform into a color :type value: float, list :param name: color map name :type name: str, matplotlib.colors.LinearSegmentedColormap :retur...
0.003311
def get_context(self): """ Return the context used to render the templates for the email subject and body. By default, this context includes: * All of the validated values in the form, as variables of the same names as their fields. * The current ``Site`` obj...
0.002882
def _execute_model(self, feed_dict, out_dict): """ Executes model. :param feed_dict: Input dictionary mapping nodes to input data. :param out_dict: Output dictionary mapping names to nodes. :return: Dictionary mapping names to input data. """ network_out = self.se...
0.006536
def _D_constraint(self, neg_pairs, w): """Compute the value, 1st derivative, second derivative (Hessian) of a dissimilarity constraint function gF(sum_ij distance(d_ij A d_ij)) where A is a diagonal matrix (in the form of a column vector 'w'). """ diff = neg_pairs[:, 0, :] - neg_pairs[:, 1, :] d...
0.003953
def stop_recording(): """ Stops the global recording of events and returns a list of the events captured. """ global _recording if not _recording: raise ValueError('Must call "start_recording" before.') recorded_events_queue, hooked = _recording unhook(hooked) return list(rec...
0.002899
def is_class(data): """ checks that the data (which is a string, buffer, or a stream supporting the read method) has the magic numbers indicating it is a Java class file. Returns False if the magic numbers do not match, or for any errors. """ try: with unpack(data) as up: ...
0.002247
def unicode_symbol(self, *, invert_color: bool = False) -> str: """ Gets the Unicode character for the piece. """ symbol = self.symbol().swapcase() if invert_color else self.symbol() return UNICODE_PIECE_SYMBOLS[symbol]
0.007722
def project_geometry(geometry, crs, to_latlong=False): """ Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa Parameters ---------- geometry : shapely Polygon or MultiPolygon the geometry to project crs : int the starting coordinate reference system of th...
0.001138
def register(coordinator): """Registers this module as a worker with the given coordinator.""" if FLAGS.phantomjs_script: utils.verify_binary('phantomjs_binary', ['--version']) assert os.path.exists(FLAGS.phantomjs_script) else: utils.verify_binary('capture_binary', ['--version']) ...
0.00134
def match(self, passageId): """ Given a passageId matches a citation level :param passageId: A passage to match :return: """ if not isinstance(passageId, CtsReference): passageId = CtsReference(passageId) if self.is_root(): return self[passageId....
0.005405
def deactivate_(self): """Init shmem variables to None """ self.preDeactivate_() self.active = False self.image_dimensions = None self.client = None
0.010204
def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = '' for run in self.runs: chxmlstr += run.toxml() for record in self.records: chxmlstr += record.toxml() for event_record in self.event_records: c...
0.002571
def bootstrap_params(rv_cont, data, n_iter=5, **kwargs): """Bootstrap the fit params of a distribution. Parameters ========== rv_cont: scipy.stats.rv_continuous instance The distribution which to fit. data: array-like, 1d The data on which to fit. n_iter: int [default=10] ...
0.001832
def start(self): """ Starts the watchdog timer. """ self._timer = Timer(self.time, self.handler) self._timer.daemon = True self._timer.start() return
0.010582
def set_min_price(self, min_price): """ The minimum price. :param min_price: :return: """ if not isinstance(min_price, int): raise DaftException("Min price should be an integer.") self._min_price = str(min_price) self._price += str(QueryParam...
0.005731
async def send_message(self, chat_id: typing.Union[base.Integer, base.String], text: base.String, parse_mode: typing.Union[base.String, None] = None, disable_web_page_preview: typing.Union[base.Boolean, None] = None, disable_notification: ...
0.008203
def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) ...
0.002829
def _execute(params, cwd): """ Executes a subprocess :param params: A list of the executable and arguments to pass to it :param cwd: The working directory to execute the command in :return: A 2-element tuple of (stdout, stderr) """ proc = subprocess.Popen( ...
0.00295
def setpts(stream, expr): """Change the PTS (presentation timestamp) of the input frames. Args: expr: The expression which is evaluated for each frame to construct its timestamp. Official documentation: `setpts, asetpts <https://ffmpeg.org/ffmpeg-filters.html#setpts_002c-asetpts>`__ """ re...
0.007853
def notifyReady(self): """ Returns a deferred that will fire when the factory has created a protocol that can be used to communicate with a Mongo server. Note that this will not fire until we have connected to a Mongo master, unless slaveOk was specified in the M...
0.003247
def indent(text, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block): """Returns HTML as a basestring. Parameters ---------- text : basestring Source code, typically SHPAML, but could be a different (...
0.001965
def run_election_new_upsert_validator(args, bigchain): """Initiates an election to add/update/remove a validator to an existing BigchainDB network :param args: dict args = { 'public_key': the public key of the proposed peer, (str) 'power': the proposed validator power for the new peer, ...
0.004561
def invoked_with(self): """Similar to :attr:`Context.invoked_with` except properly handles the case where :meth:`Context.send_help` is used. If the help command was used regularly then this returns the :attr:`Context.invoked_with` attribute. Otherwise, if it the help command was...
0.003797
def on_load(target: "EncryptableMixin", context): """ Intercept SQLAlchemy's instance load event. """ decrypt, plaintext = decrypt_instance(target) if decrypt: target.plaintext = plaintext
0.004608