_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q255700 | ConversationList._handle_watermark_notification | validation | async def _handle_watermark_notification(self, watermark_notification):
"""Receive WatermarkNotification and update the conversation.
Args:
watermark_notification: hangouts_pb2.WatermarkNotification instance
"""
conv_id = watermark_notification.conversation_id.id
res... | python | {
"resource": ""
} |
q255701 | ConversationList._sync | validation | async def _sync(self):
"""Sync conversation state and events that could have been missed."""
logger.info('Syncing events since {}'.format(self._sync_timestamp))
try:
res = await self._client.sync_all_new_events(
hangouts_pb2.SyncAllNewEventsRequest(
... | python | {
"resource": ""
} |
q255702 | User.upgrade_name | validation | def upgrade_name(self, user_):
"""Upgrade name type of this user.
Google Voice participants often first appear with no name at all, and
then get upgraded unpredictably to numbers ("+12125551212") or names.
Args:
user_ (~hangups.user.User): User to upgrade with.
"""
... | python | {
"resource": ""
} |
q255703 | User.from_entity | validation | def from_entity(entity, self_user_id):
"""Construct user from ``Entity`` message.
Args:
entity: ``Entity`` message.
self_user_id (~hangups.user.UserID or None): The ID of the current
user. If ``None``, assume ``entity`` is the current user.
Returns:
... | python | {
"resource": ""
} |
q255704 | User.from_conv_part_data | validation | def from_conv_part_data(conv_part_data, self_user_id):
"""Construct user from ``ConversationParticipantData`` message.
Args:
conv_part_id: ``ConversationParticipantData`` message.
self_user_id (~hangups.user.UserID or None): The ID of the current
user. If ``None`... | python | {
"resource": ""
} |
q255705 | UserList.get_user | validation | def get_user(self, user_id):
"""Get a user by its ID.
Args:
user_id (~hangups.user.UserID): The ID of the user.
Raises:
KeyError: If no such user is known.
Returns:
:class:`~hangups.user.User` with the given ID.
"""
try:
... | python | {
"resource": ""
} |
q255706 | UserList._add_user_from_conv_part | validation | def _add_user_from_conv_part(self, conv_part):
"""Add or upgrade User from ConversationParticipantData."""
user_ = User.from_conv_part_data(conv_part, self._self_user.id_)
existing = self._user_dict.get(user_.id_)
if existing is None:
logger.warning('Adding fallback User wit... | python | {
"resource": ""
} |
q255707 | Event.add_observer | validation | def add_observer(self, callback):
"""Add an observer to this event.
Args:
callback: A function or coroutine callback to call when the event
is fired.
Raises:
ValueError: If the callback has already been added.
"""
if callback in self._obs... | python | {
"resource": ""
} |
q255708 | Event.remove_observer | validation | def remove_observer(self, callback):
"""Remove an observer from this event.
Args:
callback: A function or coroutine callback to remove from this
event.
Raises:
ValueError: If the callback is not an observer of this event.
"""
if callback ... | python | {
"resource": ""
} |
q255709 | Event.fire | validation | async def fire(self, *args, **kwargs):
"""Fire this event, calling all observers with the same arguments."""
logger.debug('Fired {}'.format(self))
for observer in self._observers:
gen = observer(*args, **kwargs)
if asyncio.iscoroutinefunction(observer):
aw... | python | {
"resource": ""
} |
q255710 | markdown | validation | def markdown(tag):
"""Return start and end regex pattern sequences for simple Markdown tag."""
return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag)) | python | {
"resource": ""
} |
q255711 | html | validation | def html(tag):
"""Return sequence of start and end regex patterns for simple HTML tag"""
return (HTML_START.format(tag=tag), HTML_END.format(tag=tag)) | python | {
"resource": ""
} |
q255712 | run_example | validation | def run_example(example_coroutine, *extra_args):
"""Run a hangups example coroutine.
Args:
example_coroutine (coroutine): Coroutine to run with a connected
hangups client and arguments namespace as arguments.
extra_args (str): Any extra command line arguments required by the
... | python | {
"resource": ""
} |
q255713 | _get_parser | validation | def _get_parser(extra_args):
"""Return ArgumentParser with any extra arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
dirs = appdirs.AppDirs('hangups', 'hangups')
default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.tx... | python | {
"resource": ""
} |
q255714 | _async_main | validation | async def _async_main(example_coroutine, client, args):
"""Run the example coroutine."""
# Spawn a task for hangups to run in parallel with the example coroutine.
task = asyncio.ensure_future(client.connect())
# Wait for hangups to either finish connecting or raise an exception.
on_connect = asynci... | python | {
"resource": ""
} |
q255715 | print_table | validation | def print_table(col_tuple, row_tuples):
"""Print column headers and rows as a reStructuredText table.
Args:
col_tuple: Tuple of column name strings.
row_tuples: List of tuples containing row data.
"""
col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples)
... | python | {
"resource": ""
} |
q255716 | generate_enum_doc | validation | def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''):
"""Generate doc for an enum.
Args:
enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum
to generate docs for.
locations: Dictionary of location paths tuples to
descriptor_pb2.Source... | python | {
"resource": ""
} |
q255717 | generate_message_doc | validation | def generate_message_doc(message_descriptor, locations, path, name_prefix=''):
"""Generate docs for message and nested messages and enums.
Args:
message_descriptor: descriptor_pb2.DescriptorProto instance for message
to generate docs for.
locations: Dictionary of location paths tupl... | python | {
"resource": ""
} |
q255718 | compile_protofile | validation | def compile_protofile(proto_file_path):
"""Compile proto file to descriptor set.
Args:
proto_file_path: Path to proto file to compile.
Returns:
Path to file containing compiled descriptor set.
Raises:
SystemExit if the compilation fails.
"""
out_file = tempfile.mkstemp... | python | {
"resource": ""
} |
q255719 | main | validation | def main():
"""Parse arguments and print generated documentation to stdout."""
parser = argparse.ArgumentParser()
parser.add_argument('protofilepath')
args = parser.parse_args()
out_file = compile_protofile(args.protofilepath)
with open(out_file, 'rb') as proto_file:
# pylint: disable=n... | python | {
"resource": ""
} |
q255720 | dir_maker | validation | def dir_maker(path):
"""Create a directory if it does not exist."""
directory = os.path.dirname(path)
if directory != '' and not os.path.isdir(directory):
try:
os.makedirs(directory)
except OSError as e:
sys.exit('Failed to create directory: {}'.format(e)) | python | {
"resource": ""
} |
q255721 | ChatUI._exception_handler | validation | def _exception_handler(self, _loop, context):
"""Handle exceptions from the asyncio loop."""
# Start a graceful shutdown.
self._coroutine_queue.put(self._client.disconnect())
# Store the exception to be re-raised later. If the context doesn't
# contain an exception, create one c... | python | {
"resource": ""
} |
q255722 | ChatUI._input_filter | validation | def _input_filter(self, keys, _):
"""Handle global keybindings."""
if keys == [self._keys['menu']]:
if self._urwid_loop.widget == self._tabbed_window:
self._show_menu()
else:
self._hide_menu()
elif keys == [self._keys['quit']]:
... | python | {
"resource": ""
} |
q255723 | ChatUI._show_menu | validation | def _show_menu(self):
"""Show the overlay menu."""
# If the current widget in the TabbedWindowWidget has a menu,
# overlay it on the TabbedWindowWidget.
current_widget = self._tabbed_window.get_current_widget()
if hasattr(current_widget, 'get_menu_widget'):
menu_widge... | python | {
"resource": ""
} |
q255724 | ChatUI.get_conv_widget | validation | def get_conv_widget(self, conv_id):
"""Return an existing or new ConversationWidget."""
if conv_id not in self._conv_widgets:
set_title_cb = (lambda widget, title:
self._tabbed_window.set_tab(widget, title=title))
widget = ConversationWidget(
... | python | {
"resource": ""
} |
q255725 | ChatUI.add_conversation_tab | validation | def add_conversation_tab(self, conv_id, switch=False):
"""Add conversation tab if not present, and optionally switch to it."""
conv_widget = self.get_conv_widget(conv_id)
self._tabbed_window.set_tab(conv_widget, switch=switch,
title=conv_widget.title) | python | {
"resource": ""
} |
q255726 | ChatUI._on_connect | validation | async def _on_connect(self):
"""Handle connecting for the first time."""
self._user_list, self._conv_list = (
await hangups.build_user_conversation_list(self._client)
)
self._conv_list.on_event.add_observer(self._on_event)
# show the conversation menu
conv_pi... | python | {
"resource": ""
} |
q255727 | ChatUI._on_event | validation | def _on_event(self, conv_event):
"""Open conversation tab for new messages & pass events to notifier."""
conv = self._conv_list.get(conv_event.conversation_id)
user = conv.get_user(conv_event.user_id)
show_notification = all((
isinstance(conv_event, hangups.ChatMessageEvent),... | python | {
"resource": ""
} |
q255728 | CoroutineQueue.put | validation | def put(self, coro):
"""Put a coroutine in the queue to be executed."""
# Avoid logging when a coroutine is queued or executed to avoid log
# spam from coroutines that are started on every keypress.
assert asyncio.iscoroutine(coro)
self._queue.put_nowait(coro) | python | {
"resource": ""
} |
q255729 | CoroutineQueue.consume | validation | async def consume(self):
"""Consume coroutines from the queue by executing them."""
while True:
coro = await self._queue.get()
assert asyncio.iscoroutine(coro)
await coro | python | {
"resource": ""
} |
q255730 | RenameConversationDialog._rename | validation | def _rename(self, name, callback):
"""Rename conversation and call callback."""
self._coroutine_queue.put(self._conversation.rename(name))
callback() | python | {
"resource": ""
} |
q255731 | ConversationListWalker._on_event | validation | def _on_event(self, _):
"""Re-order the conversations when an event occurs."""
# TODO: handle adding new conversations
self.sort(key=lambda conv_button: conv_button.last_modified,
reverse=True) | python | {
"resource": ""
} |
q255732 | StatusLineWidget.show_message | validation | def show_message(self, message_str):
"""Show a temporary message."""
if self._message_handle is not None:
self._message_handle.cancel()
self._message_handle = asyncio.get_event_loop().call_later(
self._MESSAGE_DELAY_SECS, self._clear_message
)
self._messag... | python | {
"resource": ""
} |
q255733 | StatusLineWidget._on_event | validation | def _on_event(self, conv_event):
"""Make users stop typing when they send a message."""
if isinstance(conv_event, hangups.ChatMessageEvent):
self._typing_statuses[conv_event.user_id] = (
hangups.TYPING_TYPE_STOPPED
)
self._update() | python | {
"resource": ""
} |
q255734 | StatusLineWidget._on_typing | validation | def _on_typing(self, typing_message):
"""Handle typing updates."""
self._typing_statuses[typing_message.user_id] = typing_message.status
self._update() | python | {
"resource": ""
} |
q255735 | StatusLineWidget._update | validation | def _update(self):
"""Update status text."""
typing_users = [self._conversation.get_user(user_id)
for user_id, status in self._typing_statuses.items()
if status == hangups.TYPING_TYPE_STARTED]
displayed_names = [user.first_name for user in typing_u... | python | {
"resource": ""
} |
q255736 | MessageWidget._get_date_str | validation | def _get_date_str(timestamp, datetimefmt, show_date=False):
"""Convert UTC datetime into user interface string."""
fmt = ''
if show_date:
fmt += '\n'+datetimefmt.get('date', '')+'\n'
fmt += datetimefmt.get('time', '')
return timestamp.astimezone(tz=None).strftime(fmt) | python | {
"resource": ""
} |
q255737 | MessageWidget.from_conversation_event | validation | def from_conversation_event(conversation, conv_event, prev_conv_event,
datetimefmt, watermark_users=None):
"""Return MessageWidget representing a ConversationEvent.
Returns None if the ConversationEvent does not have a widget
representation.
"""
u... | python | {
"resource": ""
} |
q255738 | ConversationEventListWalker._handle_event | validation | def _handle_event(self, conv_event):
"""Handle updating and scrolling when a new event is added.
Automatically scroll down to show the new text if the bottom is
showing. This allows the user to scroll up to read previous messages
while new messages are arriving.
"""
if n... | python | {
"resource": ""
} |
q255739 | ConversationEventListWalker._load | validation | async def _load(self):
"""Load more events for this conversation."""
try:
conv_events = await self._conversation.get_events(
self._conversation.events[0].id_
)
except (IndexError, hangups.NetworkError):
conv_events = []
if not conv_even... | python | {
"resource": ""
} |
q255740 | ConversationEventListWalker.set_focus | validation | def set_focus(self, position):
"""Set the focus to position or raise IndexError."""
self._focus_position = position
self._modified()
# If we set focus to anywhere but the last position, the user if
# scrolling up:
try:
self.next_position(position)
exce... | python | {
"resource": ""
} |
q255741 | ConversationWidget.get_menu_widget | validation | def get_menu_widget(self, close_callback):
"""Return the menu widget associated with this widget."""
return ConversationMenu(
self._coroutine_queue, self._conversation, close_callback,
self._keys
) | python | {
"resource": ""
} |
q255742 | ConversationWidget.keypress | validation | def keypress(self, size, key):
"""Handle marking messages as read and keeping client active."""
# Set the client as active.
self._coroutine_queue.put(self._client.set_active())
# Mark the newest event as read.
self._coroutine_queue.put(self._conversation.update_read_timestamp())... | python | {
"resource": ""
} |
q255743 | ConversationWidget._set_title | validation | def _set_title(self):
"""Update this conversation's tab title."""
self.title = get_conv_name(self._conversation, show_unread=True,
truncate=True)
self._set_title_cb(self, self.title) | python | {
"resource": ""
} |
q255744 | ConversationWidget._on_return | validation | def _on_return(self, text):
"""Called when the user presses return on the send message widget."""
# Ignore if the user hasn't typed a message.
if not text:
return
elif text.startswith('/image') and len(text.split(' ')) == 2:
# Temporary UI for testing image upload... | python | {
"resource": ""
} |
q255745 | TabbedWindowWidget._update_tabs | validation | def _update_tabs(self):
"""Update tab display."""
text = []
for num, widget in enumerate(self._widgets):
palette = ('active_tab' if num == self._tab_index
else 'inactive_tab')
text += [
(palette, ' {} '.format(self._widget_title[widg... | python | {
"resource": ""
} |
q255746 | TabbedWindowWidget.keypress | validation | def keypress(self, size, key):
"""Handle keypresses for changing tabs."""
key = super().keypress(size, key)
num_tabs = len(self._widgets)
if key == self._keys['prev_tab']:
self._tab_index = (self._tab_index - 1) % num_tabs
self._update_tabs()
elif key == s... | python | {
"resource": ""
} |
q255747 | TabbedWindowWidget.set_tab | validation | def set_tab(self, widget, switch=False, title=None):
"""Add or modify a tab.
If widget is not a tab, it will be added. If switch is True, switch to
this tab. If title is given, set the tab's title.
"""
if widget not in self._widgets:
self._widgets.append(widget)
... | python | {
"resource": ""
} |
q255748 | _replace_words | validation | def _replace_words(replacements, string):
"""Replace words with corresponding values in replacements dict.
Words must be separated by spaces or newlines.
"""
output_lines = []
for line in string.split('\n'):
output_words = []
for word in line.split(' '):
new_word = repla... | python | {
"resource": ""
} |
q255749 | get_auth | validation | def get_auth(credentials_prompt, refresh_token_cache, manual_login=False):
"""Authenticate with Google.
Args:
refresh_token_cache (RefreshTokenCache): Cache to use so subsequent
logins may not require credentials.
credentials_prompt (CredentialsPrompt): Prompt to use if credentials
... | python | {
"resource": ""
} |
q255750 | _get_authorization_code | validation | def _get_authorization_code(session, credentials_prompt):
"""Get authorization code using Google account credentials.
Because hangups can't use a real embedded browser, it has to use the
Browser class to enter the user's credentials and retrieve the
authorization code, which is placed in a cookie. This... | python | {
"resource": ""
} |
q255751 | _auth_with_refresh_token | validation | def _auth_with_refresh_token(session, refresh_token):
"""Authenticate using OAuth refresh token.
Raises GoogleAuthError if authentication fails.
Returns access token string.
"""
# Make a token request.
token_request_data = {
'client_id': OAUTH2_CLIENT_ID,
'client_secret': OAUTH... | python | {
"resource": ""
} |
q255752 | _auth_with_code | validation | def _auth_with_code(session, authorization_code):
"""Authenticate using OAuth authorization code.
Raises GoogleAuthError if authentication fails.
Returns access token string and refresh token string.
"""
# Make a token request.
token_request_data = {
'client_id': OAUTH2_CLIENT_ID,
... | python | {
"resource": ""
} |
q255753 | _make_token_request | validation | def _make_token_request(session, token_request_data):
"""Make OAuth token request.
Raises GoogleAuthError if authentication fails.
Returns dict response.
"""
try:
r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data)
r.raise_for_status()
except requests.RequestExc... | python | {
"resource": ""
} |
q255754 | _get_session_cookies | validation | def _get_session_cookies(session, access_token):
"""Use the access token to get session cookies.
Raises GoogleAuthError if session cookies could not be loaded.
Returns dict of cookies.
"""
headers = {'Authorization': 'Bearer {}'.format(access_token)}
try:
r = session.get(('https://acc... | python | {
"resource": ""
} |
q255755 | RefreshTokenCache.get | validation | def get(self):
"""Get cached refresh token.
Returns:
Cached refresh token, or ``None`` on failure.
"""
logger.info(
'Loading refresh_token from %s', repr(self._filename)
)
try:
with open(self._filename) as f:
return f.r... | python | {
"resource": ""
} |
q255756 | RefreshTokenCache.set | validation | def set(self, refresh_token):
"""Cache a refresh token, ignoring any failure.
Args:
refresh_token (str): Refresh token to cache.
"""
logger.info('Saving refresh_token to %s', repr(self._filename))
try:
with open(self._filename, 'w') as f:
... | python | {
"resource": ""
} |
q255757 | Browser.submit_form | validation | def submit_form(self, form_selector, input_dict):
"""Populate and submit a form on the current page.
Raises GoogleAuthError if form can not be submitted.
"""
logger.info(
'Submitting form on page %r', self._page.url.split('?')[0]
)
logger.info(
'P... | python | {
"resource": ""
} |
q255758 | _parse_sid_response | validation | def _parse_sid_response(res):
"""Parse response format for request for new channel SID.
Example format (after parsing JS):
[ [0,["c","SID_HERE","",8]],
[1,[{"gsid":"GSESSIONID_HERE"}]]]
Returns (SID, gsessionid) tuple.
"""
res = json.loads(list(ChunkParser().get_chunks(res))[0])
... | python | {
"resource": ""
} |
q255759 | ChunkParser.get_chunks | validation | def get_chunks(self, new_data_bytes):
"""Yield chunks generated from received data.
The buffer may not be decodable as UTF-8 if there's a split multi-byte
character at the end. To handle this, do a "best effort" decode of the
buffer to decode as much of it as possible.
The leng... | python | {
"resource": ""
} |
q255760 | Channel.listen | validation | async def listen(self):
"""Listen for messages on the backwards channel.
This method only returns when the connection has been closed due to an
error.
"""
retries = 0 # Number of retries attempted so far
need_new_sid = True # whether a new SID is needed
while ... | python | {
"resource": ""
} |
q255761 | Channel._fetch_channel_sid | validation | async def _fetch_channel_sid(self):
"""Creates a new channel for receiving push data.
Sending an empty forward channel request will create a new channel on
the server.
There's a separate API to get the gsessionid alone that Hangouts for
Chrome uses, but if we don't send a gsess... | python | {
"resource": ""
} |
q255762 | Channel._longpoll_request | validation | async def _longpoll_request(self):
"""Open a long-polling request and receive arrays.
This method uses keep-alive to make re-opening the request faster, but
the remote server will set the "Connection: close" header once an hour.
Raises hangups.NetworkError or ChannelSessionError.
... | python | {
"resource": ""
} |
q255763 | Channel._on_push_data | validation | async def _on_push_data(self, data_bytes):
"""Parse push data and trigger events."""
logger.debug('Received chunk:\n{}'.format(data_bytes))
for chunk in self._chunk_parser.get_chunks(data_bytes):
# Consider the channel connected once the first chunk is received.
if not s... | python | {
"resource": ""
} |
q255764 | ChatMessageSegment.serialize | validation | def serialize(self):
"""Serialize this segment to a ``Segment`` message.
Returns:
``Segment`` message.
"""
segment = hangouts_pb2.Segment(
type=self.type_,
text=self.text,
formatting=hangouts_pb2.Formatting(
bold=self.is_bo... | python | {
"resource": ""
} |
q255765 | _decode_field | validation | def _decode_field(message, field, value):
"""Decode optional or required field."""
if field.type == FieldDescriptor.TYPE_MESSAGE:
decode(getattr(message, field.name), value)
else:
try:
if field.type == FieldDescriptor.TYPE_BYTES:
value = base64.b64decode(value)
... | python | {
"resource": ""
} |
q255766 | _decode_repeated_field | validation | def _decode_repeated_field(message, field, value_list):
"""Decode repeated field."""
if field.type == FieldDescriptor.TYPE_MESSAGE:
for value in value_list:
decode(getattr(message, field.name).add(), value)
else:
try:
for value in value_list:
if field.... | python | {
"resource": ""
} |
q255767 | decode | validation | def decode(message, pblite, ignore_first_item=False):
"""Decode pblite to Protocol Buffer message.
This method is permissive of decoding errors and will log them as warnings
and continue decoding where possible.
The first element of the outer pblite list must often be ignored using the
ignore_firs... | python | {
"resource": ""
} |
q255768 | _timezone_format | validation | def _timezone_format(value):
"""
Generates a timezone aware datetime if the 'USE_TZ' setting is enabled
:param value: The datetime value
:return: A locale aware datetime
"""
return timezone.make_aware(value, timezone.get_current_timezone()) if getattr(settings, 'USE_TZ', False) else value | python | {
"resource": ""
} |
q255769 | Seeder.execute | validation | def execute(self, using=None):
"""
Populate the database using all the Entity classes previously added.
:param using A Django database connection name
:rtype: A list of the inserted PKs
"""
if not using:
using = self.get_connection()
inserted_entitie... | python | {
"resource": ""
} |
q255770 | ADS1x15._read | validation | def _read(self, mux, gain, data_rate, mode):
"""Perform an ADC read with the provided mux, gain, data_rate, and mode
values. Returns the signed integer result of the read.
"""
config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion.
# Specify mux value.
... | python | {
"resource": ""
} |
q255771 | ADS1x15._read_comparator | validation | def _read_comparator(self, mux, gain, data_rate, mode, high_threshold,
low_threshold, active_low, traditional, latching,
num_readings):
"""Perform an ADC read with the provided mux, gain, data_rate, and mode
values and with the comparator enabled as spec... | python | {
"resource": ""
} |
q255772 | ADS1x15.read_adc | validation | def read_adc(self, channel, gain=1, data_rate=None):
"""Read a single ADC channel and return the ADC value as a signed integer
result. Channel must be a value within 0-3.
"""
assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'
# Perform a single shot read and set the... | python | {
"resource": ""
} |
q255773 | ADS1x15.get_last_result | validation | def get_last_result(self):
"""Read the last conversion result when in continuous conversion mode.
Will return a signed integer value.
"""
# Retrieve the conversion register value, convert to a signed int, and
# return it.
result = self._device.readList(ADS1x15_POINTER_CON... | python | {
"resource": ""
} |
q255774 | remove_exited_dusty_containers | validation | def remove_exited_dusty_containers():
"""Removed all dusty containers with 'Exited' in their status"""
client = get_docker_client()
exited_containers = get_exited_dusty_containers()
removed_containers = []
for container in exited_containers:
log_to_client("Removing container {}".format(conta... | python | {
"resource": ""
} |
q255775 | remove_images | validation | def remove_images():
"""Removes all dangling images as well as all images referenced in a dusty spec; forceful removal is not used"""
client = get_docker_client()
removed = _remove_dangling_images()
dusty_images = get_dusty_images()
all_images = client.images(all=True)
for image in all_images:
... | python | {
"resource": ""
} |
q255776 | update_nginx_from_config | validation | def update_nginx_from_config(nginx_config):
"""Write the given config to disk as a Dusty sub-config
in the Nginx includes directory. Then, either start nginx
or tell it to reload its config to pick up what we've
just written."""
logging.info('Updating nginx with new Dusty config')
temp_dir = tem... | python | {
"resource": ""
} |
q255777 | update_running_containers_from_spec | validation | def update_running_containers_from_spec(compose_config, recreate_containers=True):
"""Takes in a Compose spec from the Dusty Compose compiler,
writes it to the Compose spec folder so Compose can pick it
up, then does everything needed to make sure the Docker VM is
up and running containers with the upda... | python | {
"resource": ""
} |
q255778 | Repo.resolve | validation | def resolve(cls, all_known_repos, name):
"""We require the list of all remote repo paths to be passed in
to this because otherwise we would need to import the spec assembler
in this module, which would give us circular imports."""
match = None
for repo in all_known_repos:
... | python | {
"resource": ""
} |
q255779 | Repo.ensure_local_repo | validation | def ensure_local_repo(self):
"""Given a Dusty repo object, clone the remote into Dusty's local repos
directory if it does not already exist."""
if os.path.exists(self.managed_path):
logging.debug('Repo {} already exists'.format(self.remote_path))
return
logging.i... | python | {
"resource": ""
} |
q255780 | Repo.update_local_repo_async | validation | def update_local_repo_async(self, task_queue, force=False):
"""Local repo updating suitable for asynchronous, parallel execution.
We still need to run `ensure_local_repo` synchronously because it
does a bunch of non-threadsafe filesystem operations."""
self.ensure_local_repo()
ta... | python | {
"resource": ""
} |
q255781 | update_managed_repos | validation | def update_managed_repos(force=False):
"""For any active, managed repos, update the Dusty-managed
copy to bring it up to date with the latest master."""
log_to_client('Pulling latest updates for all active managed repos:')
update_specs_repo_and_known_hosts()
repos_to_update = get_all_repos(active_on... | python | {
"resource": ""
} |
q255782 | prep_for_start_local_env | validation | def prep_for_start_local_env(pull_repos):
"""Daemon-side command to ensure we're running the latest
versions of any managed repos, including the
specs repo, before we do anything else in the up flow."""
if pull_repos:
update_managed_repos(force=True)
assembled_spec = spec_assembler.get_assem... | python | {
"resource": ""
} |
q255783 | start_local_env | validation | def start_local_env(recreate_containers):
"""This command will use the compilers to get compose specs
will pass those specs to the systems that need them. Those
systems will in turn launch the services needed to make the
local environment go."""
assembled_spec = spec_assembler.get_assembled_specs()... | python | {
"resource": ""
} |
q255784 | stop_apps_or_services | validation | def stop_apps_or_services(app_or_service_names=None, rm_containers=False):
"""Stop any currently running Docker containers associated with
Dusty, or associated with the provided apps_or_services. Does not remove
the service's containers."""
if app_or_service_names:
log_to_client("Stopping the fo... | python | {
"resource": ""
} |
q255785 | restart_apps_or_services | validation | def restart_apps_or_services(app_or_service_names=None):
"""Restart any containers associated with Dusty, or associated with
the provided app_or_service_names."""
if app_or_service_names:
log_to_client("Restarting the following apps or services: {}".format(', '.join(app_or_service_names)))
else:... | python | {
"resource": ""
} |
q255786 | case_insensitive_rename | validation | def case_insensitive_rename(src, dst):
"""A hack to allow us to rename paths in a case-insensitive filesystem like HFS."""
temp_dir = tempfile.mkdtemp()
shutil.rmtree(temp_dir)
shutil.move(src, temp_dir)
shutil.move(temp_dir, dst) | python | {
"resource": ""
} |
q255787 | _compose_dict_for_nginx | validation | def _compose_dict_for_nginx(port_specs):
"""Return a dictionary containing the Compose spec required to run
Dusty's nginx container used for host forwarding."""
spec = {'image': constants.NGINX_IMAGE,
'volumes': ['{}:{}'.format(constants.NGINX_CONFIG_DIR_IN_VM, constants.NGINX_CONFIG_DIR_IN_CONT... | python | {
"resource": ""
} |
q255788 | get_compose_dict | validation | def get_compose_dict(assembled_specs, port_specs):
""" This function returns a dictionary representation of a docker-compose.yml file, based on assembled_specs from
the spec_assembler, and port_specs from the port_spec compiler """
compose_dict = _compose_dict_for_nginx(port_specs)
for app_name in assem... | python | {
"resource": ""
} |
q255789 | _conditional_links | validation | def _conditional_links(assembled_specs, app_name):
""" Given the assembled specs and app_name, this function will return all apps and services specified in
'conditional_links' if they are specified in 'apps' or 'services' in assembled_specs. That means that
some other part of the system has declared them as... | python | {
"resource": ""
} |
q255790 | _get_build_path | validation | def _get_build_path(app_spec):
""" Given a spec for an app, returns the value of the `build` field for docker-compose.
If the path is relative, it is expanded and added to the path of the app's repo. """
if os.path.isabs(app_spec['build']):
return app_spec['build']
return os.path.join(Repo(app_s... | python | {
"resource": ""
} |
q255791 | _composed_app_dict | validation | def _composed_app_dict(app_name, assembled_specs, port_specs):
""" This function returns a dictionary of the docker-compose.yml specifications for one app """
logging.info("Compose Compiler: Compiling dict for app {}".format(app_name))
app_spec = assembled_specs['apps'][app_name]
compose_dict = app_spec... | python | {
"resource": ""
} |
q255792 | _composed_service_dict | validation | def _composed_service_dict(service_spec):
"""This function returns a dictionary of the docker_compose specifications
for one service. Currently, this is just the Dusty service spec with
an additional volume mount to support Dusty's cp functionality."""
compose_dict = service_spec.plain_dict()
_apply... | python | {
"resource": ""
} |
q255793 | _get_ports_list | validation | def _get_ports_list(app_name, port_specs):
""" Returns a list of formatted port mappings for an app """
if app_name not in port_specs['docker_compose']:
return []
return ["{}:{}".format(port_spec['mapped_host_port'], port_spec['in_container_port'])
for port_spec in port_specs['docker_com... | python | {
"resource": ""
} |
q255794 | _get_compose_volumes | validation | def _get_compose_volumes(app_name, assembled_specs):
""" This returns formatted volume specifications for a docker-compose app. We mount the app
as well as any libs it needs so that local code is used in our container, instead of whatever
code was in the docker image.
Additionally, we create a volume f... | python | {
"resource": ""
} |
q255795 | _env_vars_from_file | validation | def _env_vars_from_file(filename):
"""
This code is copied from Docker Compose, so that we're exactly compatible
with their `env_file` option
"""
def split_env(env):
if '=' in env:
return env.split('=', 1)
else:
return env, None
env = {}
for line in op... | python | {
"resource": ""
} |
q255796 | _expand_libs_in_apps | validation | def _expand_libs_in_apps(specs):
"""
Expands specs.apps.depends.libs to include any indirectly required libs
"""
for app_name, app_spec in specs['apps'].iteritems():
if 'depends' in app_spec and 'libs' in app_spec['depends']:
app_spec['depends']['libs'] = _get_dependent('libs', app_n... | python | {
"resource": ""
} |
q255797 | _expand_libs_in_libs | validation | def _expand_libs_in_libs(specs):
"""
Expands specs.libs.depends.libs to include any indirectly required libs
"""
for lib_name, lib_spec in specs['libs'].iteritems():
if 'depends' in lib_spec and 'libs' in lib_spec['depends']:
lib_spec['depends']['libs'] = _get_dependent('libs', lib_n... | python | {
"resource": ""
} |
q255798 | _get_referenced_libs | validation | def _get_referenced_libs(specs):
"""
Returns all libs that are referenced in specs.apps.depends.libs
"""
active_libs = set()
for app_spec in specs['apps'].values():
for lib in app_spec['depends']['libs']:
active_libs.add(lib)
return active_libs | python | {
"resource": ""
} |
q255799 | _get_referenced_services | validation | def _get_referenced_services(specs):
"""
Returns all services that are referenced in specs.apps.depends.services,
or in specs.bundles.services
"""
active_services = set()
for app_spec in specs['apps'].values():
for service in app_spec['depends']['services']:
active_services.a... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.