idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
60,800
def open_list ( ctx , document , par , root , elem ) : _ls = None if par . ilvl != ctx . ilvl or par . numid != ctx . numid : if ctx . ilvl is not None and ( par . ilvl > ctx . ilvl ) : fmt = _get_numbering ( document , par . numid , par . ilvl ) if par . ilvl > 0 : _b = list ( root ) [ - 1 ] _ls = etree . SubElement ( _b , _get_numbering_tag ( fmt ) ) root = _ls else : _ls = etree . SubElement ( root , _get_numbering_tag ( fmt ) ) root = _ls fire_hooks ( ctx , document , par , _ls , ctx . get_hook ( _get_numbering_tag ( fmt ) ) ) ctx . in_list . append ( ( par . numid , par . ilvl ) ) elif ctx . ilvl is not None and par . ilvl < ctx . ilvl : fmt = _get_numbering ( document , ctx . numid , ctx . ilvl ) try : while True : numid , ilvl = ctx . in_list [ - 1 ] if numid == par . numid and ilvl == par . ilvl : break root = _get_parent ( root ) ctx . in_list . pop ( ) except : pass if par . numid > ctx . numid : fmt = _get_numbering ( document , par . numid , par . ilvl ) _ls = etree . SubElement ( root , _get_numbering_tag ( fmt ) ) fire_hooks ( ctx , document , par , _ls , ctx . get_hook ( _get_numbering_tag ( fmt ) ) ) ctx . in_list . append ( ( par . numid , par . ilvl ) ) root = _ls ctx . ilvl = par . ilvl ctx . numid = par . numid _a = etree . SubElement ( root , 'li' ) _a . text = elem . text for a in list ( elem ) : _a . append ( a ) fire_hooks ( ctx , document , par , _a , ctx . get_hook ( 'li' ) ) return root
Open list if it is needed and place current element as first member of a list .
60,801
def serialize_break ( ctx , document , elem , root ) : "Serialize break element." if elem . break_type == u'textWrapping' : _div = etree . SubElement ( root , 'br' ) else : _div = etree . SubElement ( root , 'span' ) if ctx . options [ 'embed_styles' ] : _div . set ( 'style' , 'page-break-after: always;' ) fire_hooks ( ctx , document , elem , _div , ctx . get_hook ( 'page_break' ) ) return root
Serialize break element .
60,802
def serialize_math ( ctx , document , elem , root ) : _div = etree . SubElement ( root , 'span' ) if ctx . options [ 'embed_styles' ] : _div . set ( 'style' , 'border: 1px solid red' ) _div . text = 'We do not support Math blocks at the moment.' fire_hooks ( ctx , document , elem , _div , ctx . get_hook ( 'math' ) ) return root
Serialize math element .
60,803
def serialize_link ( ctx , document , elem , root ) : _a = etree . SubElement ( root , 'a' ) for el in elem . elements : _ser = ctx . get_serializer ( el ) if _ser : _td = _ser ( ctx , document , el , _a ) else : if isinstance ( el , doc . Text ) : children = list ( _a ) if len ( children ) == 0 : _text = _a . text or u'' _a . text = u'{}{}' . format ( _text , el . value ( ) ) else : _text = children [ - 1 ] . tail or u'' children [ - 1 ] . tail = u'{}{}' . format ( _text , el . value ( ) ) if elem . rid in document . relationships [ ctx . options [ 'relationship' ] ] : _a . set ( 'href' , document . relationships [ ctx . options [ 'relationship' ] ] [ elem . rid ] . get ( 'target' , '' ) ) fire_hooks ( ctx , document , elem , _a , ctx . get_hook ( 'a' ) ) return root
Serilaze link element .
60,804
def serialize_image ( ctx , document , elem , root ) : _img = etree . SubElement ( root , 'img' ) if elem . rid in document . relationships [ ctx . options [ 'relationship' ] ] : img_src = document . relationships [ ctx . options [ 'relationship' ] ] [ elem . rid ] . get ( 'target' , '' ) img_name , img_extension = os . path . splitext ( img_src ) _img . set ( 'src' , 'static/{}{}' . format ( elem . rid , img_extension ) ) fire_hooks ( ctx , document , elem , _img , ctx . get_hook ( 'img' ) ) return root
Serialize image element .
60,805
def fire_hooks ( ctx , document , elem , element , hooks ) : if not hooks : return for hook in hooks : hook ( ctx , document , elem , element )
Fire hooks on newly created element .
60,806
def has_style ( node ) : elements = [ 'b' , 'i' , 'u' , 'strike' , 'color' , 'jc' , 'sz' , 'ind' , 'superscript' , 'subscript' , 'small_caps' ] return any ( [ True for elem in elements if elem in node . rpr ] )
Tells us if node element has defined styling .
60,807
def get_style_css ( ctx , node , embed = True , fontsize = - 1 ) : style = [ ] if not node : return if fontsize in [ - 1 , 2 ] : if 'sz' in node . rpr : size = int ( node . rpr [ 'sz' ] ) / 2 if ctx . options [ 'embed_fontsize' ] : if ctx . options [ 'scale_to_size' ] : multiplier = size - ctx . options [ 'scale_to_size' ] scale = 100 + int ( math . trunc ( 8.3 * multiplier ) ) style . append ( 'font-size: {}%' . format ( scale ) ) else : style . append ( 'font-size: {}pt' . format ( size ) ) if fontsize in [ - 1 , 1 ] : if not embed : if 'b' in node . rpr : style . append ( 'font-weight: bold' ) if 'i' in node . rpr : style . append ( 'font-style: italic' ) if 'u' in node . rpr : style . append ( 'text-decoration: underline' ) if 'small_caps' in node . rpr : style . append ( 'font-variant: small-caps' ) if 'strike' in node . rpr : style . append ( 'text-decoration: line-through' ) if 'color' in node . rpr : if node . rpr [ 'color' ] != '000000' : style . append ( 'color: #{}' . format ( node . rpr [ 'color' ] ) ) if 'jc' in node . ppr : align = node . ppr [ 'jc' ] if align . lower ( ) == 'both' : align = 'justify' style . append ( 'text-align: {}' . format ( align ) ) if 'ind' in node . ppr : if 'left' in node . ppr [ 'ind' ] : size = int ( node . ppr [ 'ind' ] [ 'left' ] ) / 10 style . append ( 'margin-left: {}px' . format ( size ) ) if 'right' in node . ppr [ 'ind' ] : size = int ( node . ppr [ 'ind' ] [ 'right' ] ) / 10 style . append ( 'margin-right: {}px' . format ( size ) ) if 'first_line' in node . ppr [ 'ind' ] : size = int ( node . ppr [ 'ind' ] [ 'first_line' ] ) / 10 style . append ( 'text-indent: {}px' . format ( size ) ) if len ( style ) == 0 : return '' return '; ' . join ( style ) + ';'
Returns as string defined CSS for this node .
60,808
def get_all_styles ( document , style ) : classes = [ ] while True : classes . insert ( 0 , get_style_name ( style ) ) if style . based_on : style = document . styles . get_by_id ( style . based_on ) else : break return classes
Returns list of styles on which specified style is based on .
60,809
def get_css_classes ( document , style ) : lst = [ st . lower ( ) for st in get_all_styles ( document , style ) [ - 1 : ] ] + [ '{}-fontsize' . format ( st . lower ( ) ) for st in get_all_styles ( document , style ) [ - 1 : ] ] return ' ' . join ( lst )
Returns CSS classes for this style .
60,810
def serialize_symbol ( ctx , document , el , root ) : "Serialize special symbols." span = etree . SubElement ( root , 'span' ) span . text = el . value ( ) fire_hooks ( ctx , document , el , span , ctx . get_hook ( 'symbol' ) ) return root
Serialize special symbols .
60,811
def serialize_footnote ( ctx , document , el , root ) : "Serializes footnotes." footnote_num = el . rid if el . rid not in ctx . footnote_list : ctx . footnote_id += 1 ctx . footnote_list [ el . rid ] = ctx . footnote_id footnote_num = ctx . footnote_list [ el . rid ] note = etree . SubElement ( root , 'sup' ) link = etree . SubElement ( note , 'a' ) link . set ( 'href' , '#' ) link . text = u'{}' . format ( footnote_num ) fire_hooks ( ctx , document , el , note , ctx . get_hook ( 'footnote' ) ) return root
Serializes footnotes .
60,812
def serialize_comment ( ctx , document , el , root ) : "Serializes comment." if el . comment_type == 'end' : ctx . opened_comments . remove ( el . cid ) else : if el . comment_type != 'reference' : ctx . opened_comments . append ( el . cid ) if ctx . options [ 'comment_span' ] : link = etree . SubElement ( root , 'a' ) link . set ( 'href' , '#' ) link . set ( 'class' , 'comment-link' ) link . set ( 'id' , 'comment-id-' + el . cid ) link . text = '' fire_hooks ( ctx , document , el , link , ctx . get_hook ( 'comment' ) ) return root
Serializes comment .
60,813
def serialize_endnote ( ctx , document , el , root ) : "Serializes endnotes." footnote_num = el . rid if el . rid not in ctx . endnote_list : ctx . endnote_id += 1 ctx . endnote_list [ el . rid ] = ctx . endnote_id footnote_num = ctx . endnote_list [ el . rid ] note = etree . SubElement ( root , 'sup' ) link = etree . SubElement ( note , 'a' ) link . set ( 'href' , '#' ) link . text = u'{}' . format ( footnote_num ) fire_hooks ( ctx , document , el , note , ctx . get_hook ( 'endnote' ) ) return root
Serializes endnotes .
60,814
def serialize_smarttag ( ctx , document , el , root ) : "Serializes smarttag." if ctx . options [ 'smarttag_span' ] : _span = etree . SubElement ( root , 'span' , { 'class' : 'smarttag' , 'data-smarttag-element' : el . element } ) else : _span = root for elem in el . elements : _ser = ctx . get_serializer ( elem ) if _ser : _td = _ser ( ctx , document , elem , _span ) else : if isinstance ( elem , doc . Text ) : children = list ( _span ) if len ( children ) == 0 : _text = _span . text or u'' _span . text = u'{}{}' . format ( _text , elem . text ) else : _text = children [ - 1 ] . tail or u'' children [ - 1 ] . tail = u'{}{}' . format ( _text , elem . text ) fire_hooks ( ctx , document , el , _span , ctx . get_hook ( 'smarttag' ) ) return root
Serializes smarttag .
60,815
def serialize_table ( ctx , document , table , root ) : if root is None : return root if ctx . ilvl != None : root = close_list ( ctx , root ) ctx . ilvl , ctx . numid = None , None _table = etree . SubElement ( root , 'table' ) _table . set ( 'border' , '1' ) _table . set ( 'width' , '100%' ) style = get_style ( document , table ) if style : _table . set ( 'class' , get_css_classes ( document , style ) ) for rows in table . rows : _tr = etree . SubElement ( _table , 'tr' ) for cell in rows : _td = etree . SubElement ( _tr , 'td' ) if cell . grid_span != 1 : _td . set ( 'colspan' , str ( cell . grid_span ) ) if cell . row_span != 1 : _td . set ( 'rowspan' , str ( cell . row_span ) ) for elem in cell . elements : if isinstance ( elem , doc . Paragraph ) : _ser = ctx . get_serializer ( elem ) _td = _ser ( ctx , document , elem , _td , embed = False ) if ctx . ilvl != None : _td = close_list ( ctx , _td ) ctx . ilvl , ctx . numid = None , None fire_hooks ( ctx , document , table , _td , ctx . get_hook ( 'td' ) ) fire_hooks ( ctx , document , table , _td , ctx . get_hook ( 'tr' ) ) fire_hooks ( ctx , document , table , _table , ctx . get_hook ( 'table' ) ) return root
Serializes table element .
60,816
def serialize_textbox ( ctx , document , txtbox , root ) : _div = etree . SubElement ( root , 'div' ) _div . set ( 'class' , 'textbox' ) for elem in txtbox . elements : _ser = ctx . get_serializer ( elem ) if _ser : _ser ( ctx , document , elem , _div ) fire_hooks ( ctx , document , txtbox , _div , ctx . get_hook ( 'textbox' ) ) return root
Serialize textbox element .
60,817
def serialize_elements ( document , elements , options = None ) : ctx = Context ( document , options ) tree_root = root = etree . Element ( 'div' ) for elem in elements : _ser = ctx . get_serializer ( elem ) if _ser : root = _ser ( ctx , document , elem , root ) return etree . tostring ( tree_root , pretty_print = ctx . options . get ( 'pretty_print' , True ) , encoding = "utf-8" , xml_declaration = False )
Serialize list of elements into HTML string .
60,818
def is_header ( self , elem , font_size , node , style = None ) : if hasattr ( style , 'style_id' ) : fnt_size = _get_font_size ( self . doc , style ) from . importer import calculate_weight weight = calculate_weight ( self . doc , elem ) if weight > 50 : return False if fnt_size in self . doc . possible_headers_style : return True return font_size in self . doc . possible_headers else : list_of_sizes = { } for el in elem . elements : try : fs = get_style_fontsize ( el ) weight = len ( el . value ( ) ) if el . value ( ) else 0 list_of_sizes [ fs ] = list_of_sizes . setdefault ( fs , 0 ) + weight except : pass sorted_list_of_sizes = list ( collections . OrderedDict ( sorted ( six . iteritems ( list_of_sizes ) , key = lambda t : t [ 0 ] ) ) ) font_size_to_check = font_size if len ( sorted_list_of_sizes ) > 0 : if sorted_list_of_sizes [ 0 ] != font_size : return sorted_list_of_sizes [ 0 ] in self . doc . possible_headers return font_size in self . doc . possible_headers
Used for checking if specific element is a header or not .
60,819
def get_header ( self , elem , style , node ) : font_size = style if hasattr ( elem , 'possible_header' ) : if elem . possible_header : return 'h1' if not style : return 'h6' if hasattr ( style , 'style_id' ) : font_size = _get_font_size ( self . doc , style ) try : if font_size in self . doc . possible_headers_style : return 'h{}' . format ( self . doc . possible_headers_style . index ( font_size ) + 1 ) return 'h{}' . format ( self . doc . possible_headers . index ( font_size ) + 1 ) except ValueError : return 'h6'
Returns HTML tag representing specific header for this element .
60,820
def get_serializer ( self , node ) : return self . options [ 'serializers' ] . get ( type ( node ) , None ) if type ( node ) in self . options [ 'serializers' ] : return self . options [ 'serializers' ] [ type ( node ) ] return None
Returns serializer for specific element .
60,821
def priority ( self , priority ) : with self . __lock : old_priorities = { } try : for thread in self . __threads : old_priorities [ thread ] = thread . priority thread . priority = priority except Exception : for ( thread , old_priority ) in old_priorities . iteritems ( ) : try : thread . priority = old_priority except Exception : pass raise else : self . __priority = priority
Set the priority for all threads in this group .
60,822
def affinity ( self , affinity ) : with self . __lock : old_affinities = { } try : for thread in self . __threads : old_affinities [ thread ] = thread . affinity thread . affinity = affinity except Exception : for ( thread , old_affinity ) in old_affinities . iteritems ( ) : try : thread . affinity = old_affinity except Exception : pass raise else : self . __affinity = affinity
Set the affinity for all threads in this group .
60,823
def join ( self , timeout = None ) : if timeout is None : for thread in self . __threads : thread . join ( ) else : deadline = _time ( ) + timeout for thread in self . __threads : delay = deadline - _time ( ) if delay <= 0 : return False if not thread . join ( delay ) : return False return True
Join all threads in this group .
60,824
def text_length ( elem ) : if not elem : return 0 value = elem . value ( ) try : value = len ( value ) except : value = 0 try : for a in elem . elements : value += len ( a . value ( ) ) except : pass return value
Returns length of the content in this element .
60,825
def reset ( self ) : "Resets the values." self . zf = zipfile . ZipFile ( self . file_name , 'r' ) self . _doc = None
Resets the values .
60,826
def build_rrule ( count = None , interval = None , bysecond = None , byminute = None , byhour = None , byweekno = None , bymonthday = None , byyearday = None , bymonth = None , until = None , bysetpos = None , wkst = None , byday = None , freq = None ) : result = { } if count is not None : result [ 'COUNT' ] = count if interval is not None : result [ 'INTERVAL' ] = interval if bysecond is not None : result [ 'BYSECOND' ] = bysecond if byminute is not None : result [ 'BYMINUTE' ] = byminute if byhour is not None : result [ 'BYHOUR' ] = byhour if byweekno is not None : result [ 'BYWEEKNO' ] = byweekno if bymonthday is not None : result [ 'BYMONTHDAY' ] = bymonthday if byyearday is not None : result [ 'BYYEARDAY' ] = byyearday if bymonth is not None : result [ 'BYMONTH' ] = bymonth if until is not None : result [ 'UNTIL' ] = until if bysetpos is not None : result [ 'BYSETPOS' ] = bysetpos if wkst is not None : result [ 'WKST' ] = wkst if byday is not None : result [ 'BYDAY' ] = byday if freq is not None : if freq not in vRecur . frequencies : raise ValueError ( 'Frequency value should be one of: {0}' . format ( vRecur . frequencies ) ) result [ 'FREQ' ] = freq return result
Build rrule dictionary for vRecur class .
60,827
def build_rrule_from_recurrences_rrule ( rule ) : from recurrence import serialize line = serialize ( rule ) if line . startswith ( 'RRULE:' ) : line = line [ 6 : ] return build_rrule_from_text ( line )
Build rrule dictionary for vRecur class from a django_recurrences rrule .
60,828
def build_rrule_from_dateutil_rrule ( rule ) : lines = str ( rule ) . splitlines ( ) for line in lines : if line . startswith ( 'DTSTART:' ) : continue if line . startswith ( 'RRULE:' ) : line = line [ 6 : ] return build_rrule_from_text ( line )
Build rrule dictionary for vRecur class from a dateutil rrule .
60,829
def write ( self , outfile , encoding ) : u cal = Calendar ( ) cal . add ( 'version' , '2.0' ) cal . add ( 'calscale' , 'GREGORIAN' ) for ifield , efield in FEED_FIELD_MAP : val = self . feed . get ( ifield ) if val is not None : cal . add ( efield , val ) self . write_items ( cal ) to_ical = getattr ( cal , 'as_string' , None ) if not to_ical : to_ical = cal . to_ical outfile . write ( to_ical ( ) )
u Writes the feed to the specified file in the specified encoding .
60,830
def write_items ( self , calendar ) : for item in self . items : event = Event ( ) for ifield , efield in ITEM_EVENT_FIELD_MAP : val = item . get ( ifield ) if val is not None : event . add ( efield , val ) calendar . add_component ( event )
Write all events to the calendar
60,831
def _textlist ( self , _addtail = False ) : result = [ ] if ( not _addtail ) and ( self . text is not None ) : result . append ( self . text ) for elem in self : result . extend ( elem . textlist ( True ) ) if _addtail and self . tail is not None : result . append ( self . tail ) return result
Returns a list of text strings contained within an element and its sub - elements .
60,832
def _reindent ( s , indent , reformat = True ) : s = textwrap . dedent ( s ) s = s . split ( '\n' ) s = [ x . rstrip ( ) for x in s ] while s and ( not s [ 0 ] ) : s = s [ 1 : ] while s and ( not s [ - 1 ] ) : s = s [ : - 1 ] if reformat : s = '\n' . join ( s ) s = textwrap . wrap ( s , initial_indent = indent , subsequent_indent = indent ) else : s = [ indent + x for x in s ] return '\n' . join ( s ) + '\n'
Remove the existing indentation from each line of a chunk of text s and then prefix each line with a new indent string .
60,833
def generate_docstr ( element , indent = '' , wrap = None ) : result = [ ] txt = element . text and element . text . rstrip ( ) if txt : result . append ( _reindent ( txt , indent ) ) result . append ( indent ) for d in element . findall ( 'doc' ) + element . findall ( 'rule' ) : docval = '' . join ( d . textlist ( ) ) . rstrip ( ) if not docval : continue reformat = True if 'name' in d . attrib : result . append ( indent + d . attrib [ 'name' ] . upper ( ) + ':' ) result . append ( indent ) extra_indent = ' ' if d . attrib [ 'name' ] == 'grammar' : reformat = False elif d . tag == 'rule' : result . append ( indent + 'RULE:' ) result . append ( indent ) extra_indent = ' ' else : extra_indent = '' result . append ( _reindent ( docval , indent + extra_indent , reformat ) ) result . append ( indent ) fields = element . findall ( 'field' ) if fields : result . append ( indent + 'PARAMETERS:' ) for f in fields : result . append ( indent + ' ' + _fixup_field_name ( f ) + ': ' + _field_type ( f ) ) field_docs = generate_docstr ( f , indent + ' ' ) if field_docs : result . append ( indent ) result . append ( field_docs ) result . append ( indent ) if not result : return None if wrap is not None : result = [ wrap ] + result + [ wrap ] return '\n' . join ( x . rstrip ( ) for x in result ) + '\n'
Generate a Python docstr for a given element in the AMQP XML spec file . The element could be a class or method
60,834
def generate_module ( spec , out ) : for amqp_class in spec . findall ( 'class' ) : if amqp_class . attrib [ 'name' ] == 'access' : amqp_class . attrib [ 'handler' ] = 'channel' for domain in spec . findall ( 'domain' ) : domains [ domain . attrib [ 'name' ] ] = domain . attrib [ 'type' ] for amqp_class in spec . findall ( 'class' ) : for amqp_method in amqp_class . findall ( 'method' ) : method_name_map [ ( amqp_class . attrib [ 'name' ] , amqp_method . attrib [ 'name' ] ) ] = ( amqp_class . attrib [ 'index' ] , amqp_method . attrib [ 'index' ] , amqp_class . attrib [ 'handler' ] . capitalize ( ) + '.' + _fixup_method_name ( amqp_class , amqp_method ) , ) for amqp_class in spec . findall ( 'class' ) : if amqp_class . attrib [ 'handler' ] == amqp_class . attrib [ 'name' ] : generate_class ( spec , amqp_class , out ) out . write ( '_METHOD_MAP = {\n' ) for amqp_class in spec . findall ( 'class' ) : print amqp_class . attrib for amqp_method in amqp_class . findall ( 'method' ) : chassis = [ x . attrib [ 'name' ] for x in amqp_method . findall ( 'chassis' ) ] if 'client' in chassis : out . write ( " (%s, %s): (%s, %s._%s),\n" % ( amqp_class . attrib [ 'index' ] , amqp_method . attrib [ 'index' ] , amqp_class . attrib [ 'handler' ] . capitalize ( ) , amqp_class . attrib [ 'handler' ] . capitalize ( ) , _fixup_method_name ( amqp_class , amqp_method ) ) ) out . write ( '}\n\n' ) out . write ( '_METHOD_NAME_MAP = {\n' ) for amqp_class in spec . findall ( 'class' ) : for amqp_method in amqp_class . findall ( 'method' ) : out . write ( " (%s, %s): '%s.%s',\n" % ( amqp_class . attrib [ 'index' ] , amqp_method . attrib [ 'index' ] , amqp_class . attrib [ 'handler' ] . capitalize ( ) , _fixup_method_name ( amqp_class , amqp_method ) ) ) out . write ( '}\n' )
Given an AMQP spec parsed into an xml . etree . ElemenTree and a file - like out object to write to generate the skeleton of a Python module .
60,835
def _process_method_frame ( self , channel , payload ) : method_sig = unpack ( '>HH' , payload [ : 4 ] ) args = AMQPReader ( payload [ 4 : ] ) if method_sig in _CONTENT_METHODS : self . partial_messages [ channel ] = _PartialMessage ( method_sig , args ) self . expected_types [ channel ] = 2 else : self . queue . put ( ( channel , method_sig , args , None ) )
Process Method frames
60,836
def _alert ( self , args ) : reply_code = args . read_short ( ) reply_text = args . read_shortstr ( ) details = args . read_table ( ) self . alerts . put ( ( reply_code , reply_text , details ) )
This method allows the server to send a non - fatal warning to the client . This is used for methods that are normally asynchronous and thus do not have confirmations and for which the server may detect errors that need to be reported . Fatal errors are handled as channel or connection exceptions ; non - fatal errors are sent through this method .
60,837
def access_request ( self , realm , exclusive = False , passive = False , active = False , write = False , read = False ) : args = AMQPWriter ( ) args . write_shortstr ( realm ) args . write_bit ( exclusive ) args . write_bit ( passive ) args . write_bit ( active ) args . write_bit ( write ) args . write_bit ( read ) self . _send_method ( ( 30 , 10 ) , args ) return self . wait ( allowed_methods = [ ( 30 , 11 ) , ] )
request an access ticket
60,838
def exchange_declare ( self , exchange , type , passive = False , durable = False , auto_delete = True , internal = False , nowait = False , arguments = None , ticket = None ) : if arguments is None : arguments = { } args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( exchange ) args . write_shortstr ( type ) args . write_bit ( passive ) args . write_bit ( durable ) args . write_bit ( auto_delete ) args . write_bit ( internal ) args . write_bit ( nowait ) args . write_table ( arguments ) self . _send_method ( ( 40 , 10 ) , args ) if not nowait : return self . wait ( allowed_methods = [ ( 40 , 11 ) , ] )
declare exchange create if needed
60,839
def exchange_delete ( self , exchange , if_unused = False , nowait = False , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( exchange ) args . write_bit ( if_unused ) args . write_bit ( nowait ) self . _send_method ( ( 40 , 20 ) , args ) if not nowait : return self . wait ( allowed_methods = [ ( 40 , 21 ) , ] )
delete an exchange
60,840
def queue_bind ( self , queue , exchange , routing_key = '' , nowait = False , arguments = None , ticket = None ) : if arguments is None : arguments = { } args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( queue ) args . write_shortstr ( exchange ) args . write_shortstr ( routing_key ) args . write_bit ( nowait ) args . write_table ( arguments ) self . _send_method ( ( 50 , 20 ) , args ) if not nowait : return self . wait ( allowed_methods = [ ( 50 , 21 ) , ] )
bind queue to an exchange
60,841
def _queue_declare_ok ( self , args ) : queue = args . read_shortstr ( ) message_count = args . read_long ( ) consumer_count = args . read_long ( ) return queue , message_count , consumer_count
confirms a queue definition
60,842
def basic_consume ( self , queue = '' , consumer_tag = '' , no_local = False , no_ack = False , exclusive = False , nowait = False , callback = None , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( queue ) args . write_shortstr ( consumer_tag ) args . write_bit ( no_local ) args . write_bit ( no_ack ) args . write_bit ( exclusive ) args . write_bit ( nowait ) self . _send_method ( ( 60 , 20 ) , args ) if not nowait : consumer_tag = self . wait ( allowed_methods = [ ( 60 , 21 ) , ] ) self . callbacks [ consumer_tag ] = callback return consumer_tag
start a queue consumer
60,843
def _basic_deliver ( self , args , msg ) : consumer_tag = args . read_shortstr ( ) delivery_tag = args . read_longlong ( ) redelivered = args . read_bit ( ) exchange = args . read_shortstr ( ) routing_key = args . read_shortstr ( ) msg . delivery_info = { 'channel' : self , 'consumer_tag' : consumer_tag , 'delivery_tag' : delivery_tag , 'redelivered' : redelivered , 'exchange' : exchange , 'routing_key' : routing_key , } func = self . callbacks . get ( consumer_tag , None ) if func is not None : func ( msg )
notify the client of a consumer message
60,844
def basic_get ( self , queue = '' , no_ack = False , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( queue ) args . write_bit ( no_ack ) self . _send_method ( ( 60 , 70 ) , args ) return self . wait ( allowed_methods = [ ( 60 , 71 ) , ( 60 , 72 ) , ] )
direct access to a queue
60,845
def basic_publish ( self , msg , exchange = '' , routing_key = '' , mandatory = False , immediate = False , ticket = None ) : args = AMQPWriter ( ) if ticket is not None : args . write_short ( ticket ) else : args . write_short ( self . default_ticket ) args . write_shortstr ( exchange ) args . write_shortstr ( routing_key ) args . write_bit ( mandatory ) args . write_bit ( immediate ) self . _send_method ( ( 60 , 40 ) , args , msg )
publish a message
60,846
def _basic_return ( self , args , msg ) : reply_code = args . read_short ( ) reply_text = args . read_shortstr ( ) exchange = args . read_shortstr ( ) routing_key = args . read_shortstr ( ) self . returned_messages . put ( ( reply_code , reply_text , exchange , routing_key , msg ) )
return a failed message
60,847
def _wait_method ( self , channel_id , allowed_methods ) : method_queue = self . channels [ channel_id ] . method_queue for queued_method in method_queue : method_sig = queued_method [ 0 ] if ( allowed_methods is None ) or ( method_sig in allowed_methods ) or ( method_sig == ( 20 , 40 ) ) : method_queue . remove ( queued_method ) return queued_method while True : channel , method_sig , args , content = self . method_reader . read_method ( ) if ( channel == channel_id ) and ( ( allowed_methods is None ) or ( method_sig in allowed_methods ) or ( method_sig == ( 20 , 40 ) ) ) : return method_sig , args , content if ( channel != 0 ) and ( method_sig in Channel . _IMMEDIATE_METHODS ) : self . channels [ channel ] . dispatch_method ( method_sig , args , content ) continue self . channels [ channel ] . method_queue . append ( ( method_sig , args , content ) ) if channel == 0 : self . wait ( )
Wait for a method from the server destined for a particular channel .
60,848
def channel ( self , channel_id = None ) : if channel_id in self . channels : return self . channels [ channel_id ] return Channel ( self , channel_id )
Fetch a Channel object identified by the numeric channel_id or create that object if it doesn t already exist .
60,849
def _close ( self , args ) : reply_code = args . read_short ( ) reply_text = args . read_shortstr ( ) class_id = args . read_short ( ) method_id = args . read_short ( ) self . _x_close_ok ( ) raise AMQPConnectionException ( reply_code , reply_text , ( class_id , method_id ) )
request a connection close
60,850
def _x_open ( self , virtual_host , capabilities = '' , insist = False ) : args = AMQPWriter ( ) args . write_shortstr ( virtual_host ) args . write_shortstr ( capabilities ) args . write_bit ( insist ) self . _send_method ( ( 10 , 40 ) , args ) return self . wait ( allowed_methods = [ ( 10 , 41 ) , ( 10 , 50 ) , ] )
open connection to virtual host
60,851
def _open_ok ( self , args ) : self . known_hosts = args . read_shortstr ( ) AMQP_LOGGER . debug ( 'Open OK! known_hosts [%s]' % self . known_hosts ) return None
signal that the connection is ready
60,852
def _redirect ( self , args ) : host = args . read_shortstr ( ) self . known_hosts = args . read_shortstr ( ) AMQP_LOGGER . debug ( 'Redirected to [%s], known_hosts [%s]' % ( host , self . known_hosts ) ) return host
asks the client to use a different server
60,853
def _start ( self , args ) : self . version_major = args . read_octet ( ) self . version_minor = args . read_octet ( ) self . server_properties = args . read_table ( ) self . mechanisms = args . read_longstr ( ) . split ( ' ' ) self . locales = args . read_longstr ( ) . split ( ' ' ) AMQP_LOGGER . debug ( 'Start from server, version: %d.%d, properties: %s, mechanisms: %s, locales: %s' % ( self . version_major , self . version_minor , str ( self . server_properties ) , self . mechanisms , self . locales ) )
start connection negotiation
60,854
def _x_start_ok ( self , client_properties , mechanism , response , locale ) : args = AMQPWriter ( ) args . write_table ( client_properties ) args . write_shortstr ( mechanism ) args . write_longstr ( response ) args . write_shortstr ( locale ) self . _send_method ( ( 10 , 11 ) , args )
select security mechanism and locale
60,855
def _tune ( self , args ) : self . channel_max = args . read_short ( ) or self . channel_max self . frame_max = args . read_long ( ) or self . frame_max self . method_writer . frame_max = self . frame_max self . heartbeat = args . read_short ( ) self . _x_tune_ok ( self . channel_max , self . frame_max , 0 )
propose connection tuning parameters
60,856
def _send_method ( self , method_sig , args = bytes ( ) , content = None ) : if isinstance ( args , AMQPWriter ) : args = args . getvalue ( ) self . connection . method_writer . write_method ( self . channel_id , method_sig , args , content )
Send a method for our channel .
60,857
def read_frame ( self ) : frame_type , channel , size = unpack ( '>BHI' , self . _read ( 7 ) ) payload = self . _read ( size ) ch = ord ( self . _read ( 1 ) ) if ch == 206 : return frame_type , channel , payload else : raise Exception ( 'Framing Error, received 0x%02x while expecting 0xce' % ch )
Read an AMQP frame .
60,858
def write_frame ( self , frame_type , channel , payload ) : size = len ( payload ) self . _write ( pack ( '>BHI%dsB' % size , frame_type , channel , size , payload , 0xce ) )
Write out an AMQP frame .
60,859
def _setup_transport ( self ) : if HAVE_PY26_SSL : if hasattr ( self , 'sslopts' ) : self . sslobj = ssl . wrap_socket ( self . sock , ** self . sslopts ) else : self . sslobj = ssl . wrap_socket ( self . sock ) self . sslobj . do_handshake ( ) else : self . sslobj = socket . ssl ( self . sock )
Wrap the socket in an SSL object either the new Python 2 . 6 version or the older Python 2 . 5 and lower version .
60,860
def write_bit ( self , b ) : if b : b = 1 else : b = 0 shift = self . bitcount % 8 if shift == 0 : self . bits . append ( 0 ) self . bits [ - 1 ] |= ( b << shift ) self . bitcount += 1
Write a boolean value .
60,861
def on_unexpected_error ( e ) : sys . stderr . write ( 'Unexpected error: {} ({})\n' . format ( str ( e ) , e . __class__ . __name__ ) ) sys . stderr . write ( 'See file slam_error.log for additional details.\n' ) sys . exit ( 1 )
Catch - all error handler
60,862
def init ( name , description , bucket , timeout , memory , stages , requirements , function , runtime , config_file , ** kwargs ) : if os . path . exists ( config_file ) : raise RuntimeError ( 'Please delete the old version {} if you want to ' 'reconfigure your project.' . format ( config_file ) ) module , app = function . split ( ':' ) if not name : name = module . replace ( '_' , '-' ) if not re . match ( '^[a-zA-Z][-a-zA-Z0-9]*$' , name ) : raise ValueError ( 'The name {} is invalid, only letters, numbers and ' 'dashes are allowed.' . format ( name ) ) if not bucket : random_suffix = '' . join ( random . choice ( string . ascii_uppercase + string . digits ) for n in range ( 8 ) ) bucket = '{}-{}' . format ( name , random_suffix ) stages = [ s . strip ( ) for s in stages . split ( ',' ) ] if runtime is None : if sys . version_info [ 0 ] == 2 : runtime = 'python2.7' else : runtime = 'python3.6' template_file = os . path . join ( os . path . dirname ( __file__ ) , 'templates/slam.yaml' ) with open ( template_file ) as f : template = f . read ( ) template = render_template ( template , name = name , description = description , module = module , app = app , bucket = bucket , timeout = timeout , memory = memory , requirements = requirements , stages = stages , devstage = stages [ 0 ] , runtime = runtime ) with open ( config_file , 'wt' ) as f : f . write ( template ) config = _load_config ( config_file ) for name , plugin in plugins . items ( ) : with open ( config_file , 'at' ) as f : f . write ( '\n\n# ' + ( plugin . __doc__ or name ) . replace ( '\n' , '\n# ' ) + '\n' ) if hasattr ( plugin , 'init' ) : arguments = { k : v for k , v in kwargs . items ( ) if k in getattr ( plugin . init , '_argnames' , [ ] ) } plugin_config = plugin . init . func ( config = config , ** arguments ) if plugin_config : with open ( config_file , 'at' ) as f : yaml . dump ( { name : plugin_config } , f , default_flow_style = False ) print ( 'The configuration file for your project has been generated. ' 'Remember to add {} to source control.' . format ( config_file ) )
Generate a configuration file .
60,863
def _generate_lambda_handler ( config , output = '.slam/handler.py' ) : run_function = _run_lambda_function for name , plugin in plugins . items ( ) : if name in config and hasattr ( plugin , 'run_lambda_function' ) : run_function = plugin . run_lambda_function run_code = '' . join ( inspect . getsourcelines ( run_function ) [ 0 ] [ 1 : ] ) with open ( os . path . join ( os . path . dirname ( __file__ ) , 'templates/handler.py.template' ) ) as f : template = f . read ( ) template = render_template ( template , module = config [ 'function' ] [ 'module' ] , app = config [ 'function' ] [ 'app' ] , run_lambda_function = run_code , config_json = json . dumps ( config , separators = ( ',' , ':' ) ) ) with open ( output , 'wt' ) as f : f . write ( template + '\n' )
Generate a handler . py file for the lambda function start up .
60,864
def build ( rebuild_deps , config_file ) : config = _load_config ( config_file ) print ( "Building lambda package..." ) package = _build ( config , rebuild_deps = rebuild_deps ) print ( "{} has been built successfully." . format ( package ) )
Build lambda package .
60,865
def deploy ( stage , lambda_package , no_lambda , rebuild_deps , config_file ) : config = _load_config ( config_file ) if stage is None : stage = config [ 'devstage' ] s3 = boto3 . client ( 's3' ) cfn = boto3 . client ( 'cloudformation' ) region = _get_aws_region ( ) previous_deployment = None try : previous_deployment = cfn . describe_stacks ( StackName = config [ 'name' ] ) [ 'Stacks' ] [ 0 ] except botocore . exceptions . ClientError : pass built_package = False new_package = True if lambda_package is None and not no_lambda : print ( "Building lambda package..." ) lambda_package = _build ( config , rebuild_deps = rebuild_deps ) built_package = True elif lambda_package is None : new_package = False lambda_package = _get_from_stack ( previous_deployment , 'Parameter' , 'LambdaS3Key' ) bucket = config [ 'aws' ] [ 's3_bucket' ] _ensure_bucket_exists ( s3 , bucket , region ) if new_package : s3 . upload_file ( lambda_package , bucket , lambda_package ) if built_package : os . remove ( lambda_package ) template_body = get_cfn_template ( config ) parameters = [ { 'ParameterKey' : 'LambdaS3Bucket' , 'ParameterValue' : bucket } , { 'ParameterKey' : 'LambdaS3Key' , 'ParameterValue' : lambda_package } , ] stages = list ( config [ 'stage_environments' ] . keys ( ) ) stages . sort ( ) for s in stages : param = s . title ( ) + 'Version' if s != stage : v = _get_from_stack ( previous_deployment , 'Parameter' , param ) if previous_deployment else '$LATEST' v = v or '$LATEST' else : v = '$LATEST' parameters . append ( { 'ParameterKey' : param , 'ParameterValue' : v } ) if previous_deployment is None : print ( 'Deploying {}:{}...' . format ( config [ 'name' ] , stage ) ) cfn . create_stack ( StackName = config [ 'name' ] , TemplateBody = template_body , Parameters = parameters , Capabilities = [ 'CAPABILITY_IAM' ] ) waiter = cfn . get_waiter ( 'stack_create_complete' ) else : print ( 'Updating {}:{}...' . format ( config [ 'name' ] , stage ) ) cfn . update_stack ( StackName = config [ 'name' ] , TemplateBody = template_body , Parameters = parameters , Capabilities = [ 'CAPABILITY_IAM' ] ) waiter = cfn . get_waiter ( 'stack_update_complete' ) try : waiter . wait ( StackName = config [ 'name' ] ) except botocore . exceptions . ClientError : if built_package : s3 . delete_object ( Bucket = bucket , Key = lambda_package ) raise else : if previous_deployment and new_package : old_pkg = _get_from_stack ( previous_deployment , 'Parameter' , 'LambdaS3Key' ) s3 . delete_object ( Bucket = bucket , Key = old_pkg ) _print_status ( config )
Deploy the project to the development stage .
60,866
def publish ( version , stage , config_file ) : config = _load_config ( config_file ) cfn = boto3 . client ( 'cloudformation' ) if version is None : version = config [ 'devstage' ] elif version not in config [ 'stage_environments' ] . keys ( ) and not version . isdigit ( ) : raise ValueError ( 'Invalid version. Use a stage name or a numeric ' 'version number.' ) if version == stage : raise ValueError ( 'Cannot deploy a stage into itself.' ) try : previous_deployment = cfn . describe_stacks ( StackName = config [ 'name' ] ) [ 'Stacks' ] [ 0 ] except botocore . exceptions . ClientError : raise RuntimeError ( 'This project has not been deployed yet.' ) bucket = _get_from_stack ( previous_deployment , 'Parameter' , 'LambdaS3Bucket' ) lambda_package = _get_from_stack ( previous_deployment , 'Parameter' , 'LambdaS3Key' ) template_body = get_cfn_template ( config ) parameters = [ { 'ParameterKey' : 'LambdaS3Bucket' , 'ParameterValue' : bucket } , { 'ParameterKey' : 'LambdaS3Key' , 'ParameterValue' : lambda_package } , ] stages = list ( config [ 'stage_environments' ] . keys ( ) ) stages . sort ( ) for s in stages : param = s . title ( ) + 'Version' if s != stage : v = _get_from_stack ( previous_deployment , 'Parameter' , param ) if previous_deployment else '$LATEST' v = v or '$LATEST' else : if version . isdigit ( ) : v = version else : v = _get_from_stack ( previous_deployment , 'Parameter' , version . title ( ) + 'Version' ) if v == '$LATEST' : lmb = boto3 . client ( 'lambda' ) v = lmb . publish_version ( FunctionName = _get_from_stack ( previous_deployment , 'Output' , 'FunctionArn' ) ) [ 'Version' ] parameters . append ( { 'ParameterKey' : param , 'ParameterValue' : v } ) print ( 'Publishing {}:{} to {}...' . format ( config [ 'name' ] , version , stage ) ) cfn . update_stack ( StackName = config [ 'name' ] , TemplateBody = template_body , Parameters = parameters , Capabilities = [ 'CAPABILITY_IAM' ] ) waiter = cfn . get_waiter ( 'stack_update_complete' ) try : waiter . wait ( StackName = config [ 'name' ] ) except botocore . exceptions . ClientError : raise _print_status ( config )
Publish a version of the project to a stage .
60,867
def invoke ( stage , async , dry_run , config_file , args ) : config = _load_config ( config_file ) if stage is None : stage = config [ 'devstage' ] cfn = boto3 . client ( 'cloudformation' ) lmb = boto3 . client ( 'lambda' ) try : stack = cfn . describe_stacks ( StackName = config [ 'name' ] ) [ 'Stacks' ] [ 0 ] except botocore . exceptions . ClientError : raise RuntimeError ( 'This project has not been deployed yet.' ) function = _get_from_stack ( stack , 'Output' , 'FunctionArn' ) if dry_run : invocation_type = 'DryRun' elif async : invocation_type = 'Event' else : invocation_type = 'RequestResponse' data = { } for arg in args : s = arg . split ( '=' , 1 ) if len ( s ) != 2 : raise ValueError ( 'Invalid argument ' + arg ) if s [ 0 ] [ - 1 ] == ':' : data [ s [ 0 ] [ : - 1 ] ] = json . loads ( s [ 1 ] ) else : data [ s [ 0 ] ] = s [ 1 ] rv = lmb . invoke ( FunctionName = function , InvocationType = invocation_type , Qualifier = stage , Payload = json . dumps ( { 'kwargs' : data } , sort_keys = True ) ) if rv [ 'StatusCode' ] != 200 and rv [ 'StatusCode' ] != 202 : raise RuntimeError ( 'Unexpected error. Status code = {}.' . format ( rv [ 'StatusCode' ] ) ) if invocation_type == 'RequestResponse' : payload = json . loads ( rv [ 'Payload' ] . read ( ) . decode ( 'utf-8' ) ) if 'FunctionError' in rv : if 'stackTrace' in payload : print ( 'Traceback (most recent call last):' ) for frame in payload [ 'stackTrace' ] : print ( ' File "{}", line {}, in {}' . format ( frame [ 0 ] , frame [ 1 ] , frame [ 2 ] ) ) print ( ' ' + frame [ 3 ] ) print ( '{}: {}' . format ( payload [ 'errorType' ] , payload [ 'errorMessage' ] ) ) else : raise RuntimeError ( 'Unknown error' ) else : print ( str ( payload ) )
Invoke the lambda function .
60,868
def template ( config_file ) : config = _load_config ( config_file ) print ( get_cfn_template ( config , pretty = True ) )
Print the default Cloudformation deployment template .
60,869
def register_plugins ( ) : if pkg_resources : for ep in pkg_resources . iter_entry_points ( 'slam_plugins' ) : plugin = ep . load ( ) if hasattr ( plugin , 'init' ) and hasattr ( plugin . init , '_arguments' ) : for arg in plugin . init . _arguments : init . parser . add_argument ( * arg [ 0 ] , ** arg [ 1 ] ) init . _arguments += plugin . init . _arguments init . _argnames += plugin . init . _argnames plugins [ ep . name ] = plugin
find any installed plugins and register them .
60,870
def synchronise_device_state ( self , device_state , authentication_headers ) : payload = { 'context' : device_state , 'event' : { 'header' : { 'namespace' : 'System' , 'name' : 'SynchronizeState' , 'messageId' : '' } , 'payload' : { } } } multipart_data = MultipartEncoder ( fields = [ ( 'metadata' , ( 'metadata' , json . dumps ( payload ) , 'application/json' , { 'Content-Disposition' : "form-data; name='metadata'" } ) ) , ] , boundary = 'boundary' ) headers = { ** authentication_headers , 'Content-Type' : multipart_data . content_type } stream_id = self . connection . request ( 'GET' , '/v20160207/events' , body = multipart_data , headers = headers , ) response = self . connection . get_response ( stream_id ) assert response . status in [ http . client . NO_CONTENT , http . client . OK ]
Synchronizing the component states with AVS
60,871
def send_audio_file ( self , audio_file , device_state , authentication_headers , dialog_request_id , distance_profile , audio_format ) : payload = { 'context' : device_state , 'event' : { 'header' : { 'namespace' : 'SpeechRecognizer' , 'name' : 'Recognize' , 'messageId' : self . generate_message_id ( ) , 'dialogRequestId' : dialog_request_id , } , 'payload' : { 'profile' : distance_profile , 'format' : audio_format } } } multipart_data = MultipartEncoder ( fields = [ ( 'request' , ( 'request' , json . dumps ( payload ) , 'application/json;' , { 'Content-Disposition' : "form-data; name='request'" } ) , ) , ( 'audio' , ( 'audio' , audio_file , 'application/octet-stream' , { 'Content-Disposition' : "form-data; name='audio'" } ) ) , ] , boundary = 'boundary' , ) headers = { ** authentication_headers , 'Content-Type' : multipart_data . content_type } stream_id = self . connection . request ( 'POST' , '/v20160207/events' , headers = headers , body = multipart_data , ) response = self . connection . get_response ( stream_id ) return self . parse_response ( response )
Send audio to AVS
60,872
def retrieve_api_token ( self ) : payload = self . oauth2_manager . get_access_token_params ( refresh_token = self . refresh_token ) response = requests . post ( self . oauth2_manager . access_token_url , json = payload ) response . raise_for_status ( ) response_json = json . loads ( response . text ) return response_json [ 'access_token' ]
Retrieve the access token from AVS .
60,873
def webpack_template_tag ( path_to_config ) : try : return webpack ( path_to_config ) except ( AttributeError , ValueError ) as e : raise six . reraise ( BundlingError , BundlingError ( * e . args ) , sys . exc_info ( ) [ 2 ] )
A template tag that will output a webpack bundle .
60,874
def _prepare_key ( key , * args , ** kwargs ) : if not args and not kwargs : return key items = sorted ( kwargs . items ( ) ) hashable_args = ( args , tuple ( items ) ) args_key = hashlib . md5 ( pickle . dumps ( hashable_args ) ) . hexdigest ( ) return "%s/args:%s" % ( key , args_key )
if arguments are given adds a hash of the args to the key .
60,875
def setup ( logdir = 'log' ) : logger = logging . getLogger ( ) logger . setLevel ( logging . DEBUG ) logdir = os . path . normpath ( logdir ) if not os . path . exists ( logdir ) : os . makedirs ( logdir ) t = datetime . datetime . now ( ) logfile = '{year:04d}{mon:02d}{day:02d}-' '{hour:02d}{min:02d}{sec:02d}.log' . format ( year = t . year , mon = t . month , day = t . day , hour = t . hour , min = t . minute , sec = t . second ) logfile = os . path . join ( logdir , logfile ) filehandler = logging . handlers . RotatingFileHandler ( filename = logfile , maxBytes = 10 * 1024 * 1024 , backupCount = 100 ) filehandler . setLevel ( logging . DEBUG ) fileformatter = logging . Formatter ( '%(asctime)s %(levelname)-8s: %(message)s' ) filehandler . setFormatter ( fileformatter ) logger . addHandler ( filehandler ) streamhandler = logging . StreamHandler ( ) streamhandler . setLevel ( logging . WARNING ) streamformatter = logging . Formatter ( '%(levelname)s: %(message)s' ) streamhandler . setFormatter ( streamformatter ) logger . addHandler ( streamhandler )
Set up dual logging to console and to logfile .
60,876
def get_versions ( ) -> FileVersionResult : version_counter = Counter ( ) versions_match = False version_str = None versions_discovered = OrderedDict ( ) for version_obj in version_objects : discovered = version_obj . get_version ( ) versions_discovered [ version_obj . key_name ] = discovered version_counter . update ( [ discovered ] ) if len ( version_counter ) == 1 : versions_match = True version_str = list ( version_counter . keys ( ) ) [ 0 ] return FileVersionResult ( uniform = versions_match , version_details = versions_discovered , version_result = version_str , )
Search specific project files and extract versions to check .
60,877
def supportedChars ( * tests ) : for test in tests : try : test . encode ( sys . stdout . encoding ) return test except UnicodeEncodeError : pass return '?' * len ( tests [ 0 ] )
Takes any number of strings and returns the first one the terminal encoding supports . If none are supported it returns ? the length of the first string .
60,878
def app_templates_dirs ( self ) : app_templates_dirs = OrderedDict ( ) for app_config in apps . get_app_configs ( ) : templates_dir = os . path . join ( getattr ( app_config , 'path' , '/' ) , 'templates' ) if os . path . isdir ( templates_dir ) : templates_dir = upath ( templates_dir ) app_templates_dirs [ app_config . name ] = templates_dir app_templates_dirs [ app_config . label ] = templates_dir return app_templates_dirs
Build a cached dict with settings . INSTALLED_APPS as keys and the templates directory of each application as values .
60,879
def get_contents ( self , origin ) : try : path = self . get_app_template_path ( origin . app_name , origin . template_name ) with io . open ( path , encoding = self . engine . file_charset ) as fp : return fp . read ( ) except KeyError : raise TemplateDoesNotExist ( origin ) except IOError as error : if error . errno == errno . ENOENT : raise TemplateDoesNotExist ( origin ) raise
Try to load the origin .
60,880
def load_template_source ( self , * ka ) : template_name = ka [ 0 ] for origin in self . get_template_sources ( template_name ) : try : return self . get_contents ( origin ) , origin . name except TemplateDoesNotExist : pass raise TemplateDoesNotExist ( template_name )
Backward compatible method for Django < 2 . 0 .
60,881
def rotateImage ( image , angle ) : image = [ list ( row ) for row in image ] for n in range ( angle % 4 ) : image = list ( zip ( * image [ : : - 1 ] ) ) return image
rotates a 2d array to a multiple of 90 deg . 0 = default 1 = 90 deg . cw 2 = 180 deg . 3 = 90 deg . ccw
60,882
def overlaps ( self , canvas , exclude = [ ] ) : try : exclude = list ( exclude ) except TypeError : exclude = [ exclude ] exclude . append ( self ) for selfY , row in enumerate ( self . image . image ( ) ) : for selfX , pixel in enumerate ( row ) : canvasPixelOn = canvas . testPixel ( ( selfX + self . position [ 0 ] , selfY + self . position [ 1 ] ) , excludedSprites = exclude ) if pixel and canvasPixelOn : return True return False
Returns True if sprite is touching any other sprite .
60,883
def onEdge ( self , canvas ) : sides = [ ] if int ( self . position [ 0 ] ) <= 0 : sides . append ( 1 ) if ( int ( self . position [ 0 ] ) + self . image . width ) >= canvas . width : sides . append ( 3 ) if int ( self . position [ 1 ] ) <= 0 : sides . append ( 2 ) if ( int ( self . position [ 1 ] ) + self . image . height ) >= canvas . height : sides . append ( 0 ) return sides
Returns a list of the sides of the sprite which are touching the edge of the canvas .
60,884
def remote_property ( name , get_command , set_command , field_name , doc = None ) : def getter ( self ) : try : return getattr ( self , name ) except AttributeError : value = getattr ( self . sendCommand ( get_command ( ) ) , field_name ) setattr ( self , name , value ) return value def setter ( self , value ) : setattr ( self , name , value ) self . sendCommand ( set_command ( value ) ) return property ( getter , setter , doc = doc )
Property decorator that facilitates writing properties for values from a remote device .
60,885
def sendCommand ( self , command ) : command_data = [ ord ( x ) for x in buffer ( command ) ] self . hid . write ( command_data ) response_data = '' . join ( chr ( x ) for x in self . hid . read ( 64 ) ) response = command . RESPONSE . from_buffer_copy ( response_data ) if response . status != 0 : raise CommandException ( response . status ) return response
Sends a Command object to the MCP2210 and returns its response .
60,886
def transfer ( self , data ) : settings = self . transfer_settings settings . spi_tx_size = len ( data ) self . transfer_settings = settings response = '' for i in range ( 0 , len ( data ) , 60 ) : response += self . sendCommand ( commands . SPITransferCommand ( data [ i : i + 60 ] ) ) . data time . sleep ( 0.01 ) while len ( response ) < len ( data ) : response += self . sendCommand ( commands . SPITransferCommand ( '' ) ) . data return '' . join ( response )
Transfers data over SPI .
60,887
def render_json_response ( self , context_dict , status = 200 ) : json_context = json . dumps ( context_dict , cls = DjangoJSONEncoder , ** self . get_json_dumps_kwargs ( ) ) . encode ( u'utf-8' ) return HttpResponse ( json_context , content_type = self . get_content_type ( ) , status = status )
Limited serialization for shipping plain data . Do not use for models or other complex or custom objects .
60,888
def form_valid ( self , form ) : self . object = form . save ( commit = False ) self . pre_save ( ) self . object . save ( ) if hasattr ( form , 'save_m2m' ) : form . save_m2m ( ) self . post_save ( ) if self . request . is_ajax ( ) : return self . render_json_response ( self . get_success_result ( ) ) return HttpResponseRedirect ( self . get_success_url ( ) )
If the request is ajax save the form and return a json response . Otherwise return super as expected .
60,889
def form_invalid ( self , form ) : if self . request . is_ajax ( ) : return self . render_json_response ( self . get_error_result ( form ) ) return super ( AjaxFormMixin , self ) . form_invalid ( form )
We have errors in the form . If ajax return them as json . Otherwise proceed as normal .
60,890
def assumes ( * args ) : args = tuple ( args ) def decorator ( func ) : func . assumptions = args return func return decorator
Stores a function s assumptions as an attribute .
60,891
def overridden_by_assumptions ( * args ) : args = tuple ( args ) def decorator ( func ) : func . overridden_by_assumptions = args return func return decorator
Stores what assumptions a function is overridden by as an attribute .
60,892
def equation_docstring ( quantity_dict , assumption_dict , equation = None , references = None , notes = None ) : def decorator ( func ) : out_name_end_index = func . __name__ . find ( '_from_' ) if out_name_end_index == - 1 : raise ValueError ( 'equation_docstring decorator must be applied to ' 'function whose name contains "_from_"' ) out_quantity = func . __name__ [ : out_name_end_index ] in_quantities = inspect . getargspec ( func ) . args docstring = 'Calculates {0}' . format ( quantity_string ( out_quantity , quantity_dict ) ) try : if len ( func . assumptions ) > 0 : docstring += ' assuming {0}' . format ( assumption_list_string ( func . assumptions , assumption_dict ) ) except AttributeError : pass docstring += '.' docstring = doc_paragraph ( docstring ) docstring += '\n\n' if equation is not None : func . equation = equation docstring += doc_paragraph ( ':math:`' + equation . strip ( ) + '`' ) docstring += '\n\n' docstring += 'Parameters\n' docstring += '----------\n\n' docstring += '\n' . join ( [ quantity_spec_string ( q , quantity_dict ) for q in in_quantities ] ) docstring += '\n\n' docstring += 'Returns\n' docstring += '-------\n\n' docstring += quantity_spec_string ( out_quantity , quantity_dict ) if notes is not None : docstring += '\n\n' docstring += 'Notes\n' docstring += '-----\n\n' docstring += notes . strip ( ) if references is not None : if notes is None : docstring += '\n\n' docstring += 'Notes\n' docstring += '-----\n\n' func . references = references docstring += '\n\n' docstring += '**References**\n\n' docstring += references . strip ( ) docstring += '\n' func . __doc__ = docstring return func return decorator
Creates a decorator that adds a docstring to an equation function .
60,893
def sma ( array , window_size , axis = - 1 , mode = 'reflect' , ** kwargs ) : kwargs [ 'axis' ] = axis kwargs [ 'mode' ] = mode if not isinstance ( window_size , int ) : raise TypeError ( 'window_size must be an integer' ) if not isinstance ( kwargs [ 'axis' ] , int ) : raise TypeError ( 'axis must be an integer' ) return convolve1d ( array , np . repeat ( 1.0 , window_size ) / window_size , ** kwargs )
Computes a 1D simple moving average along the given axis .
60,894
def assumption_list_string ( assumptions , assumption_dict ) : if isinstance ( assumptions , six . string_types ) : raise TypeError ( 'assumptions must be an iterable of strings, not a ' 'string itself' ) for a in assumptions : if a not in assumption_dict . keys ( ) : raise ValueError ( '{} not present in assumption_dict' . format ( a ) ) assumption_strings = [ assumption_dict [ a ] for a in assumptions ] return strings_to_list_string ( assumption_strings )
Takes in a list of short forms of assumptions and an assumption dictionary and returns a list form of the long form of the assumptions .
60,895
def quantity_spec_string ( name , quantity_dict ) : if name not in quantity_dict . keys ( ) : raise ValueError ( '{0} not present in quantity_dict' . format ( name ) ) s = '{0} : float or ndarray\n' . format ( name ) s += doc_paragraph ( 'Data for {0}.' . format ( quantity_string ( name , quantity_dict ) ) , indent = 4 ) return s
Returns a quantity specification for docstrings .
60,896
def doc_paragraph ( s , indent = 0 ) : return '\n' . join ( [ ' ' * indent + l for l in wrap ( s , width = 80 - indent ) ] )
Takes in a string without wrapping corresponding to a paragraph and returns a version of that string wrapped to be at most 80 characters in length on each line . If indent is given ensures each line is indented to that number of spaces .
60,897
def closest_val ( x , L ) : if len ( L ) == 0 : raise ValueError ( 'L must not be empty' ) if isinstance ( L , np . ndarray ) : return ( np . abs ( L - x ) ) . argmin ( ) min_index = 0 min_diff = abs ( L [ 0 ] - x ) i = 1 while i < len ( L ) : diff = abs ( L [ i ] - x ) if diff < min_diff : min_index = i min_diff = diff i += 1 return min_index
Finds the index value in an iterable closest to a desired value .
60,898
def area_poly_sphere ( lat , lon , r_sphere ) : dtr = np . pi / 180. def _tranlon ( plat , plon , qlat , qlon ) : t = np . sin ( ( qlon - plon ) * dtr ) * np . cos ( qlat * dtr ) b = ( np . sin ( qlat * dtr ) * np . cos ( plat * dtr ) - np . cos ( qlat * dtr ) * np . sin ( plat * dtr ) * np . cos ( ( qlon - plon ) * dtr ) ) return np . arctan2 ( t , b ) if len ( lat ) < 3 : raise ValueError ( 'lat must have at least 3 vertices' ) if len ( lat ) != len ( lon ) : raise ValueError ( 'lat and lon must have the same length' ) total = 0. for i in range ( - 1 , len ( lat ) - 1 ) : fang = _tranlon ( lat [ i ] , lon [ i ] , lat [ i + 1 ] , lon [ i + 1 ] ) bang = _tranlon ( lat [ i ] , lon [ i ] , lat [ i - 1 ] , lon [ i - 1 ] ) fvb = bang - fang if fvb < 0 : fvb += 2. * np . pi total += fvb return ( total - np . pi * float ( len ( lat ) - 2 ) ) * r_sphere ** 2
Calculates the area enclosed by an arbitrary polygon on the sphere .
60,899
def d_x ( data , axis , boundary = 'forward-backward' ) : if abs ( axis ) > len ( data . shape ) : raise ValueError ( 'axis is out of bounds for the shape of data' ) if boundary == 'periodic' : diff = np . roll ( data , - 1 , axis ) - np . roll ( data , 1 , axis ) elif boundary == 'forward-backward' : front = [ slice ( s ) for s in data . shape ] back = [ slice ( s ) for s in data . shape ] target = [ slice ( s ) for s in data . shape ] front [ axis ] = np . array ( [ 1 , - 1 ] ) back [ axis ] = np . array ( [ 0 , - 2 ] ) target [ axis ] = np . array ( [ 0 , - 1 ] ) diff = ( np . roll ( data , - 1 , axis ) - np . roll ( data , 1 , axis ) ) / ( 2. ) diff [ target ] = ( data [ front ] - data [ back ] ) else : raise ValueError ( 'Invalid option {} for boundary ' 'condition.' . format ( boundary ) ) return diff
Calculates a second - order centered finite difference of data along the specified axis .