_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 = parsers.parse_watermark_notification(watermark_notification) await self.on_watermark_notification.fire(res) try:
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( request_header=self._client.get_request_header(), last_sync_timestamp=parsers.to_timestamp( self._sync_timestamp ), max_response_size_bytes=1048576, # 1 MB ) ) except exceptions.NetworkError as e: logger.warning('Failed to sync events, some events may be lost: {}' .format(e)) else: for conv_state in res.conversation_state: conv_id = conv_state.conversation_id.id conv = self._conv_dict.get(conv_id, None) if conv is not None: conv.update_conversation(conv_state.conversation)
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. """ if user_.name_type > self.name_type:
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: :class:`~hangups.user.User` object. """ user_id = UserID(chat_id=entity.id.chat_id, gaia_id=entity.id.gaia_id)
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
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:
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 with %s name "%s"',
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.
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.
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:
python
{ "resource": "" }
q255710
markdown
validation
def markdown(tag): """Return start and end regex pattern sequences for simple Markdown tag.""" return
python
{ "resource": "" }
q255711
html
validation
def html(tag): """Return sequence of start and end regex patterns for simple HTML tag""" return
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 example. """ args = _get_parser(extra_args).parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) # Obtain hangups authentication cookies, prompting for credentials from # standard input if necessary. cookies = hangups.auth.get_auth_stdin(args.token_path)
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.txt') parser.add_argument( '--token-path', default=default_token_path, help='path used to store OAuth refresh token' )
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 = asyncio.Future() client.on_connect.add_observer(lambda: on_connect.set_result(None)) done, _ = await asyncio.wait( (on_connect, task), return_when=asyncio.FIRST_COMPLETED ) await asyncio.gather(*done)
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.SourceCodeInfo.Location instances. path: Path tuple to the enum definition. name_prefix: Optional prefix for this enum's name. """ print(make_subsection(name_prefix + enum_descriptor.name)) location = locations[path] if location.HasField('leading_comments'):
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 tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the message definition. name_prefix: Optional prefix for this message's name. """ # message_type is 4 prefixed_name = name_prefix + message_descriptor.name print(make_subsection(prefixed_name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for field_index, field in enumerate(message_descriptor.field): field_location = locations[path + (2, field_index)] if field.type not in [11, 14]: type_str = TYPE_TO_STR[field.type] else: type_str = make_link(field.type_name.lstrip('.')) row_tuples.append(( make_code(field.name), field.number, type_str, LABEL_TO_STR[field.label],
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()[1] try: subprocess.check_output(['protoc', '--include_source_info',
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=no-member file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString( proto_file.read() ) # pylint: enable=no-member for file_descriptor in file_descriptor_set.file: # Build dict of location tuples locations = {} for location in file_descriptor.source_code_info.location: locations[tuple(location.path)] = location # Add comment to top
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:
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 containing
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:
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_widget = current_widget.get_menu_widget(self._hide_menu) overlay = urwid.Overlay(menu_widget, self._tabbed_window,
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( self._client, self._coroutine_queue,
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)
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_picker = ConversationPickerWidget(self._conv_list, self.on_select_conversation,
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), not user.is_self, not conv.is_quiet, )) if show_notification: self.add_conversation_tab(conv_event.conversation_id) if
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
python
{ "resource": "" }
q255729
CoroutineQueue.consume
validation
async def consume(self): """Consume coroutines from the queue by executing them.""" while True:
python
{ "resource": "" }
q255730
RenameConversationDialog._rename
validation
def _rename(self, name, callback): """Rename conversation and call callback."""
python
{ "resource": "" }
q255731
ConversationListWalker._on_event
validation
def _on_event(self, _): """Re-order the conversations when an event occurs.""" #
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(
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):
python
{ "resource": "" }
q255734
StatusLineWidget._on_typing
validation
def _on_typing(self, typing_message): """Handle typing updates."""
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_users if not user.is_self] if displayed_names: typing_message = '{} {} typing...'.format( ', '.join(sorted(displayed_names)), 'is' if len(displayed_names) == 1 else
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'
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. """ user = conversation.get_user(conv_event.user_id) # Check whether the previous event occurred on the same day as this # event. if prev_conv_event is not None: is_new_day = (conv_event.timestamp.astimezone(tz=None).date() != prev_conv_event.timestamp.astimezone(tz=None).date()) else: is_new_day = False if isinstance(conv_event, hangups.ChatMessageEvent): return MessageWidget(conv_event.timestamp, conv_event.text, datetimefmt, user, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.RenameEvent): if conv_event.new_name == '': text = ('{} cleared the conversation name' .format(user.first_name)) else: text = ('{} renamed the conversation to {}' .format(user.first_name, conv_event.new_name)) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.MembershipChangeEvent): event_users = [conversation.get_user(user_id) for user_id in conv_event.participant_ids] names = ', '.join([user.full_name for user in event_users]) if conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN: text = ('{} added {} to the conversation' .format(user.first_name, names)) else: # LEAVE text = ('{} left the conversation'.format(names)) return MessageWidget(conv_event.timestamp, text, datetimefmt, show_date=is_new_day, watermark_users=watermark_users) elif isinstance(conv_event, hangups.HangoutEvent): text = {
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.
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_events: self._first_loaded = True if self._focus_position == self.POSITION_LOADING and conv_events: # If the loading indicator is still focused, and we loaded more # events, set focus on the first new event so the loaded # indicator is replaced.
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:
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(
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
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,
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 uploads filename = text.split(' ')[1] image_file = open(filename, 'rb') text = '' else: image_file = None
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
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 == self._keys['next_tab']: self._tab_index = (self._tab_index + 1) % num_tabs self._update_tabs() elif key == self._keys['close_tab']: # Don't allow closing the Conversations tab
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(' '):
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 are required to log in. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Returns: dict: Google session cookies. Raises: GoogleAuthError: If authentication with Google fails. """ with requests.Session() as session: session.headers = {'user-agent': USER_AGENT} try: logger.info('Authenticating with refresh token') refresh_token = refresh_token_cache.get() if refresh_token is None: raise GoogleAuthError("Refresh token not found") access_token = _auth_with_refresh_token(session, refresh_token) except GoogleAuthError as e: logger.info('Failed to authenticate using refresh token: %s', e) logger.info('Authenticating with 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 is the most fragile part of the authentication process, because a change to a login form or an unexpected prompt could break it. Raises GoogleAuthError authentication fails. Returns authorization code string. """ browser = Browser(session, OAUTH2_LOGIN_URL) email = credentials_prompt.get_email() browser.submit_form(FORM_SELECTOR, {EMAIL_SELECTOR: email}) password = credentials_prompt.get_password() browser.submit_form(FORM_SELECTOR, {PASSWORD_SELECTOR: password}) if browser.has_selector(TOTP_CHALLENGE_SELECTOR): browser.submit_form(TOTP_CHALLENGE_SELECTOR, {}) elif browser.has_selector(PHONE_CHALLENGE_SELECTOR): browser.submit_form(PHONE_CHALLENGE_SELECTOR, {}) if browser.has_selector(VERIFICATION_FORM_SELECTOR): if browser.has_selector(TOTP_CODE_SELECTOR):
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': OAUTH2_CLIENT_SECRET,
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, 'client_secret': OAUTH2_CLIENT_SECRET, 'code':
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.RequestException as e: raise GoogleAuthError('Token request failed: {}'.format(e)) else:
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://accounts.google.com/accounts/OAuthLogin' '?source=hangups&issueuberauth=1'), headers=headers) r.raise_for_status() except requests.RequestException as e: raise GoogleAuthError('OAuthLogin request failed: {}'.format(e)) uberauth = r.text try: r = session.get(('https://accounts.google.com/MergeSession?' 'service=mail&'
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:
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( 'Page contains forms: %s', [elem.get('id') for elem in self._page.soup.select('form')] ) try: form = self._page.soup.select(form_selector)[0] except IndexError: raise GoogleAuthError( 'Failed to find form {!r} in page'.format(form_selector) ) logger.info( 'Page contains inputs: %s', [elem.get('id') for elem in form.select('input')] ) for selector, value in input_dict.items(): try: form.select(selector)[0]['value'] = value
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.
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 length is actually the length of the string as reported by JavaScript. JavaScript's string length function returns the number of code units in the string, represented in UTF-16. We can emulate this by encoding everything in UTF-16 and multiplying the reported length by 2. Note that when encoding a string in UTF-16, Python will prepend a byte-order character, so we need to remove the first two bytes. """ self._buf += new_data_bytes while True: buf_decoded = _best_effort_decode(self._buf) buf_utf16 = buf_decoded.encode('utf-16')[2:] length_str_match = LEN_REGEX.match(buf_decoded) if length_str_match is None: break else: length_str = length_str_match.group(1) # Both lengths are in
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 retries <= self._max_retries: # After the first failed retry, back off exponentially longer after # each attempt. if retries > 0: backoff_seconds = self._retry_backoff_base ** retries logger.info('Backing off for %s seconds', backoff_seconds) await asyncio.sleep(backoff_seconds) # Request a new SID if we don't have one yet, or the previous one # became invalid. if need_new_sid: await self._fetch_channel_sid() need_new_sid = False # Clear any previous push data, since if there was an error it # could contain garbage. self._chunk_parser = ChunkParser() try: await self._longpoll_request() except ChannelSessionError as
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 gsessionid with this request, it will return a gsessionid as well as the SID. Raises hangups.NetworkError if the channel can not be created. """ logger.info('Requesting new gsessionid and SID...') # Set SID and gsessionid to None so they aren't sent in by send_maps.
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. """ params = { 'VER': 8, # channel protocol version 'gsessionid': self._gsessionid_param, 'RID': 'rpc', # request identifier 't': 1, # trial 'SID': self._sid_param, # session ID 'CI': 0, # 0 if streaming/chunked requests should be used 'ctype': 'hangouts', # client type 'TYPE': 'xmlhttp', # type of request } logger.info('Opening new long-polling request') try: async with self._session.fetch_raw('GET', CHANNEL_URL,
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 self._is_connected: if self._on_connect_called: self._is_connected = True await self.on_reconnect.fire() else: self._on_connect_called = True self._is_connected = True await self.on_connect.fire() # chunk contains a container array container_array = json.loads(chunk) # container array is an array of inner arrays
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,
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) setattr(message, field.name, value) except
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.type == FieldDescriptor.TYPE_BYTES: value = base64.b64decode(value) getattr(message, field.name).append(value) except (ValueError, TypeError) as e: # ValueError: invalid enum value, negative unsigned int value, or
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_first_item parameter because it contains an abbreviation of the name of the protobuf message (eg. cscmrp for ClientSendChatMessageResponseP) that's not part of the protobuf. Args: message: protocol buffer message instance to decode into. pblite: list representing a pblite-serialized message. ignore_first_item: If True, ignore the item at index 0 in the pblite list, making the item at index 1 correspond to field 1 in the message. """ if not isinstance(pblite, list): logger.warning('Ignoring invalid message: expected list, got %r', type(pblite)) return if ignore_first_item: pblite = pblite[1:] # If the last item of the list is a dict, use it as additional field/value # mappings. This seems to be an optimization added for dealing with really # high field numbers. if pblite and isinstance(pblite[-1], dict): extra_fields = {int(field_number): value for field_number, value in pblite[-1].items()} pblite = pblite[:-1] else: extra_fields
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 """
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_entities = {} for klass in self.orders: number = self.quantities[klass] if klass not in inserted_entities: inserted_entities[klass]
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. config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET # Validate the passed in gain and then set it in the config. if gain not in ADS1x15_CONFIG_GAIN: raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16') config |= ADS1x15_CONFIG_GAIN[gain] # Set the mode (continuous or single shot). config |= mode
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 specified. Returns the signed integer result of the read. """ assert num_readings == 1 or num_readings == 2 or num_readings == 4, 'Num readings must be 1, 2, or 4!' # Set high and low threshold register values. self._device.writeList(ADS1x15_POINTER_HIGH_THRESHOLD, [(high_threshold >> 8) & 0xFF, high_threshold & 0xFF]) self._device.writeList(ADS1x15_POINTER_LOW_THRESHOLD, [(low_threshold >> 8) & 0xFF, low_threshold & 0xFF]) # Now build up the appropriate config register value. config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion. # Specify mux value. config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET # Validate the passed in gain and then set it in the config. if gain not in ADS1x15_CONFIG_GAIN:
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!' #
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.
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
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: if set(image['RepoTags']).intersection(dusty_images): try: client.remove_image(image['Id']) except Exception as e:
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 = tempfile.mkdtemp() os.mkdir(os.path.join(temp_dir, 'html')) _write_nginx_config(constants.NGINX_BASE_CONFIG, os.path.join(temp_dir, constants.NGINX_PRIMARY_CONFIG_NAME)) _write_nginx_config(nginx_config['http'], os.path.join(temp_dir, constants.NGINX_HTTP_CONFIG_NAME))
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
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: if repo.remote_path == name: # user passed in a full name return repo if name == repo.short_name: if match is None: match = repo else: raise RuntimeError('Short repo name {} is ambiguous. It matches both {} and {}'.format(name,
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.info('Initiating clone of local repo {}'.format(self.remote_path))
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
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_only=True, include_specs_repo=False) with
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_assembled_specs()
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() required_absent_assets = virtualbox.required_absent_assets(assembled_spec) if required_absent_assets: raise RuntimeError('Assets {} are specified as required but are not set. Set them with `dusty assets set`'.format(required_absent_assets)) docker_ip = virtualbox.get_docker_vm_ip() # Stop will fail if we've never written a Composefile before if os.path.exists(constants.COMPOSEFILE_PATH): try: stop_apps_or_services(rm_containers=recreate_containers) except CalledProcessError as e: log_to_client("WARNING: docker-compose stop failed") log_to_client(str(e)) daemon_warnings.clear_namespace('disk') df_info = virtualbox.get_docker_vm_disk_info(as_dict=True) if 'M' in df_info['free'] or 'K' in df_info['free']: warning_msg = 'VM is low on disk. Available disk: {}'.format(df_info['free']) daemon_warnings.warn('disk', warning_msg) log_to_client(warning_msg) log_to_client("Compiling together the assembled specs") active_repos = spec_assembler.get_all_repos(active_only=True, include_specs_repo=False) log_to_client("Compiling
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."""
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: log_to_client("Restarting all active containers associated with Dusty") if app_or_service_names: specs = spec_assembler.get_assembled_specs() specs_list = [specs['apps'][app_name] for app_name in app_or_service_names if app_name in specs['apps']] repos = set() for spec in specs_list: if
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 =
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_CONTAINER)], 'command': 'nginx -g "daemon off;" -c /etc/nginx/conf.d/nginx.primary', 'container_name': 'dusty_{}_1'.format(constants.DUSTY_NGINX_NAME)}
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 assembled_specs['apps'].keys():
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 necessary, so they should be linked to this app """ link_to_apps = [] potential_links = assembled_specs['apps'][app_name]['conditional_links'] for potential_link in potential_links['apps']:
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
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["compose"] _apply_env_overrides(env_overrides_for_app_or_service(app_name), compose_dict) if 'image' in app_spec and 'build' in app_spec: raise RuntimeError("image and build are both specified in the spec for {}".format(app_name)) elif 'image' in app_spec: logging.info compose_dict['image'] = app_spec['image'] elif 'build' in app_spec: compose_dict['build'] = _get_build_path(app_spec) else: raise RuntimeError("Neither image nor build was specified in the spec for {}".format(app_name)) compose_dict['entrypoint'] = [] compose_dict['command'] = _compile_docker_command(app_spec) compose_dict['container_name'] = "dusty_{}_1".format(app_name) logging.info("Compose Compiler: compiled command {}".format(compose_dict['command'])) compose_dict['links']
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_env_overrides(env_overrides_for_app_or_service(service_spec.name), compose_dict)
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']:
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 for the /cp directory used by Dusty to facilitate
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:
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
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
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():
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
python
{ "resource": "" }