_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q239400
stop
train
def stop(state, host, ctid): ''' Stop OpenVZ containers. + ctid: CTID of the container to stop ''' args = ['{0}'.format(ctid)] yield 'vzctl stop {0}'.format(' '.join(args))
python
{ "resource": "" }
q239401
restart
train
def restart(state, host, ctid, force=False): ''' Restart OpenVZ containers. + ctid: CTID of the container to restart + force: whether to force container start ''' yield stop(state, host, ctid) yield start(state, host, ctid, force=force)
python
{ "resource": "" }
q239402
create
train
def create(state, host, ctid, template=None): ''' Create OpenVZ containers. + ctid: CTID of the container to create ''' # Check we don't already have a container with this CTID current_containers = host.fact.openvz_containers if ctid in current_containers: raise OperationError( ...
python
{ "resource": "" }
q239403
set
train
def set(state, host, ctid, save=True, **settings): ''' Set OpenVZ container details. + ctid: CTID of the container to set + save: whether to save the changes + settings: settings/arguments to apply to the container Settings/arguments: these are mapped directly to ``vztctl`` arguments, ...
python
{ "resource": "" }
q239404
exec_file
train
def exec_file(filename, return_locals=False, is_deploy_code=False): ''' Execute a Python file and optionally return it's attributes as a dict. ''' if filename not in PYTHON_CODES: with open(filename, 'r') as f: code = f.read() code = compile(code, filename, 'exec') ...
python
{ "resource": "" }
q239405
shell
train
def shell(state, host, commands, chdir=None): ''' Run raw shell code. + commands: command or list of commands to execute on the remote server + chdir: directory to cd into before executing commands ''' # Ensure we have a list if isinstance(commands, six.string_types): commands = [c...
python
{ "resource": "" }
q239406
script
train
def script(state, host, filename, chdir=None): ''' Upload and execute a local script on the remote host. + filename: local script filename to upload & execute + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(filename) yield files.put(state, ...
python
{ "resource": "" }
q239407
script_template
train
def script_template(state, host, template_filename, chdir=None, **data): ''' Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_fil...
python
{ "resource": "" }
q239408
hostname
train
def hostname(state, host, hostname, hostname_file=None): ''' Set the system hostname. + hostname: the hostname that should be set + hostname_file: the file that permanently sets the hostname Hostname file: By default pyinfra will auto detect this by targetting ``/etc/hostname`` on ...
python
{ "resource": "" }
q239409
sysctl
train
def sysctl( state, host, name, value, persist=False, persist_file='/etc/sysctl.conf', ): ''' Edit sysctl configuration. + name: name of the sysctl setting to ensure + value: the value or list of values the sysctl should be + persist: whether to write this sysctl to the config + persist_...
python
{ "resource": "" }
q239410
download
train
def download( state, host, source_url, destination, user=None, group=None, mode=None, cache_time=None, force=False, ): ''' Download files from remote locations. + source_url: source URl of the file + destination: where to save the file + user: user to own the files + group: group to own...
python
{ "resource": "" }
q239411
replace
train
def replace(state, host, name, match, replace, flags=None): ''' A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed ''' yield sed_replace(name,...
python
{ "resource": "" }
q239412
sync
train
def sync( state, host, source, destination, user=None, group=None, mode=None, delete=False, exclude=None, exclude_dir=None, add_deploy_dir=True, ): ''' Syncs a local directory with a remote one, with delete support. Note that delete will remove extra files on the remote side, but not extra direc...
python
{ "resource": "" }
q239413
put
train
def put( state, host, local_filename, remote_filename, user=None, group=None, mode=None, add_deploy_dir=True, ): ''' Copy a local file to the remote system. + local_filename: local filename + remote_filename: remote filename + user: user to own the files + group: group to own the files ...
python
{ "resource": "" }
q239414
template
train
def template( state, host, template_filename, remote_filename, user=None, group=None, mode=None, **data ): ''' Generate a template and write it to the remote system. + template_filename: local template filename + remote_filename: remote filename + user: user to own the files + group: gr...
python
{ "resource": "" }
q239415
sql
train
def sql( state, host, sql, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Execute arbitrary SQL against PostgreSQL. + sql: SQL command(s) to execute + database: opt...
python
{ "resource": "" }
q239416
dump
train
def dump( state, host, remote_filename, database=None, # Details for speaking to PostgreSQL via `psql` CLI postgresql_user=None, postgresql_password=None, postgresql_host=None, postgresql_port=None, ): ''' Dump a PostgreSQL database into a ``.sql`` file. Requires ``mysqldump``. + databa...
python
{ "resource": "" }
q239417
get_fact
train
def get_fact(state, host, name): ''' Wrapper around ``get_facts`` returning facts for one host or a function that does. ''' # Expecting a function to return if callable(getattr(FACTS[name], 'command', None)): def wrapper(*args): fact_data = get_facts(state, name, args=args, ...
python
{ "resource": "" }
q239418
key
train
def key(state, host, key=None, keyserver=None, keyid=None): ''' Add apt gpg keys with ``apt-key``. + key: filename or URL + keyserver: URL of keyserver to fetch key from + keyid: key identifier when using keyserver Note: Always returns an add command, not state checking. keyserver...
python
{ "resource": "" }
q239419
update
train
def update(state, host, cache_time=None, touch_periodic=False): ''' Updates apt repos. + cache_time: cache updates for this many seconds + touch_periodic: touch ``/var/lib/apt/periodic/update-success-stamp`` after update ''' # If cache_time check when apt was last updated, prevent updates if w...
python
{ "resource": "" }
q239420
run_shell_command
train
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the local machine. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target ...
python
{ "resource": "" }
q239421
upstart
train
def upstart( state, host, name, running=True, restarted=False, reloaded=False, command=None, enabled=None, ): ''' Manage the state of upstart managed services. + name: name of the service to manage + running: whether the service should be running + restarted: whether the service should ...
python
{ "resource": "" }
q239422
service
train
def service( state, host, *args, **kwargs ): ''' Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments. ''' if host.fact.which('systemctl'): ...
python
{ "resource": "" }
q239423
connect
train
def connect(state, host, for_fact=None): ''' Connect to a single host. Returns the SSH client if succesful. Stateless by design so can be run in parallel. ''' kwargs = _make_paramiko_kwargs(state, host) logger.debug('Connecting to: {0} ({1})'.format(host.name, kwargs)) # Hostname can be pr...
python
{ "resource": "" }
q239424
run_shell_command
train
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the specified host. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target ...
python
{ "resource": "" }
q239425
put_file
train
def put_file( state, host, filename_or_io, remote_filename, sudo=False, sudo_user=None, su_user=None, print_output=False, ): ''' Upload file-ios to the specified host using SFTP. Supports uploading files with sudo by uploading to a temporary directory then moving & chowning. ''' # sudo/su a...
python
{ "resource": "" }
q239426
State.deploy
train
def deploy(self, name, kwargs, data, line_number, in_deploy=True): ''' Wraps a group of operations as a deploy, this should not be used directly, instead use ``pyinfra.api.deploy.deploy``. ''' # Handle nested deploy names if self.deploy_name: name = _make_nam...
python
{ "resource": "" }
q239427
State.activate_host
train
def activate_host(self, host): ''' Flag a host as active. ''' logger.debug('Activating host: {0}'.format(host)) # Add to *both* activated and active - active will reduce as hosts fail # but connected will not, enabling us to track failed %. self.activated_hosts....
python
{ "resource": "" }
q239428
State.fail_hosts
train
def fail_hosts(self, hosts_to_fail, activated_count=None): ''' Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``. ''' if not hosts_to_fail: return activated_count = activated_count or len(self.activated_hosts) logger.debug('Failing hosts:...
python
{ "resource": "" }
q239429
State.is_host_in_limit
train
def is_host_in_limit(self, host): ''' Returns a boolean indicating if the host is within the current state limit. ''' limit_hosts = self.limit_hosts if not isinstance(limit_hosts, list): return True return host in limit_hosts
python
{ "resource": "" }
q239430
State.get_temp_filename
train
def get_temp_filename(self, hash_key=None): ''' Generate a temporary filename for this deploy. ''' if not hash_key: hash_key = six.text_type(uuid4()) temp_filename = '{0}/{1}'.format( self.config.TEMP_DIR, sha1_hash(hash_key), ) return t...
python
{ "resource": "" }
q239431
_run_server_ops
train
def _run_server_ops(state, host, progress=None): ''' Run all ops for a single server. ''' logger.debug('Running all ops on {0}'.format(host)) for op_hash in state.get_op_order(): op_meta = state.op_meta[op_hash] logger.info('--> {0} {1} on {2}'.format( click.style('-->...
python
{ "resource": "" }
q239432
_run_serial_ops
train
def _run_serial_ops(state): ''' Run all ops for all servers, one server at a time. ''' for host in list(state.inventory): host_operations = product([host], state.get_op_order()) with progress_spinner(host_operations) as progress: try: _run_server_ops( ...
python
{ "resource": "" }
q239433
_run_no_wait_ops
train
def _run_no_wait_ops(state): ''' Run all ops for all servers at once. ''' hosts_operations = product(state.inventory, state.get_op_order()) with progress_spinner(hosts_operations) as progress: # Spawn greenlet for each host to run *all* ops greenlets = [ state.pool.spawn...
python
{ "resource": "" }
q239434
_run_single_op
train
def _run_single_op(state, op_hash): ''' Run a single operation for all servers. Can be configured to run in serial. ''' op_meta = state.op_meta[op_hash] op_types = [] if op_meta['serial']: op_types.append('serial') if op_meta['run_once']: op_types.append('run once') ...
python
{ "resource": "" }
q239435
run_ops
train
def run_ops(state, serial=False, no_wait=False): ''' Runs all operations across all servers in a configurable manner. Args: state (``pyinfra.api.State`` obj): the deploy state to execute serial (boolean): whether to run operations host by host no_wait (boolean): whether to wait for ...
python
{ "resource": "" }
q239436
serve
train
def serve(service_brokers: Union[List[ServiceBroker], ServiceBroker], credentials: Union[List[BrokerCredentials], BrokerCredentials, None], logger: logging.Logger = logging.root, port=5000, debug=False): """ Starts flask with the given brokers. You can provide a list ...
python
{ "resource": "" }
q239437
multi_ping
train
def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False): """ Combine send and receive measurement into single function. This offers a retry mechanism: Overall timeout time is divided by number of retries. Additional ICMPecho packets are sent to those addresses from which we have no...
python
{ "resource": "" }
q239438
MultiPing._checksum
train
def _checksum(self, msg): """ Calculate the checksum of a packet. This is inspired by a response on StackOverflow here: https://stackoverflow.com/a/1769267/7242672 Thank you to StackOverflow user Jason Orendorff. """ def carry_around_add(a, b): c = ...
python
{ "resource": "" }
q239439
MultiPing.send
train
def send(self): """ Send pings to multiple addresses, ensuring unique IDs for each request. This operation is non-blocking. Use 'receive' to get the results. Send can be called multiple times. If there are any addresses left from the previous send, from which results have not b...
python
{ "resource": "" }
q239440
MultiPing._read_all_from_socket
train
def _read_all_from_socket(self, timeout): """ Read all packets we currently can on the socket. Returns list of tuples. Each tuple contains a packet and the time at which it was received. NOTE: The receive time is the time when our recv() call returned, which greatly depends on w...
python
{ "resource": "" }
q239441
GasDetector.get
train
async def get(self): """Get current state from the Midas gas detector.""" try: return self._parse(await self.read_registers(0, 16)) except TimeoutError: return {'ip': self.ip, 'connected': False}
python
{ "resource": "" }
q239442
GasDetector._parse
train
def _parse(self, registers): """Parse the response, returning a dictionary.""" result = {'ip': self.ip, 'connected': True} decoder = BinaryPayloadDecoder.fromRegisters(registers, byteorder=Endian.Big, ...
python
{ "resource": "" }
q239443
AsyncioModbusClient._connect
train
async def _connect(self): """Start asynchronous reconnect loop.""" self.waiting = True await self.client.start(self.ip) self.waiting = False if self.client.protocol is None: raise IOError("Could not connect to '{}'.".format(self.ip)) self.open = True
python
{ "resource": "" }
q239444
AsyncioModbusClient.read_registers
train
async def read_registers(self, address, count): """Read modbus registers. The Modbus protocol doesn't allow responses longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests. """ registers = [] while cou...
python
{ "resource": "" }
q239445
AsyncioModbusClient.write_register
train
async def write_register(self, address, value, skip_encode=False): """Write a modbus register.""" await self._request('write_registers', address, value, skip_encode=skip_encode)
python
{ "resource": "" }
q239446
AsyncioModbusClient.write_registers
train
async def write_registers(self, address, values, skip_encode=False): """Write modbus registers. The Modbus protocol doesn't allow requests longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests. """ while len(v...
python
{ "resource": "" }
q239447
AsyncioModbusClient._request
train
async def _request(self, method, *args, **kwargs): """Send a request to the device and awaits a response. This mainly ensures that requests are sent serially, as the Modbus protocol does not allow simultaneous requests (it'll ignore any request sent while it's processing something). The...
python
{ "resource": "" }
q239448
AsyncioModbusClient._close
train
def _close(self): """Close the TCP connection.""" self.client.stop() self.open = False self.waiting = False
python
{ "resource": "" }
q239449
command_line
train
def command_line(): """Command-line tool for Midas gas detector communication.""" import argparse import asyncio import json parser = argparse.ArgumentParser(description="Read a Honeywell Midas gas " "detector state from the command line.") parser.add_argume...
python
{ "resource": "" }
q239450
build_masked_loss
train
def build_masked_loss(loss_function, mask_value): """Builds a loss function that masks based on targets Args: loss_function: The loss function to mask mask_value: The value to mask in the targets Returns: function: a loss function that acts like loss_function with masked inputs ...
python
{ "resource": "" }
q239451
ProgramInfo.Run
train
def Run(self): """Run it and collect output. Returns: 1 (true) If everything went well. 0 (false) If there were problems. """ if not self.executable: logging.error('Could not locate "%s"' % self.long_name) return 0 finfo = os.stat(self.executable) self.date = time.lo...
python
{ "resource": "" }
q239452
ProgramInfo.Parse
train
def Parse(self): """Parse program output.""" (start_line, lang) = self.ParseDesc() if start_line < 0: return if 'python' == lang: self.ParsePythonFlags(start_line) elif 'c' == lang: self.ParseCFlags(start_line) elif 'java' == lang: self.ParseJavaFlags(start_line)
python
{ "resource": "" }
q239453
ProgramInfo.ParseDesc
train
def ParseDesc(self, start_line=0): """Parse the initial description. This could be Python or C++. Returns: (start_line, lang_type) start_line Line to start parsing flags on (int) lang_type Either 'python' or 'c' (-1, '') if the flags start could not be found """ ex...
python
{ "resource": "" }
q239454
ProgramInfo.ParseCFlags
train
def ParseCFlags(self, start_line=0): """Parse C style flags.""" modname = None # name of current module modlist = [] flag = None for line_num in range(start_line, len(self.output)): # collect flags line = self.output[line_num].rstrip() if not line: ...
python
{ "resource": "" }
q239455
ProgramInfo.Filter
train
def Filter(self): """Filter parsed data to create derived fields.""" if not self.desc: self.short_desc = '' return for i in range(len(self.desc)): # replace full path with name if self.desc[i].find(self.executable) >= 0: self.desc[i] = self.desc[i].replace(self.executable, self....
python
{ "resource": "" }
q239456
GenerateDoc.Output
train
def Output(self): """Output all sections of the page.""" self.Open() self.Header() self.Body() self.Footer()
python
{ "resource": "" }
q239457
GetFlagSuggestions
train
def GetFlagSuggestions(attempt, longopt_list): """Get helpful similar matches for an invalid flag.""" # Don't suggest on very short strings, or if no longopts are specified. if len(attempt) <= 2 or not longopt_list: return [] option_names = [v.split('=')[0] for v in longopt_list] # Find close approximat...
python
{ "resource": "" }
q239458
_DamerauLevenshtein
train
def _DamerauLevenshtein(a, b): """Damerau-Levenshtein edit distance from a to b.""" memo = {} def Distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min(...
python
{ "resource": "" }
q239459
FlagDictToArgs
train
def FlagDictToArgs(flag_map): """Convert a dict of values into process call parameters. This method is used to convert a dictionary into a sequence of parameters for a binary that parses arguments using this module. Args: flag_map: a mapping where the keys are flag names (strings). values are treate...
python
{ "resource": "" }
q239460
define_both_methods
train
def define_both_methods(class_name, class_dict, old_name, new_name): # pylint: disable=invalid-name """Function to help CamelCase to PEP8 style class methods migration. For any class definition: 1. Assert it does not define both old and new methods, otherwise it does not work. 2. If it define...
python
{ "resource": "" }
q239461
FlagValues._IsUnparsedFlagAccessAllowed
train
def _IsUnparsedFlagAccessAllowed(self, name): """Determine whether to allow unparsed flag access or not.""" if _UNPARSED_FLAG_ACCESS_ENV_NAME in os.environ: # We've been told explicitly what to do. allow_unparsed_flag_access = ( os.getenv(_UNPARSED_FLAG_ACCESS_ENV_NAME) == '1') elif se...
python
{ "resource": "" }
q239462
FlagValues._AssertValidators
train
def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existi...
python
{ "resource": "" }
q239463
FlagValues._RemoveAllFlagAppearances
train
def _RemoveAllFlagAppearances(self, name): """Removes flag with name for all appearances. A flag can be registered with its long name and an optional short name. This method removes both of them. This is different than __delattr__. Args: name: Either flag's long name or short name. Raises: ...
python
{ "resource": "" }
q239464
FlagValues.GetHelp
train
def GetHelp(self, prefix='', include_special_flags=True): """Generates a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of _SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatt...
python
{ "resource": "" }
q239465
FlagValues.__RenderOurModuleKeyFlags
train
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. ...
python
{ "resource": "" }
q239466
FlagValues.ModuleHelp
train
def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist)
python
{ "resource": "" }
q239467
register_multi_flags_validator
train
def register_multi_flags_validator(flag_names, multi_flags_checker, message='Flags validation failed', flag_values=FLAGS): """Adds a constraint to multiple flags. The constraint is validated when flags are init...
python
{ "resource": "" }
q239468
multi_flags_validator
train
def multi_flags_validator(flag_names, message='Flag validation failed', flag_values=FLAGS): """A function decorator for defining a multi-flag validator. Registers the decorated function as a validator for flag_names, e.g. @gflags.multi_flags_validator(['foo', ...
python
{ "resource": "" }
q239469
mark_flag_as_required
train
def mark_flag_as_required(flag_name, flag_values=FLAGS): """Ensures that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Important note: validator will pass for any non-None value, such as False, 0 (zero), '' (empty string) and so on. It is rec...
python
{ "resource": "" }
q239470
mark_flags_as_mutual_exclusive
train
def mark_flags_as_mutual_exclusive(flag_names, required=False, flag_values=FLAGS): """Ensures that only one flag among flag_names is set. Args: flag_names: [str], a list of the flag names to be checked. required: Boolean, if set, exactly one of the flags must be set. ...
python
{ "resource": "" }
q239471
DEFINE_enum
train
def DEFINE_enum( # pylint: disable=g-bad-name,redefined-builtin name, default, enum_values, help, flag_values=FLAGS, module_name=None, **args): """Registers a flag whose value can be any string from enum_values. Args: name: A string, the flag name. default: The default value of the flag. enum_...
python
{ "resource": "" }
q239472
DEFINE_list
train
def DEFINE_list( # pylint: disable=g-bad-name,redefined-builtin name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings. The flag value is parsed with a CSV parser. Args: name: A string, the flag name. default: The default value of the f...
python
{ "resource": "" }
q239473
DEFINE_multi
train
def DEFINE_multi( # pylint: disable=g-bad-name,redefined-builtin parser, serializer, name, default, help, flag_values=FLAGS, module_name=None, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who...
python
{ "resource": "" }
q239474
DEFINE_multi_float
train
def DEFINE_multi_float( # pylint: disable=g-bad-name,redefined-builtin name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values in...
python
{ "resource": "" }
q239475
DEFINE_alias
train
def DEFINE_alias(name, original_name, flag_values=FLAGS, module_name=None): # pylint: disable=g-bad-name """Defines an alias flag for an existing one. Args: name: A string, name of the alias flag. original_name: A string, name of the original flag. flag_values: FlagValues object with which the flag wi...
python
{ "resource": "" }
q239476
DuplicateFlagError.from_flag
train
def from_flag(cls, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError by providing flag name and values. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If th...
python
{ "resource": "" }
q239477
BooleanParser.convert
train
def convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if isinstance(argument, str): if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) i...
python
{ "resource": "" }
q239478
EnumParser.parse
train
def parse(self, argument): """Determine validity of argument and return the correct element of enum. If self.enum_values is empty, then all arguments are valid and argument will be returned. Otherwise, if argument matches an element in enum, then the first matching element will be returned. A...
python
{ "resource": "" }
q239479
CsvListSerializer.serialize
train
def serialize(self, value): """Serialize a list as a string, if possible, or as a unicode string.""" if six.PY2: # In Python2 csv.writer doesn't accept unicode, so we convert to UTF-8. output = io.BytesIO() csv.writer(output).writerow([unicode(x).encode('utf-8') for x in value]) serializ...
python
{ "resource": "" }
q239480
Meter.record
train
def record(self): """ Record PyAudio stream into StringIO output This coroutine keeps stream open; the stream is closed in stop() """ while True: frames = [] self.stream.start_stream() for i in range(self.num_frames): data = s...
python
{ "resource": "" }
q239481
Meter.stop
train
def stop(self): """Stop the stream and terminate PyAudio""" self.prestop() if not self._graceful: self._graceful = True self.stream.stop_stream() self.audio.terminate() msg = 'Stopped' self.verbose_info(msg, log=False) # Log 'Stopped' anyway ...
python
{ "resource": "" }
q239482
Meter.get_threshold
train
def get_threshold(self): """Get and validate raw RMS value from threshold""" if self.threshold.startswith('+'): if self.threshold[1:].isdigit(): self._threshold = int(self.threshold[1:]) self._upper = True elif self.threshold.startswith('-'): ...
python
{ "resource": "" }
q239483
Meter.collect_rms
train
def collect_rms(self, rms): """Collect and calculate min, max and average RMS values""" if self._data: self._data['min'] = min(rms, self._data['min']) self._data['max'] = max(rms, self._data['max']) self._data['avg'] = float(rms + self._data['avg']) / 2 else: ...
python
{ "resource": "" }
q239484
TimeBasedSequence.from_timedelta
train
def from_timedelta(cls, timedelta): """expects a datetime.timedelta object""" from math import ceil units = ceil(timedelta.total_seconds() / cls.time_unit) return cls.create(units)
python
{ "resource": "" }
q239485
b58decode_check
train
def b58decode_check(v: str) -> bytes: '''Decode and verify the checksum of a Base58 encoded string''' result = b58decode(v) result, check = result[:-4], result[-4:] digest = sha256(sha256(result).digest()).digest() if check != digest[:4]: raise ValueError("Invalid checksum") return re...
python
{ "resource": "" }
q239486
bech32_decode
train
def bech32_decode(bech): """Validate a Bech32 string, and determine HRP and data.""" if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return None, None bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len(b...
python
{ "resource": "" }
q239487
SessionSecurityMiddleware.process_request
train
def process_request(self, request): """ Update last activity time or logout. """ if django.VERSION < (1, 10): is_authenticated = request.user.is_authenticated() else: is_authenticated = request.user.is_authenticated if not is_authenticated: r...
python
{ "resource": "" }
q239488
get_last_activity
train
def get_last_activity(session): """ Get the last activity datetime string from the session and return the python datetime object. """ try: return datetime.strptime(session['_session_security'], '%Y-%m-%dT%H:%M:%S.%f') except AttributeError: #######################...
python
{ "resource": "" }
q239489
Credentials.name
train
def name(self): """Get the name associated with these credentials""" return self.inquire(name=True, lifetime=False, usage=False, mechs=False).name
python
{ "resource": "" }
q239490
Credentials.acquire
train
def acquire(cls, name=None, lifetime=None, mechs=None, usage='both', store=None): """Acquire GSSAPI credentials This method acquires credentials. If the `store` argument is used, the credentials will be acquired from the given credential store (if supported). Otherwise...
python
{ "resource": "" }
q239491
Credentials.store
train
def store(self, store=None, usage='both', mech=None, overwrite=False, set_default=False): """Store these credentials into the given store This method stores the current credentials into the specified credentials store. If the default store is used, support for :rfc:`5588`...
python
{ "resource": "" }
q239492
Credentials.impersonate
train
def impersonate(self, name=None, lifetime=None, mechs=None, usage='initiate'): """Impersonate a name using the current credentials This method acquires credentials by impersonating another name using the current credentials. :requires-ext:`s4u` Args: ...
python
{ "resource": "" }
q239493
Credentials.inquire
train
def inquire(self, name=True, lifetime=True, usage=True, mechs=True): """Inspect these credentials for information This method inspects these credentials for information about them. Args: name (bool): get the name associated with the credentials lifetime (bool): get the ...
python
{ "resource": "" }
q239494
Credentials.inquire_by_mech
train
def inquire_by_mech(self, mech, name=True, init_lifetime=True, accept_lifetime=True, usage=True): """Inspect these credentials for per-mechanism information This method inspects these credentials for per-mechanism information about them. Args: mech (...
python
{ "resource": "" }
q239495
Credentials.add
train
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): """Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mecha...
python
{ "resource": "" }
q239496
Name.display_as
train
def display_as(self, name_type): """ Display this name as the given name type. This method attempts to display the current :class:`Name` using the syntax of the given :class:`NameType`, if possible. Warning: In MIT krb5 versions below 1.13.3, this method can segfau...
python
{ "resource": "" }
q239497
Name.export
train
def export(self, composite=False): """Export this name as a token. This method exports the name into a byte string which can then be imported by using the `token` argument of the constructor. Args: composite (bool): whether or not use to a composite token -- ...
python
{ "resource": "" }
q239498
Name._inquire
train
def _inquire(self, **kwargs): """Inspect this name for information. This method inspects the name for information. If no keyword arguments are passed, all available information is returned. Otherwise, only the keyword arguments that are passed and set to `True` are returned. ...
python
{ "resource": "" }
q239499
Mechanism.from_sasl_name
train
def from_sasl_name(cls, name=None): """ Create a Mechanism from its SASL name Args: name (str): SASL name of the desired mechanism Returns: Mechanism: the desired mechanism Raises: GSSError :requires-ext:`rfc5801` """ ...
python
{ "resource": "" }