_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q13900
postprocess_html
train
def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" if metadata.get('build_lists') and metadata['build_lists'] == 'true': html = html.replace('<ul>', '<ul class="build">') html = html.replace('<ol>', '<ol class="build">') return html
python
{ "resource": "" }
q13901
suppress_message
train
def suppress_message(linter, checker_method, message_id_or_symbol, test_func): """ This wrapper allows the suppression of a message if the supplied test function returns True. It is useful to prevent one particular message from being raised in one particular case, while leaving the rest of the messages ...
python
{ "resource": "" }
q13902
SqliteStorage.lookup_full_hashes
train
def lookup_full_hashes(self, hash_values): """Query DB to see if hash is blacklisted""" q = '''SELECT threat_type,platform_type,threat_entry_type, expires_at < current_timestamp AS has_expired FROM full_hash WHERE value IN ({}) ''' output = [] with self.get_cursor...
python
{ "resource": "" }
q13903
SqliteStorage.store_full_hash
train
def store_full_hash(self, threat_list, hash_value, cache_duration, malware_threat_type): """Store full hash found for the given hash prefix""" log.info('Storing full hash %s to list %s with cache duration %s', to_hex(hash_value), str(threat_list), cache_duration) qi = '''INSERT ...
python
{ "resource": "" }
q13904
SqliteStorage.cleanup_full_hashes
train
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)): """Remove long expired full_hash entries.""" q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS') ''' log.info('Cleaning up full_hash entries expired more than {} seconds ago.'.format(ke...
python
{ "resource": "" }
q13905
SqliteStorage.get_threat_lists
train
def get_threat_lists(self): """Get a list of known threat lists.""" q = '''SELECT threat_type,platform_type,threat_entry_type FROM threat_list''' output = [] with self.get_cursor() as dbc: dbc.execute(q) for h in dbc.fetchall(): threat_type, platfo...
python
{ "resource": "" }
q13906
SqliteStorage.get_client_state
train
def get_client_state(self): """Get a dict of known threat lists including clientState values.""" q = '''SELECT threat_type,platform_type,threat_entry_type,client_state FROM threat_list''' output = {} with self.get_cursor() as dbc: dbc.execute(q) for h in dbc.fetch...
python
{ "resource": "" }
q13907
SqliteStorage.add_threat_list
train
def add_threat_list(self, threat_list): """Add threat list entry if it does not exist.""" q = '''INSERT OR IGNORE INTO threat_list (threat_type, platform_type, threat_entry_type, timestamp) VALUES (?, ?, ?, current_timestamp) ''' pa...
python
{ "resource": "" }
q13908
SqliteStorage.delete_threat_list
train
def delete_threat_list(self, threat_list): """Delete threat list entry.""" log.info('Deleting cached threat list "{}"'.format(repr(threat_list))) q = '''DELETE FROM threat_list WHERE threat_type=? AND platform_type=? AND threat_entry_type=? ''' params = [threa...
python
{ "resource": "" }
q13909
SqliteStorage.hash_prefix_list_checksum
train
def hash_prefix_list_checksum(self, threat_list): """Returns SHA256 checksum for alphabetically-sorted concatenated list of hash prefixes""" q = '''SELECT value FROM hash_prefix WHERE threat_type=? AND platform_type=? AND threat_entry_type=? ORDER BY value ''' ...
python
{ "resource": "" }
q13910
SqliteStorage.remove_hash_prefix_indices
train
def remove_hash_prefix_indices(self, threat_list, indices): """Remove records matching idices from a lexicographically-sorted local threat list.""" batch_size = 40 q = '''DELETE FROM hash_prefix WHERE threat_type=? AND platform_type=? AND threat_entry_type=? AND value IN ({}) ...
python
{ "resource": "" }
q13911
SqliteStorage.dump_hash_prefix_values
train
def dump_hash_prefix_values(self): """Export all hash prefix values. Returns a list of known hash prefix values """ q = '''SELECT distinct value from hash_prefix''' output = [] with self.get_cursor() as dbc: dbc.execute(q) output = [bytes(r[0]) fo...
python
{ "resource": "" }
q13912
_check_events
train
def _check_events(tk): """Checks events in the queue on a given Tk instance""" used = False try: # Process all enqueued events, then exit. while True: try: # Get an event request from the queue. method, args, kwargs, response_queue = tk.tk._event_...
python
{ "resource": "" }
q13913
SafeBrowsingList.update_hash_prefix_cache
train
def update_hash_prefix_cache(self): """Update locally cached threat lists.""" try: self.storage.cleanup_full_hashes() self.storage.commit() self._sync_threat_lists() self.storage.commit() self._sync_hash_prefix_cache() except Exception:...
python
{ "resource": "" }
q13914
SafeBrowsingList._sync_full_hashes
train
def _sync_full_hashes(self, hash_prefixes): """Download full hashes matching hash_prefixes. Also update cache expiration timestamps. """ client_state = self.storage.get_client_state() self.api_client.fair_use_delay() fh_response = self.api_client.get_full_hashes(hash_pre...
python
{ "resource": "" }
q13915
SafeBrowsingList.lookup_url
train
def lookup_url(self, url): """Look up specified URL in Safe Browsing threat lists.""" if type(url) is not str: url = url.encode('utf8') if not url.strip(): raise ValueError("Empty input string.") url_hashes = URL(url).hashes try: list_names = s...
python
{ "resource": "" }
q13916
SafeBrowsingList._lookup_hashes
train
def _lookup_hashes(self, full_hashes): """Lookup URL hash in blacklists Returns names of lists it was found in. """ full_hashes = list(full_hashes) cues = [fh[0:4] for fh in full_hashes] result = [] matching_prefixes = {} matching_full_hashes = set() ...
python
{ "resource": "" }
q13917
SafeBrowsingApiClient.get_threats_lists
train
def get_threats_lists(self): """Retrieve all available threat lists""" response = self.service.threatLists().list().execute() self.set_wait_duration(response.get('minimumWaitDuration')) return response['threatLists']
python
{ "resource": "" }
q13918
SafeBrowsingApiClient.get_threats_update
train
def get_threats_update(self, client_state): """Fetch hash prefixes update for given threat list. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
python
{ "resource": "" }
q13919
SafeBrowsingApiClient.get_full_hashes
train
def get_full_hashes(self, prefixes, client_state): """Find full hashes matching hash prefixes. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
python
{ "resource": "" }
q13920
URL.hashes
train
def hashes(self): """Hashes of all possible permutations of the URL in canonical form""" for url_variant in self.url_permutations(self.canonical): url_hash = self.digest(url_variant) yield url_hash
python
{ "resource": "" }
q13921
URL.canonical
train
def canonical(self): """Convert URL to its canonical form.""" def full_unescape(u): uu = urllib.unquote(u) if uu == u: return uu else: return full_unescape(uu) def full_unescape_to_bytes(u): uu = urlparse.unquote_to...
python
{ "resource": "" }
q13922
URL.url_permutations
train
def url_permutations(url): """Try all permutations of hostname and path which can be applied to blacklisted URLs """ def url_host_permutations(host): if re.match(r'\d+\.\d+\.\d+\.\d+', host): yield host return parts = host.split('....
python
{ "resource": "" }
q13923
_compare_versions
train
def _compare_versions(v1, v2): """ Compare two version strings and return -1, 0 or 1 depending on the equality of the subset of matching version numbers. The implementation is inspired by the top answer at http://stackoverflow.com/a/1714190/997768. """ def normalize(v): # strip trai...
python
{ "resource": "" }
q13924
exists
train
def exists(package): """ Return True if package information is available. If ``pkg-config`` not on path, raises ``EnvironmentError``. """ pkg_config_exe = os.environ.get('PKG_CONFIG', None) or 'pkg-config' cmd = '{0} --exists {1}'.format(pkg_config_exe, package).split() return call(cmd) == ...
python
{ "resource": "" }
q13925
libs
train
def libs(package, static=False): """ Return the LDFLAGS string returned by pkg-config. The static specifier will also include libraries for static linking (i.e., includes any private libraries). """ _raise_if_not_exists(package) return _query(package, *_build_options('--libs', static=static...
python
{ "resource": "" }
q13926
variables
train
def variables(package): """ Return a dictionary of all the variables defined in the .pc pkg-config file of 'package'. """ _raise_if_not_exists(package) result = _query(package, '--print-variables') names = (x.strip() for x in result.split('\n') if x != '') return dict(((x, _query(package...
python
{ "resource": "" }
q13927
installed
train
def installed(package, version): """ Check if the package meets the required version. The version specifier consists of an optional comparator (one of =, ==, >, <, >=, <=) and an arbitrarily long version number separated by dots. The should be as you would expect, e.g. for an installed version '0.1...
python
{ "resource": "" }
q13928
parse
train
def parse(packages, static=False): """ Parse the output from pkg-config about the passed package or packages. Builds a dictionary containing the 'libraries', the 'library_dirs', the 'include_dirs', and the 'define_macros' that are presented by pkg-config. *package* is a string with space-delimited ...
python
{ "resource": "" }
q13929
Connection.send
train
def send(self, data, sample_rate=None): '''Send the data over UDP while taking the sample_rate in account The sample rate should be a number between `0` and `1` which indicates the probability that a message will be sent. The sample_rate is also communicated to `statsd` so it knows what...
python
{ "resource": "" }
q13930
Timer.start
train
def start(self): '''Start the timer and store the start time, this can only be executed once per instance It returns the timer instance so it can be chained when instantiating the timer instance like this: ``timer = Timer('application_name').start()``''' assert self._sta...
python
{ "resource": "" }
q13931
Timer.intermediate
train
def intermediate(self, subname): '''Send the time that has passed since our last measurement :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' t = time.time() response = self.send(subname, t - self._last)...
python
{ "resource": "" }
q13932
Timer.decorate
train
def decorate(self, function_or_name): '''Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>>...
python
{ "resource": "" }
q13933
Timer.time
train
def time(self, subname=None, class_=None): '''Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Ti...
python
{ "resource": "" }
q13934
Gauge.increment
train
def increment(self, subname=None, delta=1): '''Increment the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to add to the gauge :type delta: int >>> gauge = Ga...
python
{ "resource": "" }
q13935
Gauge.decrement
train
def decrement(self, subname=None, delta=1): '''Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge...
python
{ "resource": "" }
q13936
Repo.aggregate
train
def aggregate(self): """ Aggregate all merges into the target branch If the target_dir doesn't exist, create an empty git repo otherwise clean it, add all remotes , and merge all merges. """ logger.info('Start aggregation of %s', self.cwd) target_dir = self.cwd i...
python
{ "resource": "" }
q13937
Repo._check_status
train
def _check_status(self): """Check repo status and except if dirty.""" logger.info('Checking repo status') status = self.log_call( ['git', 'status', '--porcelain'], callwith=subprocess.check_output, cwd=self.cwd, ) if status: raise D...
python
{ "resource": "" }
q13938
Repo._fetch_options
train
def _fetch_options(self, merge): """Get the fetch options from the given merge dict.""" cmd = tuple() for option in FETCH_DEFAULTS: value = merge.get(option, self.defaults.get(option)) if value: cmd += ("--%s" % option, str(value)) return cmd
python
{ "resource": "" }
q13939
Repo.collect_prs_info
train
def collect_prs_info(self): """Collect all pending merge PRs info. :returns: mapping of PRs by state """ REPO_RE = re.compile( '^(https://github.com/|git@github.com:)' '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$') PULL_RE = re.compile( '^(refs/)?pul...
python
{ "resource": "" }
q13940
Repo.show_closed_prs
train
def show_closed_prs(self): """Log only closed PRs.""" all_prs = self.collect_prs_info() for pr_info in all_prs.get('closed', []): logger.info( '{url} in state {state} ({merged})'.format(**pr_info) )
python
{ "resource": "" }
q13941
Repo.show_all_prs
train
def show_all_prs(self): """Log all PRs grouped by state.""" for __, prs in self.collect_prs_info().items(): for pr_info in prs: logger.info( '{url} in state {state} ({merged})'.format(**pr_info) )
python
{ "resource": "" }
q13942
load_config
train
def load_config(config, expand_env=False, force=False): """Return repos from a directory and fnmatch. Not recursive. :param config: paths to config file :type config: str :param expand_env: True to expand environment varialbes in the config. :type expand_env: bool :param bool force: True to agg...
python
{ "resource": "" }
q13943
main
train
def main(): """Main CLI application.""" parser = get_parser() argcomplete.autocomplete(parser, always_complete_options=False) args = parser.parse_args() setup_logger( level=args.log_level ) try: if args.config and \ args.command in \ ('agg...
python
{ "resource": "" }
q13944
aggregate_repo
train
def aggregate_repo(repo, args, sem, err_queue): """Aggregate one repo according to the args. Args: repo (Repo): The repository to aggregate. args (argparse.Namespace): CLI arguments. """ try: logger.debug('%s' % repo) dirmatch = args.dirmatch if not match_dir(r...
python
{ "resource": "" }
q13945
has_no_error
train
def has_no_error( state, incorrect_msg="Your code generated an error. Fix it and try again!" ): """Check whether the submission did not generate a runtime error. Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors. By default, after the entire SCT finished executing, ``...
python
{ "resource": "" }
q13946
has_ncols
train
def has_ncols( state, incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}.", ): """Test whether the student and solution query results have equal numbers of columns. Args: i...
python
{ "resource": "" }
q13947
check_row
train
def check_row(state, index, missing_msg=None, expand_msg=None): """Zoom in on a particular row in the query result, by index. After zooming in on a row, which is represented as a single-row query result, you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution query res...
python
{ "resource": "" }
q13948
check_column
train
def check_column(state, name, missing_msg=None, expand_msg=None): """Zoom in on a particular column in the query result, by name. After zooming in on a column, which is represented as a single-column query result, you can use ``has_equal_value()`` to verify whether the column in the solution query result ...
python
{ "resource": "" }
q13949
has_equal_value
train
def has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None): """Verify if a student and solution query result match up. This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result). ``has_equal_value`` then goes over all column...
python
{ "resource": "" }
q13950
check_query
train
def check_query(state, query, error_msg=None, expand_msg=None): """Run arbitrary queries against to the DB connection to verify the database state. For queries that do not return any output (INSERTs, UPDATEs, ...), you cannot use functions like ``check_col()`` and ``is_equal()`` to verify the query result....
python
{ "resource": "" }
q13951
lower_case
train
def lower_case(f): """Decorator specifically for turning mssql AST into lowercase""" # if it has already been wrapped, we return original if hasattr(f, "lower_cased"): return f @wraps(f) def wrapper(*args, **kwargs): f.lower_cased = True return f(*args, **kwargs).lower() ...
python
{ "resource": "" }
q13952
try_unbuffered_file
train
def try_unbuffered_file(file, _alreadyopen={}): """ Try re-opening a file in an unbuffered mode and return it. If that fails, just return the original file. This function remembers the file descriptors it opens, so it never opens the same one twice. This is meant for files like sys....
python
{ "resource": "" }
q13953
WriterProcessBase._loop
train
def _loop(self): """ This is the loop that runs in the subproces. It is called from `run` and is responsible for all printing, text updates, and time management. """ self.stop_flag.value = False self.time_started.value = time() self.time_elapsed.value = 0 ...
python
{ "resource": "" }
q13954
WriterProcessBase.run
train
def run(self): """ Runs the printer loop in a subprocess. This is called by multiprocessing. """ try: self._loop() except Exception: # Send the exception through the exc_queue, so the parent # process can check it. typ, val, tb ...
python
{ "resource": "" }
q13955
WriterProcessBase.stop
train
def stop(self): """ Stop this WriterProcessBase, and reset the cursor. """ self.stop_flag.value = True with self.lock: ( Control().text(C(' ', style='reset_all')) .pos_restore().move_column(1).erase_line() .write(self.file) ...
python
{ "resource": "" }
q13956
WriterProcessBase.update_text
train
def update_text(self): """ Write the current text, and check for any new text changes. This also updates the elapsed time. """ self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
python
{ "resource": "" }
q13957
WriterProcessBase.write
train
def write(self): """ Write the current text to self.file, and flush it. This can be overridden to handle custom writes. """ if self._text is not None: with self.lock: self.file.write(str(self._text).encode()) self.file.flush() sleep...
python
{ "resource": "" }
q13958
WriterProcess.exception
train
def exception(self): """ Try retrieving the last subprocess exception. If set, the exception is returned. Otherwise None is returned. """ if self._exception is not None: return self._exception try: exc, tblines = self.exc_queue.get_nowait() exc...
python
{ "resource": "" }
q13959
StaticProgress.fmt
train
def fmt(self, value): """ Sets self.fmt, with some extra help for plain format strings. """ if isinstance(value, str): value = value.split(self.join_str) if not (value and isinstance(value, (list, tuple))): raise TypeError( ' '.join(( '...
python
{ "resource": "" }
q13960
StaticProgress.run
train
def run(self): """ Overrides WriterProcess.run, to handle KeyboardInterrupts better. This should not be called by any user. `multiprocessing` calls this in a subprocess. Use `self.start` to start this instance. """ try: Control().cursor_hide().writ...
python
{ "resource": "" }
q13961
StaticProgress.stop
train
def stop(self): """ Stop this animated progress, and block until it is finished. """ super().stop() while not self.stopped: # stop() should block, so printing afterwards isn't interrupted. sleep(0.001) # Retrieve the latest exception, if any. exc = self.ex...
python
{ "resource": "" }
q13962
StaticProgress.write
train
def write(self): """ Writes a single frame of the progress spinner to the terminal. This function updates the current frame before returning. """ if self.text is None: # Text has not been sent through the pipe yet. # Do not write anything until it is set to no...
python
{ "resource": "" }
q13963
AnimatedProgress._advance_frame
train
def _advance_frame(self): """ Sets `self.current_frame` to the next frame, looping to the beginning if needed. """ self.current_frame += 1 if self.current_frame == self.frame_len: self.current_frame = 0
python
{ "resource": "" }
q13964
AnimatedProgress.write_char_delay
train
def write_char_delay(self, ctl, delay): """ Write the formatted format pieces in order, applying a delay between characters for the text only. """ for i, fmt in enumerate(self.fmt): if '{text' in fmt: # The text will use a write delay. ctl....
python
{ "resource": "" }
q13965
ProgressBar.update
train
def update(self, percent=None, text=None): """ Update the progress bar percentage and message. """ if percent is not None: self.percent = percent if text is not None: self.message = text super().update()
python
{ "resource": "" }
q13966
cls_get_by_name
train
def cls_get_by_name(cls, name): """ Return a class attribute by searching the attributes `name` attribute. """ try: val = getattr(cls, name) except AttributeError: for attr in (a for a in dir(cls) if not a.startswith('_')): try: val = getattr(cls, attr) ...
python
{ "resource": "" }
q13967
cls_names
train
def cls_names(cls, wanted_cls, registered=True): """ Return a list of attributes for all `wanted_cls` attributes in this class, where `wanted_cls` is the desired attribute type. """ return [ fset.name for fset in cls_sets(cls, wanted_cls, registered=registered) ]
python
{ "resource": "" }
q13968
cls_sets
train
def cls_sets(cls, wanted_cls, registered=True): """ Return a list of all `wanted_cls` attributes in this class, where `wanted_cls` is the desired attribute type. """ sets = [] for attr in dir(cls): if attr.startswith('_'): continue val = getattr(cls, attr, None) ...
python
{ "resource": "" }
q13969
_build_color_variants
train
def _build_color_variants(cls): """ Build colorized variants of all frames and return a list of all frame object names. """ # Get the basic frame types first. frametypes = cls.sets(registered=False) _colornames = [ # 'black', disabled for now, it won't show on my terminal. '...
python
{ "resource": "" }
q13970
FrameSet.from_barset
train
def from_barset( cls, barset, name=None, delay=None, use_wrapper=True, wrapper=None): """ Copy a BarSet's frames to create a new FrameSet. Arguments: barset : An existing BarSet object to copy frames from. name : A name for the new...
python
{ "resource": "" }
q13971
BarSet.as_rainbow
train
def as_rainbow(self, offset=35, style=None, rgb_mode=False): """ Wrap each frame in a Colr object, using `Colr.rainbow`. """ return self._as_rainbow( ('wrapper', ), offset=offset, style=style, rgb_mode=rgb_mode, )
python
{ "resource": "" }
q13972
BarSet._generate_move
train
def _generate_move( cls, char, width=None, fill_char=None, bounce=False, reverse=True, back_char=None): """ Yields strings that simulate movement of a character from left to right. For use with `BarSet.from_char`. Arguments: char : Charac...
python
{ "resource": "" }
q13973
BaseTransport.set_write_buffer_limits
train
def set_write_buffer_limits(self, high=None, low=None): """Set the low and high watermark for the write buffer.""" if high is None: high = self.write_buffer_size if low is None: low = high // 2 if low > high: low = high self._write_buffer_high ...
python
{ "resource": "" }
q13974
BaseTransport.close
train
def close(self): """Close the transport after all oustanding data has been written.""" if self._closing or self._handle.closed: return elif self._protocol is None: raise TransportError('transport not started') # If the write buffer is empty, close now. Otherwise d...
python
{ "resource": "" }
q13975
BaseTransport.abort
train
def abort(self): """Close the transport immediately.""" if self._handle.closed: return elif self._protocol is None: raise TransportError('transport not started') self._handle.close(self._on_close_complete) assert self._handle.closed
python
{ "resource": "" }
q13976
Transport.write_eof
train
def write_eof(self): """Shut down the write direction of the transport.""" self._check_status() if not self._writable: raise TransportError('transport is not writable') if self._closing: raise TransportError('transport is closing') try: self._h...
python
{ "resource": "" }
q13977
Transport.get_extra_info
train
def get_extra_info(self, name, default=None): """Get transport specific data. In addition to the fields from :meth:`BaseTransport.get_extra_info`, the following information is also available: ===================== =================================================== Name ...
python
{ "resource": "" }
q13978
parse_dbus_address
train
def parse_dbus_address(address): """Parse a D-BUS address string into a list of addresses.""" if address == 'session': address = os.environ.get('DBUS_SESSION_BUS_ADDRESS') if not address: raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set') elif address == 'system': addr...
python
{ "resource": "" }
q13979
parse_dbus_header
train
def parse_dbus_header(header): """Parse a D-BUS header. Return the message size.""" if six.indexbytes(header, 0) == ord('l'): endian = '<' elif six.indexbytes(header, 0) == ord('B'): endian = '>' else: raise ValueError('illegal endianness') if not 1 <= six.indexbytes(header, ...
python
{ "resource": "" }
q13980
TxdbusAuthenticator.getMechanismName
train
def getMechanismName(self): """Return the authentication mechanism name.""" if self._server_side: mech = self._authenticator.current_mech return mech.getMechanismName() if mech else None else: return getattr(self._authenticator, 'authMech', None)
python
{ "resource": "" }
q13981
DbusProtocol.get_unique_name
train
def get_unique_name(self): """Return the unique name of the D-BUS connection.""" self._name_acquired.wait() if self._error: raise compat.saved_exc(self._error) elif self._transport is None: raise DbusError('not connected') return self._unique_name
python
{ "resource": "" }
q13982
DbusProtocol.send_message
train
def send_message(self, message): """Send a D-BUS message. The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance. """ if not isinstance(message, txdbus.DbusMessage): raise TypeError('message: expecting DbusMessage instance (got {!r})', ...
python
{ "resource": "" }
q13983
DbusProtocol.call_method
train
def call_method(self, service, path, interface, method, signature=None, args=None, no_reply=False, auto_start=False, timeout=-1): """Call a D-BUS method and wait for its reply. This method calls the D-BUS method with name *method* that resides on the object at bus address *s...
python
{ "resource": "" }
q13984
docfrom
train
def docfrom(base): """Decorator to set a function's docstring from another function.""" def setdoc(func): func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '') return func return setdoc
python
{ "resource": "" }
q13985
objref
train
def objref(obj): """Return a string that uniquely and compactly identifies an object.""" ref = _objrefs.get(obj) if ref is None: clsname = obj.__class__.__name__.split('.')[-1] seqno = _lastids.setdefault(clsname, 1) ref = '{}-{}'.format(clsname, seqno) _objrefs[obj] = ref ...
python
{ "resource": "" }
q13986
delegate_method
train
def delegate_method(other, method, name=None): """Add a method to the current class that delegates to another method. The *other* argument must be a property that returns the instance to delegate to. Due to an implementation detail, the property must be defined in the current class. The *method* argume...
python
{ "resource": "" }
q13987
accept_ws
train
def accept_ws(buf, pos): """Skip whitespace at the current buffer position.""" match = re_ws.match(buf, pos) if not match: return None, pos return buf[match.start(0):match.end(0)], match.end(0)
python
{ "resource": "" }
q13988
accept_lit
train
def accept_lit(char, buf, pos): """Accept a literal character at the current buffer position.""" if pos >= len(buf) or buf[pos] != char: return None, pos return char, pos+1
python
{ "resource": "" }
q13989
expect_lit
train
def expect_lit(char, buf, pos): """Expect a literal character at the current buffer position.""" if pos >= len(buf) or buf[pos] != char: return None, len(buf) return char, pos+1
python
{ "resource": "" }
q13990
accept_re
train
def accept_re(regexp, buf, pos): """Accept a regular expression at the current buffer position.""" match = regexp.match(buf, pos) if not match: return None, pos return buf[match.start(1):match.end(1)], match.end(0)
python
{ "resource": "" }
q13991
expect_re
train
def expect_re(regexp, buf, pos): """Require a regular expression at the current buffer position.""" match = regexp.match(buf, pos) if not match: return None, len(buf) return buf[match.start(1):match.end(1)], match.end(0)
python
{ "resource": "" }
q13992
parse_content_type
train
def parse_content_type(header): """Parse the "Content-Type" header.""" typ = subtyp = None; options = {} typ, pos = expect_re(re_token, header, 0) _, pos = expect_lit('/', header, pos) subtyp, pos = expect_re(re_token, header, pos) ctype = header[:pos] if subtyp else '' while pos < len(heade...
python
{ "resource": "" }
q13993
parse_te
train
def parse_te(header): """Parse the "TE" header.""" pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) _, pos = accept_ws(header, pos) _, pos = accept_lit(';', header, pos) _, pos = accept_ws(header, pos) qvalue, pos = accept_r...
python
{ "resource": "" }
q13994
parse_trailer
train
def parse_trailer(header): """Parse the "Trailer" header.""" pos = 0 names = [] while pos < len(header): name, pos = expect_re(re_token, header, pos) if name: names.append(name) _, pos = accept_ws(header, pos) _, pos = expect_lit(',', header, pos) _, p...
python
{ "resource": "" }
q13995
parse_url
train
def parse_url(url, default_scheme='http', is_connect=False): """Parse an URL and return its components. The *default_scheme* argument specifies the scheme in case URL is an otherwise valid absolute URL but with a missing scheme. The *is_connect* argument must be set to ``True`` if the URL was requeste...
python
{ "resource": "" }
q13996
create_chunk
train
def create_chunk(buf): """Create a chunk for the HTTP "chunked" transfer encoding.""" chunk = [] chunk.append(s2b('{:X}\r\n'.format(len(buf)))) chunk.append(buf) chunk.append(b'\r\n') return b''.join(chunk)
python
{ "resource": "" }
q13997
create_chunked_body_end
train
def create_chunked_body_end(trailers=None): """Create the ending that terminates a chunked body.""" chunk = [] chunk.append('0\r\n') if trailers: for name, value in trailers: chunk.append(name) chunk.append(': ') chunk.append(value) chunk.append('\...
python
{ "resource": "" }
q13998
create_request
train
def create_request(version, method, url, headers): """Create a HTTP request header.""" # According to my measurements using b''.join is faster that constructing a # bytearray. message = [] message.append('{} {} HTTP/{}\r\n'.format(method, url, version)) for name, value in headers: messag...
python
{ "resource": "" }
q13999
create_response
train
def create_response(version, status, headers): """Create a HTTP response header.""" message = [] message.append('HTTP/{} {}\r\n'.format(version, status)) for name, value in headers: message.append(name) message.append(': ') message.append(value) message.append('\r\n') ...
python
{ "resource": "" }