_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q28600
message_from_string
train
def message_from_string(s, *args, **kws): """Parse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. """
python
{ "resource": "" }
q28601
message_from_bytes
train
def message_from_bytes(s, *args, **kws): """Parse a bytes string into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from
python
{ "resource": "" }
q28602
message_from_file
train
def message_from_file(fp, *args, **kws): """Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. """
python
{ "resource": "" }
q28603
message_from_binary_file
train
def message_from_binary_file(fp, *args, **kws): """Read a binary file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor.
python
{ "resource": "" }
q28604
HTTPResponse._safe_read
train
def _safe_read(self, amt): """Read the number of bytes requested, compensating for partial reads. Normally, we have a blocking socket, but a read() can be interrupted by a signal (resulting in a partial read). Note that we cannot distinguish between EOF and an interrupt when zero ...
python
{ "resource": "" }
q28605
HTTPResponse._safe_readinto
train
def _safe_readinto(self, b): """Same as _safe_read, but for reading into a buffer.""" total_bytes = 0 mvb = memoryview(b) while total_bytes < len(b): if MAXAMOUNT < len(mvb): temp_mvb = mvb[0:MAXAMOUNT] n = self.fp.readinto(temp_mvb) ...
python
{ "resource": "" }
q28606
HTTPConnection.set_tunnel
train
def set_tunnel(self, host, port=None, headers=None): """ Sets up the host and the port for the HTTP CONNECT Tunnelling. The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request. """ self._tunnel_host
python
{ "resource": "" }
q28607
HTTPConnection.close
train
def close(self): """Close the connection to the HTTP server.""" if self.sock: self.sock.close() # close it manually...
python
{ "resource": "" }
q28608
HTTPConnection._send_output
train
def _send_output(self, message_body=None): """Send the currently buffered request and clear the buffer. Appends an extra \\r\\n to the buffer. A message_body may be specified, to be appended to the request. """ self._buffer.extend((bytes(b""), bytes(b""))) msg = bytes(b"...
python
{ "resource": "" }
q28609
HTTPConnection.putheader
train
def putheader(self, header, *values): """Send a request header line to the server. For example: h.putheader('Accept', 'text/html') """ if self.__state != _CS_REQ_STARTED: raise CannotSendHeader() if hasattr(header, 'encode'): header = header.encode('asci...
python
{ "resource": "" }
q28610
HTTPConnection.endheaders
train
def endheaders(self, message_body=None): """Indicate that the last header line has been sent to the server. This method sends the request to the server. The optional message_body argument can be used to pass a message body associated with the request. The message body will be sent in ...
python
{ "resource": "" }
q28611
HTTPConnection.request
train
def request(self, method, url, body=None, headers={}): """Send a complete request to the server."""
python
{ "resource": "" }
q28612
HTTPConnection.getresponse
train
def getresponse(self): """Get the response from the server. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by class the response_class variable. If a request has not been sent or if a previous response has ...
python
{ "resource": "" }
q28613
_validate_xtext
train
def _validate_xtext(xtext): """If input token contains ASCII non-printables, register a defect.""" non_printables = _non_printable_finder(xtext) if non_printables: xtext.defects.append(errors.NonPrintableDefect(non_printables))
python
{ "resource": "" }
q28614
_decode_ew_run
train
def _decode_ew_run(value): """ Decode a run of RFC2047 encoded words. _decode_ew_run(value) -> (text, value, defects) Scans the supplied value for a run of tokens that look like they are RFC 2047 encoded words, decodes those words into text according to RFC 2047 rules (whitespace between encod...
python
{ "resource": "" }
q28615
get_encoded_word
train
def get_encoded_word(value): """ encoded-word = "=?" charset "?" encoding "?" encoded-text "?=" """ ew = EncodedWord() if not value.startswith('=?'): raise errors.HeaderParseError( "expected encoded word but found {}".format(value)) _3to2list1 = list(value[2:].split('?=', 1)) ...
python
{ "resource": "" }
q28616
get_display_name
train
def get_display_name(value): """ display-name = phrase Because this is simply a name-rule, we don't return a display-name token containing a phrase, but rather a display-name
python
{ "resource": "" }
q28617
get_invalid_mailbox
train
def get_invalid_mailbox(value, endchars): """ Read everything up to one of the chars in endchars. This is outside the formal grammar. The InvalidMailbox TokenList that is returned acts like a Mailbox, but the data attributes are None. """ invalid_mailbox = InvalidMailbox()
python
{ "resource": "" }
q28618
get_invalid_parameter
train
def get_invalid_parameter(value): """ Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. """ invalid_parameter = InvalidParameter() while value and value[0] != ';': ...
python
{ "resource": "" }
q28619
_find_mime_parameters
train
def _find_mime_parameters(tokenlist, value): """Do our best to find the parameters in an invalid MIME header """ while value and value[0] != ';': if value[0] in PHRASE_ENDS: tokenlist.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] else: ...
python
{ "resource": "" }
q28620
header_length
train
def header_length(bytearray): """Return the length of s when it is encoded with base64.""" groups_of_3, leftover =
python
{ "resource": "" }
q28621
header_encode
train
def header_encode(header_bytes, charset='iso-8859-1'): """Encode a single header line with Base64 encoding in a given charset. charset names the character set to use to encode the header. It defaults to iso-8859-1. Base64 encoding is defined in RFC 2045. """ if not header_bytes: return ""
python
{ "resource": "" }
q28622
body_encode
train
def body_encode(s, maxlinelen=76, eol=NL): r"""Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this fun...
python
{ "resource": "" }
q28623
decode
train
def decode(string): """Decode a raw base64 string, returning a bytes object. This function does not parse a full MIME header value encoded with base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. """ if not string: return
python
{ "resource": "" }
q28624
urldefrag
train
def urldefrag(url): """Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the empty string. """ url, _coerce_result = _coerce_args(url) if '#' in url: s,
python
{ "resource": "" }
q28625
body_encode
train
def body_encode(body, maxlinelen=76, eol=NL): """Encode with quoted-printable, wrapping at maxlinelen characters. Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly in an email. Each line will be wra...
python
{ "resource": "" }
q28626
decode
train
def decode(encoded, eol=NL): """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ if not encoded: return encoded # BAW: see comment in encode() above. Again, we're building up the # decoded string with string concatenation, which could be done m...
python
{ "resource": "" }
q28627
header_decode
train
def header_decode(s): """Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use the high level email.header
python
{ "resource": "" }
q28628
_body_accumulator.write_str
train
def write_str(self, s): """Add string s to the accumulated body."""
python
{ "resource": "" }
q28629
_body_accumulator.newline
train
def newline(self): """Write eol, then start new line."""
python
{ "resource": "" }
q28630
_body_accumulator.write_wrapped
train
def write_wrapped(self, s, extra_room=0): """Add a soft line break if needed, then
python
{ "resource": "" }
q28631
HTMLParser.reset
train
def reset(self): """Reset this instance. Loses all unprocessed data.""" self.rawdata = '' self.lasttag = '???'
python
{ "resource": "" }
q28632
HTMLParser.feed
train
def feed(self, data): r"""Feed data to the parser. Call this as often as you want, with as little or as much text as you want
python
{ "resource": "" }
q28633
encode_base64
train
def encode_base64(msg): """Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata
python
{ "resource": "" }
q28634
encode_quopri
train
def encode_quopri(msg): """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata
python
{ "resource": "" }
q28635
encode_7or8bit
train
def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload() if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fas...
python
{ "resource": "" }
q28636
encode_noop
train
def encode_noop(msg): """Do nothing.""" # Well, not quite *nothing*: in Python3 we have to turn bytes into a string # in our internal surrogateescaped form in order to keep the model # consistent.
python
{ "resource": "" }
q28637
is_py2_stdlib_module
train
def is_py2_stdlib_module(m): """ Tries to infer whether the module m is from the Python 2 standard library. This may not be reliable on all systems. """ if PY3: return False if not 'stdlib_path' in is_py2_stdlib_module.__dict__: stdlib_files = [contextlib.__file__, os.__file__, c...
python
{ "resource": "" }
q28638
restore_sys_modules
train
def restore_sys_modules(scrubbed): """ Add any previously scrubbed modules back to the sys.modules cache, but only if it's safe to do so. """ clash = set(sys.modules) & set(scrubbed) if len(clash) != 0: # If several, choose one arbitrarily to raise an exception about first
python
{ "resource": "" }
q28639
install_hooks
train
def install_hooks(): """ This function installs the future.standard_library import hook into sys.meta_path. """ if PY3: return install_aliases() flog.debug('sys.meta_path was: {0}'.format(sys.meta_path)) flog.debug('Installing hooks ...') # Add it unless
python
{ "resource": "" }
q28640
remove_hooks
train
def remove_hooks(scrub_sys_modules=False): """ This function removes the import hook from sys.meta_path. """ if PY3: return flog.debug('Uninstalling hooks ...') # Loop backwards, so deleting items keeps the ordering: for i, hook in list(enumerate(sys.meta_path))[::-1]: if has...
python
{ "resource": "" }
q28641
detect_hooks
train
def detect_hooks(): """ Returns True if the import hooks are installed, False if not. """ flog.debug('Detecting hooks ...') present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path]) if
python
{ "resource": "" }
q28642
RenameImport._find_and_load_module
train
def _find_and_load_module(self, name, path=None): """ Finds and loads it. But if there's a . in the name, handles it properly. """ bits = name.split('.') while len(bits) > 1: # Treat the first bit as a package packagename = bits.pop(0) ...
python
{ "resource": "" }
q28643
format_datetime
train
def format_datetime(dt, usegmt=False): """Turn a datetime into a date string as specified in RFC 2822. If usegmt is True, dt must be an aware datetime with an offset of zero. In this case 'GMT' will be rendered instead of the normal +0000 required by RFC2822. This is to support HTTP headers involving...
python
{ "resource": "" }
q28644
unquote
train
def unquote(str): """Remove quotes from a string.""" if len(str) > 1: if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
python
{ "resource": "" }
q28645
decode_rfc2231
train
def decode_rfc2231(s): """Decode string according to RFC 2231""" parts = s.split(TICK, 2)
python
{ "resource": "" }
q28646
encode_rfc2231
train
def encode_rfc2231(s, charset=None, language=None): """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the
python
{ "resource": "" }
q28647
decode_params
train
def decode_params(params): """Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). """ # Copy params so we don't mess with the original params = params[:] new_params = [] # Map parameter's name to a list of continuations. The...
python
{ "resource": "" }
q28648
localtime
train
def localtime(dt=None, isdst=-1): """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If *dt* is naive (tha...
python
{ "resource": "" }
q28649
filepath_to_uri
train
def filepath_to_uri(path): """Convert a file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method doe...
python
{ "resource": "" }
q28650
encode
train
def encode(string, charset='utf-8', encoding=None, lang=''): """Encode string using the CTE encoding that produces the shorter result. Produces an RFC 2047/2243 encoded word of the form: =?charset*lang?cte?encoded_string?= where '*lang' is omitted unless the 'lang' parameter is given a value. ...
python
{ "resource": "" }
q28651
bind_method
train
def bind_method(cls, name, func): """Bind a method to class, python 2 and python 3 compatible. Parameters ---------- cls : type class to receive bound method name : basestring name of method on class instance func : function function to be bound as method
python
{ "resource": "" }
q28652
_PolicyBase.clone
train
def clone(self, **kw): """Return a new instance with specified attributes changed. The new instance has the same attribute values as the current object, except for the changes passed in as keyword arguments. """ newpolicy = self.__class__.__new__(self.__class__) for att...
python
{ "resource": "" }
q28653
Policy.handle_defect
train
def handle_defect(self, obj, defect): """Based on policy, either raise defect or call register_defect. handle_defect(obj, defect) defect should be a Defect subclass, but in any case must be an Exception subclass. obj is the object on which the defect should be
python
{ "resource": "" }
q28654
_quote
train
def _quote(str, LegalChars=_LegalChars): r"""Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string.
python
{ "resource": "" }
q28655
BaseCookie.output
train
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): """Return a string suitable for HTTP."""
python
{ "resource": "" }
q28656
BaseCookie.js_output
train
def js_output(self, attrs=None): """Return a string suitable for JavaScript.""" result = [] items = sorted(self.items())
python
{ "resource": "" }
q28657
_whatsnd
train
def _whatsnd(data): """Try to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix. """ hdr = data[:...
python
{ "resource": "" }
q28658
fixup_parse_tree
train
def fixup_parse_tree(cls_node): """ one-line classes don't get a suite in the parse tree so we add one to normalize the tree """ for node in cls_node.children: if node.type == syms.suite: # already in the preferred format, do nothing return # !%@#! oneliners have...
python
{ "resource": "" }
q28659
newbytes.index
train
def index(self, sub, *args): ''' Returns index of sub in bytes. Raises ValueError if byte is not in bytes and TypeError if can't be converted bytes or its length is not 1. ''' if isinstance(sub, int): if len(args) == 0: start, end = 0, len(self...
python
{ "resource": "" }
q28660
isidentifier
train
def isidentifier(s, dotted=False): ''' A function equivalent to the str.isidentifier method on Py3 ''' if dotted: return all(isidentifier(a) for
python
{ "resource": "" }
q28661
viewitems
train
def viewitems(obj, **kwargs): """ Function for iterating over dictionary items with the same set-like behaviour on Py2.7 as on Py3. Passes kwargs to method."""
python
{ "resource": "" }
q28662
viewkeys
train
def viewkeys(obj, **kwargs): """ Function for iterating over dictionary keys with the same set-like behaviour on Py2.7 as on Py3. Passes kwargs to method."""
python
{ "resource": "" }
q28663
viewvalues
train
def viewvalues(obj, **kwargs): """ Function for iterating over dictionary values with the same set-like behaviour on Py2.7 as on Py3. Passes kwargs to method."""
python
{ "resource": "" }
q28664
_get_caller_globals_and_locals
train
def _get_caller_globals_and_locals(): """ Returns the globals and locals of the calling frame. Is there an alternative to frame hacking here? """ caller_frame = inspect.stack()[2]
python
{ "resource": "" }
q28665
_repr_strip
train
def _repr_strip(mystring): """ Returns the string without any initial or final quotes. """ r = repr(mystring) if r.startswith("'")
python
{ "resource": "" }
q28666
as_native_str
train
def as_native_str(encoding='utf-8'): ''' A decorator to turn a function or method call that returns text, i.e. unicode, into one that returns a native platform str. Use it as a decorator like this:: from __future__ import unicode_literals class MyClass(object): @as_native_...
python
{ "resource": "" }
q28667
Plotter.bind
train
def bind(self, source=None, destination=None, node=None, edge_title=None, edge_label=None, edge_color=None, edge_weight=None, point_title=None, point_label=None, point_color=None, point_size=None): """Relate data attributes to graph structure and visual representation. To faci...
python
{ "resource": "" }
q28668
Plotter.nodes
train
def nodes(self, nodes): """Specify the set of nodes and associated data. Must include any nodes referenced in the edge list. :param nodes: Nodes and their attributes. :type point_size: Pandas dataframe :returns: Plotter. :rtype: Plotter. **Example** ...
python
{ "resource": "" }
q28669
Plotter.edges
train
def edges(self, edges): """Specify edge list data and associated edge attribute values. :param edges: Edges and their attributes. :type point_size: Pandas dataframe, NetworkX graph, or IGraph graph. :returns: Plotter. :rtype: Plotter. **Example** :: ...
python
{ "resource": "" }
q28670
Plotter.graph
train
def graph(self, ig): """Specify the node and edge data. :param ig: Graph with node and edge attributes. :type ig: NetworkX graph
python
{ "resource": "" }
q28671
Plotter.settings
train
def settings(self, height=None, url_params={}, render=None): """Specify iframe height and add URL parameter dictionary. The library takes care of URI component encoding for the dictionary. :param height: Height in pixels. :type height: Integer. :param url_params: Dictionary of...
python
{ "resource": "" }
q28672
Plotter.plot
train
def plot(self, graph=None, nodes=None, name=None, render=None, skip_upload=False): """Upload data to the Graphistry server and show as an iframe of it. name, Uses the currently bound schema structure and visual encodings. Optional parameters override the current bindings. When used in ...
python
{ "resource": "" }
q28673
Plotter.pandas2igraph
train
def pandas2igraph(self, edges, directed=True): """Convert a pandas edge dataframe to an IGraph graph. Uses current bindings. Defaults to treating edges as directed. **Example** :: import graphistry g = graphistry.bind() es = pandas....
python
{ "resource": "" }
q28674
Plotter.igraph2pandas
train
def igraph2pandas(self, ig): """Under current bindings, transform an IGraph into a pandas edges dataframe and a nodes dataframe. **Example** :: import graphistry g = graphistry.bind() es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]}) ...
python
{ "resource": "" }
q28675
PyGraphistry.authenticate
train
def authenticate(): """Authenticate via already provided configuration. This is called once automatically per session when uploading and rendering a visualization.""" key = PyGraphistry.api_key() #Mocks may set to True, so bypass in that case if (key is None) and PyGraphistry._is...
python
{ "resource": "" }
q28676
PyGraphistry.api_key
train
def api_key(value=None): """Set or get the API key. Also set via environment variable GRAPHISTRY_API_KEY.""" if value is None:
python
{ "resource": "" }
q28677
PyGraphistry.register
train
def register(key=None, server=None, protocol=None, api=None, certificate_validation=None, bolt=None): """API key registration and server selection Changing the key effects all derived Plotter instances. :param key: API key. :type key: String. :param server: URL of the visualiza...
python
{ "resource": "" }
q28678
PyGraphistry.hypergraph
train
def hypergraph(raw_events, entity_types=None, opts={}, drop_na=True, drop_edge_attrs=False, verbose=True, direct=False): """Transform a dataframe into a hypergraph. :param Dataframe raw_events: Dataframe to transform :param List entity_types: Optional list of columns (strings) to turn into node...
python
{ "resource": "" }
q28679
PyGraphistry.bind
train
def bind(node=None, source=None, destination=None, edge_title=None, edge_label=None, edge_color=None, edge_weight=None, point_title=None, point_label=None, point_color=None, point_size=None): """Create a base plotter. Typically called at start of a program. For parameters, see...
python
{ "resource": "" }
q28680
UserAgentRequestHandler.do_HEAD
train
def do_HEAD(self): """Serve a HEAD request.""" self.queue.put(self.headers.get("User-Agent"))
python
{ "resource": "" }
q28681
ProfileLooter.pages
train
def pages(self): # type: () -> ProfileIterator """Obtain an iterator over Instagram post pages. Returns: PageIterator: an iterator over the instagram post pages. Raises: ValueError: when the requested user does not exist. RuntimeError: when the user ...
python
{ "resource": "" }
q28682
PostLooter.medias
train
def medias(self, timeframe=None): """Return a generator that yields only the refered post. Yields: dict: a media dictionary obtained from the given post. Raises: StopIteration: if the post does not fit the timeframe. """ info = self.info if
python
{ "resource": "" }
q28683
PostLooter.download
train
def download(self, destination, # type: Union[str, fs.base.FS] condition=None, # type: Optional[Callable[[dict], bool]] media_count=None, # type: Optional[int] timeframe=None, # type: Optional[_Timeframe] new_only=False, ...
python
{ "resource": "" }
q28684
warn_logging
train
def warn_logging(logger): # type: (logging.Logger) -> Callable """Create a `showwarning` function that uses the given logger. Arguments: logger (~logging.Logger): the logger to use. Returns: function: a function that can be used as the `warnings.showwarning`
python
{ "resource": "" }
q28685
wrap_warnings
train
def wrap_warnings(logger): """Have the function patch `warnings.showwarning` with the given logger. Arguments: logger (~logging.logger): the logger to wrap warnings with when the decorated function is called. Returns: `function`: a decorator function. """ def decorator...
python
{ "resource": "" }
q28686
date_from_isoformat
train
def date_from_isoformat(isoformat_date): """Convert an ISO-8601 date into a `datetime.date` object. Argument: isoformat_date (str): a date in ISO-8601 format (YYYY-MM-DD) Returns: ~datetime.date: the object corresponding to the given ISO date. Raises: ValueError: when the date...
python
{ "resource": "" }
q28687
get_times_from_cli
train
def get_times_from_cli(cli_token): """Convert a CLI token to a datetime tuple. Argument: cli_token (str): an isoformat datetime token ([ISO date]:[ISO date]) or a special value among: * thisday * thisweek * thismonth * thisyear...
python
{ "resource": "" }
q28688
BatchRunner.run_all
train
def run_all(self): # type: () -> None """Run all the jobs specified in the configuration file. """
python
{ "resource": "" }
q28689
BatchRunner.run_job
train
def run_job(self, section_id, session=None): # type: (Text, Optional[Session]) -> None """Run a job as described in the section named ``section_id``. Raises: KeyError: when the section could not be found. """ if not self.parser.has_section(section_id): r...
python
{ "resource": "" }
q28690
html_page_context
train
def html_page_context(app, pagename, templatename, context, doctree): """Event handler for the html-page-context signal. Modifies the context directly. - Replaces the 'toc' value created by the HTML builder with one that shows all document titles and the local table of contents. - Sets display_...
python
{ "resource": "" }
q28691
get_rendered_toctree
train
def get_rendered_toctree(builder, docname, prune=False, collapse=True): """Build the toctree relative to the named document, with the given parameters, and then return the rendered HTML fragment. """ fulltoc = build_full_toctree(builder, docname, ...
python
{ "resource": "" }
q28692
build_full_toctree
train
def build_full_toctree(builder, docname, prune, collapse): """Return a single toctree starting from docname containing all sub-document doctrees. """ env = builder.env doctree = env.get_doctree(env.config.master_doc) toctrees = [] for toctreenode in doctree.traverse(addnodes.toctree): ...
python
{ "resource": "" }
q28693
awsRetry
train
def awsRetry(f): """ This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto """ @wraps(f) def wrapper(*args, **kwargs): for attempt in retry(delays=truncExpBackoff(),
python
{ "resource": "" }
q28694
AWSProvisioner._readClusterSettings
train
def _readClusterSettings(self): """ Reads the cluster settings from the instance metadata, which assumes the instance is the leader. """ instanceMetaData = get_instance_metadata() region = zoneToRegion(self._zone) conn = boto.ec2.connect_to_region(region) ...
python
{ "resource": "" }
q28695
AWSProvisioner.destroyCluster
train
def destroyCluster(self): """ Terminate instances and delete the profile and security group. """ assert self._ctx def expectedShutdownErrors(e): return e.status == 400 and 'dependent object' in e.body instances = self._getNodesInCluster(nodeType=None, both=Tr...
python
{ "resource": "" }
q28696
AWSProvisioner._waitForIP
train
def _waitForIP(cls, instance): """ Wait until the instances has a public IP address assigned to it. :type instance: boto.ec2.instance.Instance """ logger.debug('Waiting for ip...') while True: time.sleep(a_short_time)
python
{ "resource": "" }
q28697
wait_instances_running
train
def wait_instances_running(ec2, instances): """ Wait until no instance in the given iterable is 'pending'. Yield every instance that entered the running state as soon as it does. :param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests :param Iterator[Instance] in...
python
{ "resource": "" }
q28698
wait_spot_requests_active
train
def wait_spot_requests_active(ec2, requests, timeout=None, tentative=False): """ Wait until no spot request in the given iterator is in the 'open' state or, optionally, a timeout occurs. Yield spot requests as soon as they leave the 'open' state. :param Iterator[SpotInstanceRequest] requests: :par...
python
{ "resource": "" }
q28699
create_ondemand_instances
train
def create_ondemand_instances(ec2, image_id, spec, num_instances=1): """ Requests the RunInstances EC2 API call but accounts for the race between recently created instance profiles, IAM roles and an instance creation that refers to them. :rtype: list[Instance] """ instance_type = spec['instance...
python
{ "resource": "" }