_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q240400
RFC1459Support.on_raw_332
train
async def on_raw_332(self, message): """ Current topic on channel join. """ target, channel, topic = message.params if not self.in_channel(channel): return self.channels[channel]['topic'] = topic
python
{ "resource": "" }
q240401
RFC1459Support.on_raw_333
train
async def on_raw_333(self, message): """ Topic setter and time on channel join. """ target, channel, setter, timestamp = message.params if not self.in_channel(channel): return # No need to sync user since this is most likely outdated info. self.channels[channel]['top...
python
{ "resource": "" }
q240402
RFC1459Support.on_raw_375
train
async def on_raw_375(self, message): """ Start message of the day. """ await self._registration_completed(message) self.motd = message.params[1] + '\n'
python
{ "resource": "" }
q240403
RFC1459Support.on_raw_422
train
async def on_raw_422(self, message): """ MOTD is missing. """ await self._registration_completed(message) self.motd = None await self.on_connect()
python
{ "resource": "" }
q240404
RFC1459Support.on_raw_433
train
async def on_raw_433(self, message): """ Nickname in use. """ if not self.registered: self._registration_attempts += 1 # Attempt to set new nickname. if self._attempt_nicknames: await self.set_nickname(self._attempt_nicknames.pop(0)) else: ...
python
{ "resource": "" }
q240405
TLSSupport.connect
train
async def connect(self, hostname=None, port=None, tls=False, **kwargs): """ Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. """ if not port: if tls: port = DEFAULT_TLS_PORT else: port = rfc14...
python
{ "resource": "" }
q240406
TLSSupport._connect
train
async def _connect(self, hostname, port, reconnect=False, password=None, encoding=pydle.protocol.DEFAULT_ENCODING, channels=[], tls=False, tls_verify=False, source_address=None): """ Connect to IRC server, optionally over TLS. """ self.password = password # Create connection if we can't reuse i...
python
{ "resource": "" }
q240407
BasicClient._reset_attributes
train
def _reset_attributes(self): """ Reset attributes. """ # Record-keeping. self.channels = {} self.users = {} # Low-level data stuff. self._receive_buffer = b'' self._pending = {} self._handler_top_level = False self._ping_checker_handle = None ...
python
{ "resource": "" }
q240408
BasicClient._reset_connection_attributes
train
def _reset_connection_attributes(self): """ Reset connection attributes. """ self.connection = None self.encoding = None self._autojoin_channels = [] self._reconnect_attempts = 0
python
{ "resource": "" }
q240409
BasicClient.run
train
def run(self, *args, **kwargs): """ Connect and run bot in event loop. """ self.eventloop.run_until_complete(self.connect(*args, **kwargs)) try: self.eventloop.run_forever() finally: self.eventloop.stop()
python
{ "resource": "" }
q240410
BasicClient.connect
train
async def connect(self, hostname=None, port=None, reconnect=False, **kwargs): """ Connect to IRC server. """ if (not hostname or not port) and not reconnect: raise ValueError('Have to specify hostname and port if not reconnecting.') # Disconnect from current connection. if s...
python
{ "resource": "" }
q240411
BasicClient._connect
train
async def _connect(self, hostname, port, reconnect=False, channels=[], encoding=protocol.DEFAULT_ENCODING, source_address=None): """ Connect to IRC host. """ # Create connection if we can't reuse it. if not reconnect or not self.connection: self._autojoin_chann...
python
{ "resource": "" }
q240412
BasicClient._reconnect_delay
train
def _reconnect_delay(self): """ Calculate reconnection delay. """ if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED: if self._reconnect_attempts >= len(self.RECONNECT_DELAYS): return self.RECONNECT_DELAYS[-1] else: return self.RECONNECT_DELAYS[...
python
{ "resource": "" }
q240413
BasicClient._perform_ping_timeout
train
async def _perform_ping_timeout(self, delay: int): """ Handle timeout gracefully. Args: delay (int): delay before raising the timeout (in seconds) """ # pause for delay seconds await sleep(delay) # then continue error = TimeoutError( 'Pin...
python
{ "resource": "" }
q240414
BasicClient.rawmsg
train
async def rawmsg(self, command, *args, **kwargs): """ Send raw message. """ message = str(self._create_message(command, *args, **kwargs)) await self._send(message)
python
{ "resource": "" }
q240415
BasicClient.handle_forever
train
async def handle_forever(self): """ Handle data forever. """ while self.connected: data = await self.connection.recv() if not data: if self.connected: await self.disconnect(expected=False) break await self.on_data(da...
python
{ "resource": "" }
q240416
BasicClient.on_data_error
train
async def on_data_error(self, exception): """ Handle error. """ self.logger.error('Encountered error on socket.', exc_info=(type(exception), exception, None)) await self.disconnect(expected=False)
python
{ "resource": "" }
q240417
BasicClient.on_raw
train
async def on_raw(self, message): """ Handle a single message. """ self.logger.debug('<< %s', message._raw) if not message._valid: self.logger.warning('Encountered strictly invalid IRC message from server: %s', message._raw) if isinstance(messa...
python
{ "resource": "" }
q240418
BasicClient.on_unknown
train
async def on_unknown(self, message): """ Unknown command. """ self.logger.warning('Unknown command: [%s] %s %s', message.source, message.command, message.params)
python
{ "resource": "" }
q240419
ClientPool.connect
train
def connect(self, client: BasicClient, *args, **kwargs): """ Add client to pool. """ self.clients.add(client) self.connect_args[client] = (args, kwargs) # hack the clients event loop to use the pools own event loop client.eventloop = self.eventloop
python
{ "resource": "" }
q240420
ClientPool.disconnect
train
def disconnect(self, client): """ Remove client from pool. """ self.clients.remove(client) del self.connect_args[client] client.disconnect()
python
{ "resource": "" }
q240421
normalize
train
def normalize(input, case_mapping=protocol.DEFAULT_CASE_MAPPING): """ Normalize input according to case mapping. """ if case_mapping not in protocol.CASE_MAPPINGS: raise pydle.protocol.ProtocolViolation('Unknown case mapping ({})'.format(case_mapping)) input = input.lower() if case_mapping in ...
python
{ "resource": "" }
q240422
parse_user
train
def parse_user(raw): """ Parse nick(!user(@host)?)? structure. """ nick = raw user = None host = None # Attempt to extract host. if protocol.HOST_SEPARATOR in raw: raw, host = raw.split(protocol.HOST_SEPARATOR) # Attempt to extract user. if protocol.USER_SEPARATOR in raw: ...
python
{ "resource": "" }
q240423
RFC1459Message.parse
train
def parse(cls, line, encoding=pydle.protocol.DEFAULT_ENCODING): """ Parse given line into IRC message structure. Returns a Message. """ valid = True # Decode message. try: message = line.decode(encoding) except UnicodeDecodeError: ...
python
{ "resource": "" }
q240424
RFC1459Message.construct
train
def construct(self, force=False): """ Construct a raw IRC message. """ # Sanity check for command. command = str(self.command) if not protocol.COMMAND_PATTERN.match(command) and not force: raise pydle.protocol.ProtocolViolation('The constructed command does not follow the com...
python
{ "resource": "" }
q240425
featurize
train
def featurize(*features): """ Put features into proper MRO order. """ from functools import cmp_to_key def compare_subclass(left, right): if issubclass(left, right): return -1 elif issubclass(right, left): return 1 return 0 sorted_features = sorted(featu...
python
{ "resource": "" }
q240426
WHOXSupport.on_raw_join
train
async def on_raw_join(self, message): """ Override JOIN to send WHOX. """ await super().on_raw_join(message) nick, metadata = self._parse_user(message.source) channels = message.params[0].split(',') if self.is_same_nick(self.nickname, nick): # We joined. ...
python
{ "resource": "" }
q240427
WHOXSupport.on_raw_354
train
async def on_raw_354(self, message): """ WHOX results have arrived. """ # Is the message for us? target, identifier = message.params[:2] if identifier != WHOX_IDENTIFIER: return # Great. Extract relevant information. metadata = { 'nickname': messa...
python
{ "resource": "" }
q240428
ISUPPORTSupport._create_channel
train
def _create_channel(self, channel): """ Create channel with optional ban and invite exception lists. """ super()._create_channel(channel) if 'EXCEPTS' in self._isupport: self.channels[channel]['exceptlist'] = None if 'INVEX' in self._isupport: self.channels[channe...
python
{ "resource": "" }
q240429
ISUPPORTSupport.on_raw_005
train
async def on_raw_005(self, message): """ ISUPPORT indication. """ isupport = {} # Parse response. # Strip target (first argument) and 'are supported by this server' (last argument). for feature in message.params[1:-1]: if feature.startswith(FEATURE_DISABLED_PREFIX): ...
python
{ "resource": "" }
q240430
ISUPPORTSupport.on_isupport_casemapping
train
async def on_isupport_casemapping(self, value): """ IRC case mapping for nickname and channel name comparisons. """ if value in rfc1459.protocol.CASE_MAPPINGS: self._case_mapping = value self.channels = rfc1459.parsing.NormalizingDict(self.channels, case_mapping=value) ...
python
{ "resource": "" }
q240431
ISUPPORTSupport.on_isupport_chanlimit
train
async def on_isupport_chanlimit(self, value): """ Simultaneous channel limits for user. """ self._channel_limits = {} for entry in value.split(','): types, limit = entry.split(':') # Assign limit to channel type group and add lookup entry for type. self._cha...
python
{ "resource": "" }
q240432
ISUPPORTSupport.on_isupport_chanmodes
train
async def on_isupport_chanmodes(self, value): """ Valid channel modes and their behaviour. """ list, param, param_set, noparams = [ set(modes) for modes in value.split(',')[:4] ] self._channel_modes.update(set(value.replace(',', ''))) # The reason we have to do it like this is because o...
python
{ "resource": "" }
q240433
ISUPPORTSupport.on_isupport_excepts
train
async def on_isupport_excepts(self, value): """ Server allows ban exceptions. """ if not value: value = BAN_EXCEPT_MODE self._channel_modes.add(value) self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].add(value)
python
{ "resource": "" }
q240434
ISUPPORTSupport.on_isupport_extban
train
async def on_isupport_extban(self, value): """ Extended ban prefixes. """ self._extban_prefix, types = value.split(',') self._extban_types = set(types)
python
{ "resource": "" }
q240435
ISUPPORTSupport.on_isupport_invex
train
async def on_isupport_invex(self, value): """ Server allows invite exceptions. """ if not value: value = INVITE_EXCEPT_MODE self._channel_modes.add(value) self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].add(value)
python
{ "resource": "" }
q240436
ISUPPORTSupport.on_isupport_maxbans
train
async def on_isupport_maxbans(self, value): """ Maximum entries in ban list. Replaced by MAXLIST. """ if 'MAXLIST' not in self._isupport: if not self._list_limits: self._list_limits = {} self._list_limits['b'] = int(value)
python
{ "resource": "" }
q240437
ISUPPORTSupport.on_isupport_maxchannels
train
async def on_isupport_maxchannels(self, value): """ Old version of CHANLIMIT. """ if 'CHANTYPES' in self._isupport and 'CHANLIMIT' not in self._isupport: self._channel_limits = {} prefixes = self._isupport['CHANTYPES'] # Assume the limit is for all types of channels....
python
{ "resource": "" }
q240438
ISUPPORTSupport.on_isupport_maxlist
train
async def on_isupport_maxlist(self, value): """ Limits on channel modes involving lists. """ self._list_limits = {} for entry in value.split(','): modes, limit = entry.split(':') # Assign limit to mode group and add lookup entry for mode. self._list_limits[f...
python
{ "resource": "" }
q240439
ISUPPORTSupport.on_isupport_prefix
train
async def on_isupport_prefix(self, value): """ Nickname prefixes on channels and their associated modes. """ if not value: # No prefixes support. self._nickname_prefixes = collections.OrderedDict() return modes, prefixes = value.lstrip('(').split(')', 1) ...
python
{ "resource": "" }
q240440
ISUPPORTSupport.on_isupport_targmax
train
async def on_isupport_targmax(self, value): """ The maximum number of targets certain types of commands can affect. """ if not value: return for entry in value.split(','): command, limit = entry.split(':', 1) if not limit: continue ...
python
{ "resource": "" }
q240441
ISUPPORTSupport.on_isupport_wallchops
train
async def on_isupport_wallchops(self, value): """ Support for messaging every opped member or higher on a channel. Replaced by STATUSMSG. """ for prefix, mode in self._nickname_prefixes.items(): if mode == 'o': break else: prefix = '@' self._status...
python
{ "resource": "" }
q240442
TaggedMessage.parse
train
def parse(cls, line, encoding=pydle.protocol.DEFAULT_ENCODING): """ Parse given line into IRC message structure. Returns a TaggedMessage. """ valid = True # Decode message. try: message = line.decode(encoding) except UnicodeDecodeError: ...
python
{ "resource": "" }
q240443
TaggedMessage.construct
train
def construct(self, force=False): """ Construct raw IRC message and return it. """ message = super().construct(force=force) # Add tags. if self.tags: raw_tags = [] for tag, value in self.tags.items(): if value == True: ...
python
{ "resource": "" }
q240444
_get_public_suffix_list
train
def _get_public_suffix_list(): """Return a set containing all Public Suffixes. If the env variable PUBLIC_SUFFIX_LIST does not point to a local copy of the public suffix list it is downloaded into memory each time urltools is imported. """ local_psl = os.environ.get('PUBLIC_SUFFIX_LIST') if...
python
{ "resource": "" }
q240445
normalize
train
def normalize(url): """Normalize a URL. >>> normalize('hTtp://ExAMPLe.COM:80') 'http://example.com/' """ url = url.strip() if url == '': return '' parts = split(url) if parts.scheme: netloc = parts.netloc if parts.scheme in SCHEMES: path = normalize_p...
python
{ "resource": "" }
q240446
_encode_query
train
def _encode_query(query): """Quote all values of a query string.""" if query == '': return query query_args = [] for query_kv in query.split('&'): k, v = query_kv.split('=') query_args.append(k + "=" + quote(v.encode('utf-8'))) return '&'.join(query_args)
python
{ "resource": "" }
q240447
encode
train
def encode(url): """Encode URL.""" parts = extract(url) return construct(URL(parts.scheme, parts.username, parts.password, _idna_encode(parts.subdomain), _idna_encode(parts.domain), _...
python
{ "resource": "" }
q240448
construct
train
def construct(parts): """Construct a new URL from parts.""" url = '' if parts.scheme: if parts.scheme in SCHEMES: url += parts.scheme + '://' else: url += parts.scheme + ':' if parts.username and parts.password: url += parts.username + ':' + parts.password...
python
{ "resource": "" }
q240449
_normalize_port
train
def _normalize_port(scheme, port): """Return port if it is not default port, else None. >>> _normalize_port('http', '80') >>> _normalize_port('http', '8080') '8080' """ if not scheme: return port if port and port != DEFAULT_PORT[scheme]: return port
python
{ "resource": "" }
q240450
unquote
train
def unquote(text, exceptions=[]): """Unquote a text but ignore the exceptions. >>> unquote('foo%23bar') 'foo#bar' >>> unquote('foo%23bar', ['#']) 'foo%23bar' """ if not text: if text is None: raise TypeError('None object cannot be unquoted') else: ret...
python
{ "resource": "" }
q240451
split
train
def split(url): """Split URL into scheme, netloc, path, query and fragment. >>> split('http://www.example.com/abc?x=1&y=2#foo') SplitResult(scheme='http', netloc='www.example.com', path='/abc', query='x=1&y=2', fragment='foo') """ scheme = netloc = path = query = fragment = '' ip6_start = url.f...
python
{ "resource": "" }
q240452
split_netloc
train
def split_netloc(netloc): """Split netloc into username, password, host and port. >>> split_netloc('foo:bar@www.example.com:8080') ('foo', 'bar', 'www.example.com', '8080') """ username = password = host = port = '' if '@' in netloc: user_pw, netloc = netloc.split('@', 1) if ':'...
python
{ "resource": "" }
q240453
split_host
train
def split_host(host): """Use the Public Suffix List to split host into subdomain, domain and tld. >>> split_host('foo.bar.co.uk') ('foo', 'bar', 'co.uk') """ # host is IPv6? if '[' in host: return '', host, '' # host is IPv4? for c in host: if c not in IP_CHARS: ...
python
{ "resource": "" }
q240454
protocol.connection_made
train
def connection_made(self, transport): """ Gets called when a connection to the gateway is established. Initialise the protocol object. """ self.transport = transport self.loop = transport.loop self._cmd_lock = asyncio.Lock(loop=self.loop) self._wd_lock = a...
python
{ "resource": "" }
q240455
protocol.connection_lost
train
def connection_lost(self, exc): """ Gets called when the connection to the gateway is lost. Tear down and clean up the protocol object. """ _LOGGER.error("Disconnected: %s", exc) self.connected = False self.transport.close() if self._report_task is not Non...
python
{ "resource": "" }
q240456
protocol.setup_watchdog
train
async def setup_watchdog(self, cb, timeout): """Trigger a reconnect after @timeout seconds of inactivity.""" self._watchdog_timeout = timeout self._watchdog_cb = cb self._watchdog_task = self.loop.create_task(self._watchdog(timeout))
python
{ "resource": "" }
q240457
protocol.cancel_watchdog
train
async def cancel_watchdog(self): """Cancel the watchdog task and related variables.""" if self._watchdog_task is not None: _LOGGER.debug("Canceling Watchdog task.") self._watchdog_task.cancel() try: await self._watchdog_task except asyncio....
python
{ "resource": "" }
q240458
protocol._inform_watchdog
train
async def _inform_watchdog(self): """Inform the watchdog of activity.""" async with self._wd_lock: if self._watchdog_task is None: # Check within the Lock to deal with external cancel_watchdog # calls with queued _inform_watchdog tasks. return ...
python
{ "resource": "" }
q240459
protocol._watchdog
train
async def _watchdog(self, timeout): """Trigger and cancel the watchdog after timeout. Call callback.""" await asyncio.sleep(timeout, loop=self.loop) _LOGGER.debug("Watchdog triggered!") await self.cancel_watchdog() await self._watchdog_cb()
python
{ "resource": "" }
q240460
protocol._dissect_msg
train
def _dissect_msg(self, match): """ Split messages into bytes and return a tuple of bytes. """ recvfrom = match.group(1) frame = bytes.fromhex(match.group(2)) if recvfrom == 'E': _LOGGER.warning("Received erroneous message, ignoring: %s", frame) ret...
python
{ "resource": "" }
q240461
protocol._get_u16
train
def _get_u16(self, msb, lsb): """ Convert 2 bytes into an unsigned int. """ buf = struct.pack('>BB', self._get_u8(msb), self._get_u8(lsb)) return int(struct.unpack('>H', buf)[0])
python
{ "resource": "" }
q240462
protocol._get_s16
train
def _get_s16(self, msb, lsb): """ Convert 2 bytes into a signed int. """ buf = struct.pack('>bB', self._get_s8(msb), self._get_u8(lsb)) return int(struct.unpack('>h', buf)[0])
python
{ "resource": "" }
q240463
protocol._report
train
async def _report(self): """ Call _update_cb with the status dict as an argument whenever a status update occurs. This method is a coroutine """ while True: oldstatus = dict(self.status) stat = await self._updateq.get() if self._update...
python
{ "resource": "" }
q240464
protocol.set_update_cb
train
async def set_update_cb(self, cb): """Register the update callback.""" if self._report_task is not None and not self._report_task.cancelled(): self.loop.create_task(self._report_task.cancel()) self._update_cb = cb if cb is not None: self._report_task = self.loop.c...
python
{ "resource": "" }
q240465
protocol.issue_cmd
train
async def issue_cmd(self, cmd, value, retry=3): """ Issue a command, then await and return the return value. This method is a coroutine """ async with self._cmd_lock: if not self.connected: _LOGGER.debug( "Serial transport closed, ...
python
{ "resource": "" }
q240466
pyotgw.get_target_temp
train
def get_target_temp(self): """ Get the target temperature. """ if not self._connected: return temp_ovrd = self._protocol.status.get(DATA_ROOM_SETPOINT_OVRD) if temp_ovrd: return temp_ovrd return self._protocol.status.get(DATA_ROOM_SETPOINT)
python
{ "resource": "" }
q240467
pyotgw.get_reports
train
async def get_reports(self): """ Update the pyotgw object with the information from all of the PR commands and return the updated status dict. This method is a coroutine """ cmd = OTGW_CMD_REPORT reports = {} for value in OTGW_REPORTS.keys(): ...
python
{ "resource": "" }
q240468
pyotgw.add_alternative
train
async def add_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT): """ Add the specified Data-ID to the list of alternative commands to send to the boiler instead of a Data-ID that is known to be unsupported by the boiler. Alternative Data-IDs will always be sent to the boiler i...
python
{ "resource": "" }
q240469
pyotgw.del_alternative
train
async def del_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT): """ Remove the specified Data-ID from the list of alternative commands. Only one occurrence is deleted. If the Data-ID appears multiple times in the list of alternative commands, this command must be repeated to ...
python
{ "resource": "" }
q240470
pyotgw.add_unknown_id
train
async def add_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT): """ Inform the gateway that the boiler doesn't support the specified Data-ID, even if the boiler doesn't indicate that by returning an Unknown-DataId response. Using this command allows the gateway to send ...
python
{ "resource": "" }
q240471
pyotgw.del_unknown_id
train
async def del_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT): """ Start forwarding the specified Data-ID to the boiler again. This command resets the counter used to determine if the specified Data-ID is supported by the boiler. Return the ID that was marked as suppor...
python
{ "resource": "" }
q240472
pyotgw.set_max_ch_setpoint
train
async def set_max_ch_setpoint(self, temperature, timeout=OTGW_DEFAULT_TIMEOUT): """ Set the maximum central heating setpoint. This command is only available with boilers that support this function. Return the newly accepted setpoint, or None on failure. ...
python
{ "resource": "" }
q240473
pyotgw.set_dhw_setpoint
train
async def set_dhw_setpoint(self, temperature, timeout=OTGW_DEFAULT_TIMEOUT): """ Set the domestic hot water setpoint. This command is only available with boilers that support this function. Return the newly accepted setpoint, or None on failure. Th...
python
{ "resource": "" }
q240474
pyotgw.set_max_relative_mod
train
async def set_max_relative_mod(self, max_mod, timeout=OTGW_DEFAULT_TIMEOUT): """ Override the maximum relative modulation from the thermostat. Valid values are 0 through 100. Clear the setting by specifying a non-numeric value. Return the newly ...
python
{ "resource": "" }
q240475
pyotgw.set_control_setpoint
train
async def set_control_setpoint(self, setpoint, timeout=OTGW_DEFAULT_TIMEOUT): """ Manipulate the control setpoint being sent to the boiler. Set to 0 to pass along the value specified by the thermostat. Return the newly accepted value, or None on failure...
python
{ "resource": "" }
q240476
pyotgw._send_report
train
async def _send_report(self, status): """ Call all subscribed coroutines in _notify whenever a status update occurs. This method is a coroutine """ if len(self._notify) > 0: # Each client gets its own copy of the dict. asyncio.gather(*[coro(dict(s...
python
{ "resource": "" }
q240477
pyotgw._poll_gpio
train
async def _poll_gpio(self, poll, interval=10): """ Start or stop polling GPIO states. GPIO states aren't being pushed by the gateway, we need to poll if we want updates. """ if poll and self._gpio_task is None: async def polling_routine(interval): ...
python
{ "resource": "" }
q240478
pyotgw._update_status
train
def _update_status(self, update): """Update the status dict and push it to subscribers.""" if isinstance(update, dict): self._protocol.status.update(update) self._protocol._updateq.put_nowait(self._protocol.status)
python
{ "resource": "" }
q240479
BuildTarget.write_dockerfile
train
def write_dockerfile(self, output_dir): """ Used only to write a Dockerfile that will NOT be built by docker-make """ if not os.path.exists(output_dir): os.makedirs(output_dir) lines = [] for istep, step in enumerate(self.steps): if istep == 0: ...
python
{ "resource": "" }
q240480
BuildTarget.build
train
def build(self, client, nobuild=False, usecache=True, pull=False): """ Drives the build of the final image - get the list of steps and execute them. Args: client (docker.Client): docker client object that will build the image nob...
python
{ "resource": "" }
q240481
BuildTarget.finalizenames
train
def finalizenames(self, client, finalimage): """ Tag the built image with its final name and untag intermediate containers """ client.api.tag(finalimage, *self.targetname.split(':')) cprint('Tagged final image as "%s"' % self.targetname, 'green') if not self.keepbu...
python
{ "resource": "" }
q240482
BuildStep._resolve_squash_cache
train
def _resolve_squash_cache(self, client): """ Currently doing a "squash" basically negates the cache for any subsequent layers. But we can work around this by A) checking if the cache was successful for the _unsquashed_ version of the image, and B) if so, re-using an older squashed versio...
python
{ "resource": "" }
q240483
FileCopyStep.dockerfile_lines
train
def dockerfile_lines(self): """ Used only when printing dockerfiles, not for building """ w1 = colored( 'WARNING: this build includes files that are built in other images!!! The generated' '\n Dockerfile must be built in a directory that contains' ...
python
{ "resource": "" }
q240484
ImageDefs._check_yaml_and_paths
train
def _check_yaml_and_paths(ymlfilepath, yamldefs): """ Checks YAML for errors and resolves all paths """ relpath = os.path.relpath(ymlfilepath) if '/' not in relpath: relpath = './%s' % relpath pathroot = os.path.abspath(os.path.dirname(ymlfilepath)) for image...
python
{ "resource": "" }
q240485
ImageDefs.generate_build
train
def generate_build(self, image, targetname, rebuilds=None, cache_repo='', cache_tag='', buildargs=None, **kwargs): """ Separate the build into a series of one or more intermediate steps. Each specified build directory gets its own step Args: image (str...
python
{ "resource": "" }
q240486
ImageDefs.sort_dependencies
train
def sort_dependencies(self, image, dependencies=None): """ Topologically sort the docker commands by their requirements Note: Circular "requires" dependencies are assumed to have already been checked in get_external_base_image, they are not checked here Args: ...
python
{ "resource": "" }
q240487
ImageDefs.get_external_base_image
train
def get_external_base_image(self, image, stack=None): """ Makes sure that this image has exactly one unique external base image """ if stack is None: stack = list() mydef = self.ymldefs[image] if image in stack: stack.append(image) raise erro...
python
{ "resource": "" }
q240488
StagedFile.stage
train
def stage(self, startimage, newimage): """ Copies the file from source to target Args: startimage (str): name of the image to stage these files into newimage (str): name of the created image """ client = utils.get_client() cprint(' Copying file from "%s:...
python
{ "resource": "" }
q240489
_runargs
train
def _runargs(argstring): """ Entrypoint for debugging """ import shlex parser = cli.make_arg_parser() args = parser.parse_args(shlex.split(argstring)) run(args)
python
{ "resource": "" }
q240490
lookup
train
def lookup(source, keys, fallback = None): """Traverses the source, looking up each key. Returns None if can't find anything instead of raising an exception.""" try: for key in keys: source = source[key] return source except (KeyError, AttributeError, TypeError): return fallback
python
{ "resource": "" }
q240491
GraphiteReporter.run
train
def run(self): """Run the thread.""" while True: try: try: name, value, valueType, stamp = self.queue.get() except TypeError: break self.log(name, value, valueType, stamp) finally: self.queue.task_done()
python
{ "resource": "" }
q240492
GraphiteReporter.connect
train
def connect(self): """Connects to the Graphite server if not already connected.""" if self.sock is not None: return backoff = 0.01 while True: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect((self.host, self.port)) ...
python
{ "resource": "" }
q240493
GraphiteReporter.disconnect
train
def disconnect(self): """Disconnect from the Graphite server if connected.""" if self.sock is not None: try: self.sock.close() except socket.error: pass finally: self.sock = None
python
{ "resource": "" }
q240494
GraphiteReporter._sendMsg
train
def _sendMsg(self, msg): """Send a line to graphite. Retry with exponential backoff.""" if not self.sock: self.connect() if not isinstance(msg, binary_type): msg = msg.encode("UTF-8") backoff = 0.001 while True: try: self.sock.sendall(msg) break except socket...
python
{ "resource": "" }
q240495
GraphiteReporter.log
train
def log(self, name, value, valueType=None, stamp=None): """Log a named numeric value. The value type may be 'value', 'count', or None.""" if type(value) == float: form = "%s%s %2.2f %d\n" else: form = "%s%s %s %d\n" if valueType is not None and len(valueType) > 0 and valueType[0] != '.'...
python
{ "resource": "" }
q240496
GraphiteReporter.enqueue
train
def enqueue(self, name, value, valueType=None, stamp=None): """Enqueue a call to log.""" # If queue is too large, refuse to log. if self.maxQueueSize and self.queue.qsize() > self.maxQueueSize: return # Stick arguments into the queue self.queue.put((name, value, valueType, stamp))
python
{ "resource": "" }
q240497
AtomicValue.update
train
def update(self, function): """Atomically apply function to the value, and return the old and new values.""" with self.lock: oldValue = self.value self.value = function(oldValue) return oldValue, self.value
python
{ "resource": "" }
q240498
EWMA.tick
train
def tick(self): """Updates rates and decays""" count = self._uncounted.getAndSet(0) instantRate = float(count) / self.interval if self._initialized: self.rate += (self.alpha * (instantRate - self.rate)) else: self.rate = instantRate self._initialized = True
python
{ "resource": "" }
q240499
statsId
train
def statsId(obj): """Gets a unique ID for each object.""" if hasattr(obj, ID_KEY): return getattr(obj, ID_KEY) newId = next(NEXT_ID) setattr(obj, ID_KEY, newId) return newId
python
{ "resource": "" }