idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
12,000 | def scheduler ( self , sleep_time = 0.2 ) : while self . listening : if self . scheduled_calls : timestamp = time . time ( ) self . scheduled_calls [ : ] = [ item for item in self . scheduled_calls if not self . time_reached ( timestamp , item ) ] time . sleep ( sleep_time ) logger . info ( "Shutting down the call scheduler..." ) | Starts the scheduler to check for scheduled calls and execute them at the correct time . |
12,001 | def call_later ( self , time_seconds , callback , arguments ) : scheduled_call = { 'ts' : time . time ( ) + time_seconds , 'callback' : callback , 'args' : arguments } self . scheduled_calls . append ( scheduled_call ) | Schedules a function to be run x number of seconds from now . |
12,002 | def time_reached ( self , current_time , scheduled_call ) : if current_time >= scheduled_call [ 'ts' ] : scheduled_call [ 'callback' ] ( scheduled_call [ 'args' ] ) return True else : return False | Checks to see if it s time to run a scheduled call or not . |
12,003 | def send_datagram ( self , message , address , message_type = "unicast" ) : if self . bufsize is not 0 and len ( message ) > self . bufsize : raise Exception ( "Datagram is too large. Messages should be " + "under " + str ( self . bufsize ) + " bytes in size." ) if message_type == "broadcast" : self . sock . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 ) elif message_type == "multicast" : self . sock . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_TTL , 2 ) try : logger . debug ( "Sending packet" ) self . sock . sendto ( message , address ) if self . stats_enabled : self . stats [ 'bytes_sent' ] += len ( message ) except socket . error : logger . error ( "Failed to send, [Errno 101]: Network is unreachable." ) | Sends a UDP datagram packet to the requested address . |
12,004 | def receive_datagram ( self , data , address ) : if not self . app : logger . debug ( "Packet received" , address , data ) return False try : response = self . app . handle_message ( data , address ) except Exception as err : logger . error ( "Error processing message from " + str ( address ) + ":" + str ( data ) ) logger . error ( traceback . format_exc ( ) ) return False if response : self . send_datagram ( response , address ) | Executes when UDP data has been received and sends the packet data to our app to process the request . |
12,005 | def make_application ( ) : settings = { } application = web . Application ( [ web . url ( '/' , SimpleHandler ) ] , ** settings ) statsd . install ( application , ** { 'namespace' : 'testing' } ) return application | Create a application configured to send metrics . |
12,006 | def plots_html_page ( query_module ) : template = jenv . get_template ( "analysis.html" ) context = dict ( extended = config . EXTENDED ) cl = client . get_client ( ) session = cl . create_session ( ) seaborn . set_style ( 'whitegrid' ) decade_df = query_module . decade_query ( ) pix_size = pixels_to_inches ( ( 600 , 400 ) ) ax = seaborn . lmplot ( x = 'decade' , y = 'area' , data = decade_df , size = pix_size [ 1 ] , aspect = pix_size [ 0 ] / pix_size [ 1 ] , scatter_kws = { "s" : 30 , "alpha" : 0.3 } ) ax . set ( xlabel = 'Decade' , ylabel = 'Area, m^2' ) context [ 'area_by_decade_svg' ] = fig_to_svg ( plt . gcf ( ) ) plt . close ( 'all' ) if config . EXTENDED : gender_df = query_module . gender_query ( ) pix_size = pixels_to_inches ( ( 600 , 400 ) ) g = seaborn . FacetGrid ( gender_df , hue = "gender" , margin_titles = True , size = pix_size [ 1 ] , aspect = pix_size [ 0 ] / pix_size [ 1 ] ) bins = np . linspace ( 0 , 5 , 30 ) g . map ( plt . hist , "area" , bins = bins , lw = 0 , alpha = 0.5 , normed = True ) g . axes [ 0 , 0 ] . set_xlabel ( 'Area, m^2' ) g . axes [ 0 , 0 ] . set_ylabel ( 'Percentage of paintings' ) context [ 'area_by_gender_svg' ] = fig_to_svg ( plt . gcf ( ) ) plt . close ( 'all' ) out_file = path . join ( out_dir , "analysis.html" ) html_content = template . render ( ** context ) with open ( out_file , 'w' ) as f : f . write ( html_content ) plt . close ( 'all' ) session . close ( ) | Generate analysis output as html page |
12,007 | def _to_pywintypes ( row ) : def _pywintype ( x ) : if isinstance ( x , dt . date ) : return dt . datetime ( x . year , x . month , x . day , tzinfo = dt . timezone . utc ) elif isinstance ( x , ( dt . datetime , pa . Timestamp ) ) : if x . tzinfo is None : return x . replace ( tzinfo = dt . timezone . utc ) elif isinstance ( x , str ) : if re . match ( "^\d{4}-\d{2}-\d{2}$" , x ) : return "'" + x return x elif isinstance ( x , np . integer ) : return int ( x ) elif isinstance ( x , np . floating ) : return float ( x ) elif x is not None and not isinstance ( x , ( str , int , float , bool ) ) : return str ( x ) return x return [ _pywintype ( x ) for x in row ] | convert values in a row to types accepted by excel |
12,008 | def iterrows ( self , workbook = None ) : resolved_tables = [ ] max_height = 0 max_width = 0 self . __formula_values = { } for name , ( table , ( row , col ) ) in list ( self . __tables . items ( ) ) : self . __tables [ None ] = ( table , ( row , col ) ) data = table . get_data ( workbook , row , col , self . __formula_values ) del self . __tables [ None ] height , width = data . shape upper_left = ( row , col ) lower_right = ( row + height - 1 , col + width - 1 ) max_height = max ( max_height , lower_right [ 0 ] + 1 ) max_width = max ( max_width , lower_right [ 1 ] + 1 ) resolved_tables . append ( ( name , data , upper_left , lower_right ) ) for row , col in self . __values . keys ( ) : max_width = max ( max_width , row + 1 ) max_height = max ( max_height , col + 1 ) table = [ [ None ] * max_width for i in range ( max_height ) ] for name , data , upper_left , lower_right in resolved_tables : for i , r in enumerate ( range ( upper_left [ 0 ] , lower_right [ 0 ] + 1 ) ) : for j , c in enumerate ( range ( upper_left [ 1 ] , lower_right [ 1 ] + 1 ) ) : table [ r ] [ c ] = data [ i ] [ j ] for ( r , c ) , value in self . __values . items ( ) : if isinstance ( value , Value ) : value = value . value if isinstance ( value , Expression ) : if value . has_value : self . __formula_values [ ( r , c ) ] = value . value value = value . get_formula ( workbook , r , c ) table [ r ] [ c ] = value for row in table : yield row | Yield rows as lists of data . |
12,009 | def create ( context , name , content = None , file_path = None , mime = 'text/plain' , jobstate_id = None , md5 = None , job_id = None , test_id = None ) : if content and file_path : raise Exception ( 'content and file_path are mutually exclusive' ) elif not content and not file_path : raise Exception ( 'At least one of content or file_path must be specified' ) headers = { 'DCI-NAME' : name , 'DCI-MIME' : mime , 'DCI-JOBSTATE-ID' : jobstate_id , 'DCI-MD5' : md5 , 'DCI-JOB-ID' : job_id , 'DCI-TEST-ID' : test_id } headers = utils . sanitize_kwargs ( ** headers ) uri = '%s/%s' % ( context . dci_cs_api , RESOURCE ) if content : if not hasattr ( content , 'read' ) : if not isinstance ( content , bytes ) : content = content . encode ( 'utf-8' ) content = io . BytesIO ( content ) return context . session . post ( uri , headers = headers , data = content ) else : if not os . path . exists ( file_path ) : raise FileErrorException ( ) with open ( file_path , 'rb' ) as f : return context . session . post ( uri , headers = headers , data = f ) | Method to create a file on the Control - Server |
12,010 | def register_formatter ( field_typestr ) : def decorator_register ( formatter ) : @ functools . wraps ( formatter ) def wrapped_formatter ( * args , ** kwargs ) : field_name = args [ 0 ] field = args [ 1 ] field_id = args [ 2 ] field_type = get_type ( field_typestr ) if not isinstance ( field , field_type ) : message = ( 'Field {0} ({1!r}) is not an ' '{2} type. It is an {3}.' ) raise ValueError ( message . format ( field_name , field , field_typestr , typestring ( field ) ) ) nodes = formatter ( * args , ** kwargs ) section = make_section ( section_id = field_id + '-section' , contents = nodes ) return section FIELD_FORMATTERS [ field_typestr ] = wrapped_formatter return wrapped_formatter return decorator_register | Decorate a configuration field formatter function to register it with the get_field_formatter accessor . |
12,011 | def format_configurablefield_nodes ( field_name , field , field_id , state , lineno ) : default_item = nodes . definition_list_item ( ) default_item . append ( nodes . term ( text = "Default" ) ) default_item_content = nodes . definition ( ) para = nodes . paragraph ( ) name = '.' . join ( ( field . target . __module__ , field . target . __name__ ) ) para += pending_task_xref ( rawsource = name ) default_item_content += para default_item += default_item_content dl = nodes . definition_list ( ) dl += default_item dl += create_field_type_item_node ( field , state ) desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a ConfigurableField config field . |
12,012 | def format_listfield_nodes ( field_name , field , field_id , state , lineno ) : itemtype_node = nodes . definition_list_item ( ) itemtype_node += nodes . term ( text = 'Item type' ) itemtype_def = nodes . definition ( ) itemtype_def += make_python_xref_nodes_for_type ( field . itemtype , state , hide_namespace = False ) itemtype_node += itemtype_def minlength_node = None if field . minLength : minlength_node = nodes . definition_list_item ( ) minlength_node += nodes . term ( text = 'Minimum length' ) minlength_def = nodes . definition ( ) minlength_def += nodes . paragraph ( text = str ( field . minLength ) ) minlength_node += minlength_def maxlength_node = None if field . maxLength : maxlength_node = nodes . definition_list_item ( ) maxlength_node += nodes . term ( text = 'Maximum length' ) maxlength_def = nodes . definition ( ) maxlength_def += nodes . paragraph ( text = str ( field . maxLength ) ) maxlength_node += maxlength_def length_node = None if field . length : length_node = nodes . definition_list_item ( ) length_node += nodes . term ( text = 'Required length' ) length_def = nodes . definition ( ) length_def += nodes . paragraph ( text = str ( field . length ) ) length_node += length_def field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) field_type_item_content_p += make_python_xref_nodes_for_type ( field . itemtype , state , hide_namespace = False ) [ 0 ] . children [ 0 ] field_type_item_content_p += nodes . Text ( ' ' , ' ' ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content env = state . document . settings . env ref_target = create_configfield_ref_target_node ( field_id , env , lineno ) title = nodes . title ( text = field_name ) title += ref_target dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item if minlength_node : dl += minlength_node if maxlength_node : dl += maxlength_node if length_node : dl += length_node desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a ListField config field . |
12,013 | def format_choicefield_nodes ( field_name , field , field_id , state , lineno ) : choice_dl = nodes . definition_list ( ) for choice_value , choice_doc in field . allowed . items ( ) : item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_definition = nodes . definition ( ) item_definition . append ( nodes . paragraph ( text = choice_doc ) ) item += item_definition choice_dl . append ( item ) choices_node = nodes . definition_list_item ( ) choices_node . append ( nodes . term ( text = 'Choices' ) ) choices_definition = nodes . definition ( ) choices_definition . append ( choice_dl ) choices_node . append ( choices_definition ) field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) field_type_item_content_p += make_python_xref_nodes_for_type ( field . dtype , state , hide_namespace = False ) [ 0 ] . children [ 0 ] field_type_item_content_p += nodes . Text ( ' ' , ' ' ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a ChoiceField config field . |
12,014 | def format_rangefield_nodes ( field_name , field , field_id , state , lineno ) : field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) field_type_item_content_p += make_python_xref_nodes_for_type ( field . dtype , state , hide_namespace = False ) [ 0 ] . children [ 0 ] field_type_item_content_p += nodes . Text ( ' ' , ' ' ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content range_node = nodes . definition_list_item ( ) range_node += nodes . term ( text = 'Range' ) range_node_def = nodes . definition ( ) range_node_def += nodes . paragraph ( text = field . rangeString ) range_node += range_node_def dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += range_node desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a RangeField config field . |
12,015 | def format_dictfield_nodes ( field_name , field , field_id , state , lineno ) : valuetype_item = nodes . definition_list_item ( ) valuetype_item = nodes . term ( text = 'Value type' ) valuetype_def = nodes . definition ( ) valuetype_def += make_python_xref_nodes_for_type ( field . itemtype , state , hide_namespace = False ) valuetype_item += valuetype_def dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += create_field_type_item_node ( field , state ) dl += create_keytype_item_node ( field , state ) dl += valuetype_item desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a DictField config field . |
12,016 | def format_configfield_nodes ( field_name , field , field_id , state , lineno ) : dtype_node = nodes . definition_list_item ( ) dtype_node = nodes . term ( text = 'Data type' ) dtype_def = nodes . definition ( ) dtype_def_para = nodes . paragraph ( ) name = '.' . join ( ( field . dtype . __module__ , field . dtype . __name__ ) ) dtype_def_para += pending_config_xref ( rawsource = name ) dtype_def += dtype_def_para dtype_node += dtype_def dl = nodes . definition_list ( ) dl += dtype_node dl += create_field_type_item_node ( field , state ) desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a ConfigField config field . |
12,017 | def format_configchoicefield_nodes ( field_name , field , field_id , state , lineno ) : choice_dl = nodes . definition_list ( ) for choice_value , choice_class in field . typemap . items ( ) : item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_definition = nodes . definition ( ) def_para = nodes . paragraph ( ) name = '.' . join ( ( choice_class . __module__ , choice_class . __name__ ) ) def_para += pending_config_xref ( rawsource = name ) item_definition += def_para item += item_definition choice_dl . append ( item ) choices_node = nodes . definition_list_item ( ) choices_node . append ( nodes . term ( text = 'Choices' ) ) choices_definition = nodes . definition ( ) choices_definition . append ( choice_dl ) choices_node . append ( choices_definition ) field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) if field . multi : multi_text = "Multi-selection " else : multi_text = "Single-selection " field_type_item_content_p += nodes . Text ( multi_text , multi_text ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a ConfigChoiceField config field . |
12,018 | def format_configdictfield_nodes ( field_name , field , field_id , state , lineno ) : value_item = nodes . definition_list_item ( ) value_item += nodes . term ( text = "Value type" ) value_item_def = nodes . definition ( ) value_item_def_para = nodes . paragraph ( ) name = '.' . join ( ( field . itemtype . __module__ , field . itemtype . __name__ ) ) value_item_def_para += pending_config_xref ( rawsource = name ) value_item_def += value_item_def_para value_item += value_item_def dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += create_field_type_item_node ( field , state ) dl += create_keytype_item_node ( field , state ) dl += value_item desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a ConfigDictField config field . |
12,019 | def format_registryfield_nodes ( field_name , field , field_id , state , lineno ) : from lsst . pex . config . registry import ConfigurableWrapper choice_dl = nodes . definition_list ( ) for choice_value , choice_class in field . registry . items ( ) : if hasattr ( choice_class , '__module__' ) and hasattr ( choice_class , '__name__' ) : name = '.' . join ( ( choice_class . __module__ , choice_class . __name__ ) ) elif isinstance ( choice_class , ConfigurableWrapper ) : name = '.' . join ( ( choice_class . _target . __class__ . __module__ , choice_class . _target . __class__ . __name__ ) ) else : name = '.' . join ( ( choice_class . __class__ . __module__ , choice_class . __class__ . __name__ ) ) item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_definition = nodes . definition ( ) def_para = nodes . paragraph ( ) def_para += pending_task_xref ( rawsource = name ) item_definition += def_para item += item_definition choice_dl . append ( item ) choices_node = nodes . definition_list_item ( ) choices_node . append ( nodes . term ( text = 'Choices' ) ) choices_definition = nodes . definition ( ) choices_definition . append ( choice_dl ) choices_node . append ( choices_definition ) field_type_item = nodes . definition_list_item ( ) field_type_item . append ( nodes . term ( text = "Field type" ) ) field_type_item_content = nodes . definition ( ) field_type_item_content_p = nodes . paragraph ( ) if field . multi : multi_text = "Multi-selection " else : multi_text = "Single-selection " field_type_item_content_p += nodes . Text ( multi_text , multi_text ) field_type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children [ 0 ] if field . optional : field_type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) field_type_item_content += field_type_item_content_p field_type_item += field_type_item_content dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node desc_node = create_description_node ( field , state ) title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | Create a section node that documents a RegistryField config field . |
12,020 | def create_field_type_item_node ( field , state ) : type_item = nodes . definition_list_item ( ) type_item . append ( nodes . term ( text = "Field type" ) ) type_item_content = nodes . definition ( ) type_item_content_p = nodes . paragraph ( ) type_item_content_p += make_python_xref_nodes_for_type ( type ( field ) , state , hide_namespace = True ) [ 0 ] . children if field . optional : type_item_content_p += nodes . Text ( ' (optional)' , ' (optional)' ) type_item_content += type_item_content_p type_item += type_item_content return type_item | Create a definition list item node that describes a field s type . |
12,021 | def create_default_item_node ( field , state ) : default_item = nodes . definition_list_item ( ) default_item . append ( nodes . term ( text = "Default" ) ) default_item_content = nodes . definition ( ) default_item_content . append ( nodes . literal ( text = repr ( field . default ) ) ) default_item . append ( default_item_content ) return default_item | Create a definition list item node that describes the default value of a Field config . |
12,022 | def create_keytype_item_node ( field , state ) : keytype_node = nodes . definition_list_item ( ) keytype_node = nodes . term ( text = 'Key type' ) keytype_def = nodes . definition ( ) keytype_def += make_python_xref_nodes_for_type ( field . keytype , state , hide_namespace = False ) keytype_node += keytype_def return keytype_node | Create a definition list item node that describes the key type of a dict - type config field . |
12,023 | def create_description_node ( field , state ) : doc_container_node = nodes . container ( ) doc_container_node += parse_rst_content ( field . doc , state ) return doc_container_node | Creates docutils nodes for the Field s description built from the field s doc and optional attributes . |
12,024 | def create_title_node ( field_name , field , field_id , state , lineno ) : env = state . document . settings . env ref_target = create_configfield_ref_target_node ( field_id , env , lineno ) title = nodes . title ( text = field_name ) title += ref_target return title | Create docutils nodes for the configuration field s title and reference target node . |
12,025 | def create_configfield_ref_target_node ( target_id , env , lineno ) : target_node = nodes . target ( '' , '' , ids = [ target_id ] ) if not hasattr ( env , 'lsst_configfields' ) : env . lsst_configfields = { } env . lsst_configfields [ target_id ] = { 'docname' : env . docname , 'lineno' : lineno , 'target' : target_node , } return target_node | Create a target node that marks a configuration field . |
12,026 | def translate_argv ( raw_args ) : kwargs = { } def get_parameter ( param_str ) : for i , a in enumerate ( raw_args ) : if a == param_str : assert len ( raw_args ) == i + 2 and raw_args [ i + 1 ] [ 0 ] != '-' , 'All arguments must have a value, e.g. `-testing true`' return raw_args [ i + 1 ] return None value = get_parameter ( '-testing' ) if value is not None and value . lower ( ) in ( 'true' , 't' , 'yes' ) : kwargs [ 'testing' ] = True value = get_parameter ( '-connect' ) if value is not None : colon = value . find ( ':' ) if colon > - 1 : kwargs [ 'host' ] = value [ 0 : colon ] kwargs [ 'port' ] = int ( value [ colon + 1 : ] ) else : kwargs [ 'host' ] = value value = get_parameter ( '-name' ) if value is not None : kwargs [ 'name' ] = value value = get_parameter ( '-group' ) if value is not None : kwargs [ 'group_name' ] = value value = get_parameter ( '-scan' ) if value in ( 'true' , 't' , 'yes' ) : kwargs [ 'scan_for_port' ] = True value = get_parameter ( '-debug' ) if value in ( 'true' , 't' , 'yes' ) : kwargs [ 'debug' ] = True return kwargs | Enables conversion from system arguments . |
12,027 | def _build_toctree ( self ) : dirname = posixpath . dirname ( self . _env . docname ) tree_prefix = self . options [ 'toctree' ] . strip ( ) root = posixpath . normpath ( posixpath . join ( dirname , tree_prefix ) ) docnames = [ docname for docname in self . _env . found_docs if docname . startswith ( root ) ] class_names = [ docname . split ( '/' ) [ - 1 ] . split ( '.' ) [ - 1 ] for docname in docnames ] docnames = [ docname for docname , _ in sorted ( zip ( docnames , class_names ) , key = lambda pair : pair [ 1 ] ) ] tocnode = sphinx . addnodes . toctree ( ) tocnode [ 'includefiles' ] = docnames tocnode [ 'entries' ] = [ ( None , docname ) for docname in docnames ] tocnode [ 'maxdepth' ] = - 1 tocnode [ 'glob' ] = None tocnode [ 'hidden' ] = True return tocnode | Create a hidden toctree node with the contents of a directory prefixed by the directory name specified by the toctree directive option . |
12,028 | def do_GET ( self ) : self . send_response ( 200 ) self . send_header ( "Content-type" , "text/html" ) self . end_headers ( ) self . wfile . write ( bytes ( json . dumps ( self . message ) , "utf-8" ) ) | Handle GET WebMethod |
12,029 | def serve_forever ( self , poll_interval = 0.5 ) : while self . is_alive : self . handle_request ( ) time . sleep ( poll_interval ) | Cycle for webserer |
12,030 | def stop ( self ) : self . is_alive = False self . server_close ( ) flows . Global . LOGGER . info ( "Server Stops " + ( str ( self . server_address ) ) ) | Stop the webserver |
12,031 | def check_scalar ( self , scalar_dict ) : table = { k : np . array ( [ v ] ) for k , v in scalar_dict . items ( ) } return self . mask ( table ) [ 0 ] | check if scalar_dict satisfy query |
12,032 | def dumpfile ( self , fd ) : self . start ( ) dump = DumpFile ( fd ) self . queue . append ( dump ) | Dump a file through a Spin instance . |
12,033 | def run ( self ) : document = self . state . document if not document . settings . file_insertion_enabled : return [ document . reporter . warning ( 'File insertion disabled' , line = self . lineno ) ] try : location = self . state_machine . get_source_and_line ( self . lineno ) url = self . arguments [ 0 ] reader = RemoteCodeBlockReader ( url , self . options , self . config ) text , lines = reader . read ( location = location ) retnode = nodes . literal_block ( text , text ) set_source_info ( self , retnode ) if self . options . get ( 'diff' ) : retnode [ 'language' ] = 'udiff' elif 'language' in self . options : retnode [ 'language' ] = self . options [ 'language' ] retnode [ 'linenos' ] = ( 'linenos' in self . options or 'lineno-start' in self . options or 'lineno-match' in self . options ) retnode [ 'classes' ] += self . options . get ( 'class' , [ ] ) extra_args = retnode [ 'highlight_args' ] = { } if 'emphasize-lines' in self . options : hl_lines = parselinenos ( self . options [ 'emphasize-lines' ] , lines ) if any ( i >= lines for i in hl_lines ) : logger . warning ( 'line number spec is out of range(1-%d): %r' % ( lines , self . options [ 'emphasize-lines' ] ) , location = location ) extra_args [ 'hl_lines' ] = [ x + 1 for x in hl_lines if x < lines ] extra_args [ 'linenostart' ] = reader . lineno_start if 'caption' in self . options : caption = self . options [ 'caption' ] or self . arguments [ 0 ] retnode = container_wrapper ( self , retnode , caption ) self . add_name ( retnode ) return [ retnode ] except Exception as exc : return [ document . reporter . warning ( str ( exc ) , line = self . lineno ) ] | Run the remote - code - block directive . |
12,034 | def read_file ( self , url , location = None ) : response = requests_retry_session ( ) . get ( url , timeout = 10.0 ) response . raise_for_status ( ) text = response . text if 'tab-width' in self . options : text = text . expandtabs ( self . options [ 'tab-width' ] ) return text . splitlines ( True ) | Read content from the web by overriding LiteralIncludeReader . read_file . |
12,035 | def verify_time ( self , now ) : return now . time ( ) >= self . start_time and now . time ( ) <= self . end_time | Verify the time |
12,036 | def verify_weekday ( self , now ) : return self . weekdays == "*" or str ( now . weekday ( ) ) in self . weekdays . split ( " " ) | Verify the weekday |
12,037 | def verify_day ( self , now ) : return self . day == "*" or str ( now . day ) in self . day . split ( " " ) | Verify the day |
12,038 | def verify_month ( self , now ) : return self . month == "*" or str ( now . month ) in self . month . split ( " " ) | Verify the month |
12,039 | def aggregate_duplicates ( X , Y , aggregator = "mean" , precision = precision ) : if callable ( aggregator ) : pass elif "min" in aggregator . lower ( ) : aggregator = np . min elif "max" in aggregator . lower ( ) : aggregator = np . max elif "median" in aggregator . lower ( ) : aggregator = np . median elif aggregator . lower ( ) in [ "average" , "mean" ] : aggregator = np . mean elif "first" in aggregator . lower ( ) : def aggregator ( x ) : return x [ 0 ] elif "last" in aggregator . lower ( ) : def aggregator ( x ) : return x [ - 1 ] else : warnings . warn ( 'Aggregator "{}" not understood. Skipping sample ' "aggregation." . format ( aggregator ) ) return X , Y is_y_multivariate = Y . ndim > 1 X_rounded = X . round ( decimals = precision ) unique_xs = np . unique ( X_rounded , axis = 0 ) old_size = len ( X_rounded ) new_size = len ( unique_xs ) if old_size == new_size : return X , Y if not is_y_multivariate : Y = np . atleast_2d ( Y ) . T reduced_y = np . empty ( ( new_size , Y . shape [ 1 ] ) ) warnings . warn ( "Domain space duplicates caused a data reduction. " + "Original size: {} vs. New size: {}" . format ( old_size , new_size ) ) for col in range ( Y . shape [ 1 ] ) : for i , distinct_row in enumerate ( unique_xs ) : filtered_rows = np . all ( X_rounded == distinct_row , axis = 1 ) reduced_y [ i , col ] = aggregator ( Y [ filtered_rows , col ] ) if not is_y_multivariate : reduced_y = reduced_y . flatten ( ) return unique_xs , reduced_y | A function that will attempt to collapse duplicates in domain space X by aggregating values over the range space Y . |
12,040 | def __set_data ( self , X , Y , w = None ) : self . X = X self . Y = Y self . check_duplicates ( ) if w is not None : self . w = np . array ( w ) else : self . w = np . ones ( len ( Y ) ) * 1.0 / float ( len ( Y ) ) if self . normalization == "feature" : min_max_scaler = sklearn . preprocessing . MinMaxScaler ( ) self . Xnorm = min_max_scaler . fit_transform ( np . atleast_2d ( self . X ) ) elif self . normalization == "zscore" : self . Xnorm = sklearn . preprocessing . scale ( self . X , axis = 0 , with_mean = True , with_std = True , copy = True ) else : self . Xnorm = np . array ( self . X ) | Internally assigns the input data and normalizes it according to the user s specifications |
12,041 | def build ( self , X , Y , w = None , edges = None ) : self . reset ( ) if X is None or Y is None : return self . __set_data ( X , Y , w ) if self . debug : sys . stdout . write ( "Graph Preparation: " ) start = time . clock ( ) self . graph_rep = nglpy . Graph ( self . Xnorm , self . graph , self . max_neighbors , self . beta , connect = self . connect , ) if self . debug : end = time . clock ( ) sys . stdout . write ( "%f s\n" % ( end - start ) ) | Assigns data to this object and builds the requested topological structure |
12,042 | def load_data_and_build ( self , filename , delimiter = "," ) : data = np . genfromtxt ( filename , dtype = float , delimiter = delimiter , names = True ) data = data . view ( np . float64 ) . reshape ( data . shape + ( - 1 , ) ) X = data [ : , 0 : - 1 ] Y = data [ : , - 1 ] self . build ( X = X , Y = Y ) | Convenience function for directly working with a data file . This opens a file and reads the data into an array sets the data as an nparray and list of dimnames |
12,043 | def get_normed_x ( self , rows = None , cols = None ) : if rows is None : rows = list ( range ( 0 , self . get_sample_size ( ) ) ) if cols is None : cols = list ( range ( 0 , self . get_dimensionality ( ) ) ) if not hasattr ( rows , "__iter__" ) : rows = [ rows ] rows = sorted ( list ( set ( rows ) ) ) retValue = self . Xnorm [ rows , : ] return retValue [ : , cols ] | Returns the normalized input data requested by the user |
12,044 | def get_x ( self , rows = None , cols = None ) : if rows is None : rows = list ( range ( 0 , self . get_sample_size ( ) ) ) if cols is None : cols = list ( range ( 0 , self . get_dimensionality ( ) ) ) if not hasattr ( rows , "__iter__" ) : rows = [ rows ] rows = sorted ( list ( set ( rows ) ) ) retValue = self . X [ rows , : ] if len ( rows ) == 0 : return [ ] return retValue [ : , cols ] | Returns the input data requested by the user |
12,045 | def get_y ( self , indices = None ) : if indices is None : indices = list ( range ( 0 , self . get_sample_size ( ) ) ) else : if not hasattr ( indices , "__iter__" ) : indices = [ indices ] indices = sorted ( list ( set ( indices ) ) ) if len ( indices ) == 0 : return [ ] return self . Y [ indices ] | Returns the output data requested by the user |
12,046 | def get_weights ( self , indices = None ) : if indices is None : indices = list ( range ( 0 , self . get_sample_size ( ) ) ) else : indices = sorted ( list ( set ( indices ) ) ) if len ( indices ) == 0 : return [ ] return self . w [ indices ] | Returns the weights requested by the user |
12,047 | def check_duplicates ( self ) : if self . aggregator is not None : X , Y = TopologicalObject . aggregate_duplicates ( self . X , self . Y , self . aggregator ) self . X = X self . Y = Y temp_x = self . X . round ( decimals = TopologicalObject . precision ) unique_xs = len ( np . unique ( temp_x , axis = 0 ) ) if len ( self . X ) != unique_xs : raise ValueError ( "Domain space has duplicates. Try using an " "aggregator function to consolidate duplicates " "into a single sample with one range value. " "e.g., " + self . __class__ . __name__ + "(aggregator='max'). " "\n\tNumber of " "Records: {}\n\tNumber of Unique Records: {}\n" . format ( len ( self . X ) , unique_xs ) ) | Function to test whether duplicates exist in the input or output space . First if an aggregator function has been specified the domain space duplicates will be consolidated using the function to generate a new range value for that shared point . Otherwise it will raise a ValueError . The function will raise a warning if duplicates exist in the output space |
12,048 | def column_stack_2d ( data ) : return list ( list ( itt . chain . from_iterable ( _ ) ) for _ in zip ( * data ) ) | Perform column - stacking on a list of 2d data blocks . |
12,049 | def discover_conf_py_directory ( initial_dir ) : initial_dir = pathlib . Path ( initial_dir ) . resolve ( ) try : return str ( _search_parents ( initial_dir ) ) except FileNotFoundError : raise | Discover the directory containing the conf . py file . |
12,050 | def _search_parents ( initial_dir ) : root_paths = ( '.' , '/' ) parent = pathlib . Path ( initial_dir ) while True : if _has_conf_py ( parent ) : return parent if str ( parent ) in root_paths : break parent = parent . parent msg = ( "Cannot detect a conf.py Sphinx configuration file from {!s}. " "Are you inside a Sphinx documenation repository?" ) . format ( initial_dir ) raise FileNotFoundError ( msg ) | Search the initial and parent directories for a conf . py Sphinx configuration file that represents the root of a Sphinx project . |
12,051 | def request_session ( token , url = None ) : if url is None : api = SlackApi ( ) else : api = SlackApi ( url ) response = api . rtm . start ( token = token ) return SessionMetadata ( response , api , token ) | Requests a WebSocket session for the Real - Time Messaging API . Returns a SessionMetadata object containing the information retrieved from the API call . |
12,052 | def _find_resource_by_key ( self , resource_list , key , value ) : original = value value = unicode ( value . upper ( ) ) for k , resource in resource_list . iteritems ( ) : if key in resource and resource [ key ] . upper ( ) == value : return k , resource raise KeyError , original | Finds a resource by key first case insensitive match . |
12,053 | def find_im_by_user_name ( self , name , auto_create = True ) : uid = self . find_user_by_name ( name ) [ 0 ] try : return self . find_im_by_user_id ( uid ) except KeyError : if auto_create : response = self . api . im . open ( token = self . token , user = uid ) return response [ u'channel' ] [ u'id' ] else : raise | Finds the ID of the IM with a particular user by name with the option to automatically create a new channel if it doesn t exist . |
12,054 | def update ( self , event ) : event = event . copy ( ) reactor . callInThread ( self . _update_deferred , event ) | All messages from the Protocol get passed through this method . This allows the client to have an up - to - date state for the client . However this method doesn t actually update right away . Instead the acutal update happens in another thread potentially later in order to allow user code to handle the event faster . |
12,055 | def iter_series ( self , workbook , row , col ) : for series in self . __series : series = dict ( series ) series [ "values" ] = series [ "values" ] . get_formula ( workbook , row , col ) if "categories" in series : series [ "categories" ] = series [ "categories" ] . get_formula ( workbook , row , col ) yield series | Yield series dictionaries with values resolved to the final excel formulas . |
12,056 | def get_userinfo ( self ) : wanted_fields = [ "name" , "mobile" , "orgEmail" , "position" , "avatar" ] userinfo = { k : self . json_response . get ( k , None ) for k in wanted_fields } return userinfo | Method to get current user s name mobile email and position . |
12,057 | def get_admin_ids ( self ) : admins = self . json_response . get ( "admin_list" , None ) admin_ids = [ admin_id for admin_id in admins [ "userid" ] ] return admin_ids | Method to get the administrator id list . |
12,058 | def run ( program , * args , ** kwargs ) : args = flattened ( args , split = SHELL ) full_path = which ( program ) logger = kwargs . pop ( "logger" , LOG . debug ) fatal = kwargs . pop ( "fatal" , True ) dryrun = kwargs . pop ( "dryrun" , is_dryrun ( ) ) include_error = kwargs . pop ( "include_error" , False ) message = "Would run" if dryrun else "Running" message = "%s: %s %s" % ( message , short ( full_path or program ) , represented_args ( args ) ) if logger : logger ( message ) if dryrun : return message if not full_path : return abort ( "%s is not installed" , short ( program ) , fatal = fatal ) stdout = kwargs . pop ( "stdout" , subprocess . PIPE ) stderr = kwargs . pop ( "stderr" , subprocess . PIPE ) args = [ full_path ] + args try : path_env = kwargs . pop ( "path_env" , None ) if path_env : kwargs [ "env" ] = added_env_paths ( path_env , env = kwargs . get ( "env" ) ) p = subprocess . Popen ( args , stdout = stdout , stderr = stderr , ** kwargs ) output , err = p . communicate ( ) output = decode ( output , strip = True ) err = decode ( err , strip = True ) if p . returncode and fatal is not None : note = ": %s\n%s" % ( err , output ) if output or err else "" message = "%s exited with code %s%s" % ( short ( program ) , p . returncode , note . strip ( ) ) return abort ( message , fatal = fatal ) if include_error and err : output = "%s\n%s" % ( output , err ) return output and output . strip ( ) except Exception as e : return abort ( "%s failed: %s" , short ( program ) , e , exc_info = e , fatal = fatal ) | Run program with args |
12,059 | def get_dept_name ( self ) : self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return self . json_response . get ( "name" , None ) | Method to get the department name |
12,060 | def get_dept_manager_ids ( self ) : self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return self . json_response . get ( "deptManagerUseridList" , None ) | Method to get the id list of department manager . |
12,061 | def get_depts ( self , dept_name = None ) : depts = self . json_response . get ( "department" , None ) params = self . kwargs . get ( "params" , None ) fetch_child = params . get ( "fetch_child" , True ) if params else True if dept_name is not None : depts = [ dept for dept in depts if dept [ "name" ] == dept_name ] depts = [ { "id" : dept [ "id" ] , "name" : dept [ "name" ] } for dept in depts ] self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return depts if fetch_child else depts [ 0 ] | Method to get department by name . |
12,062 | def setup ( app ) : jira . setup ( app ) lsstdocushare . setup ( app ) mockcoderefs . setup ( app ) packagetoctree . setup ( app ) remotecodeblock . setup ( app ) try : __version__ = get_distribution ( 'documenteer' ) . version except DistributionNotFound : __version__ = 'unknown' return { 'version' : __version__ , 'parallel_read_safe' : True , 'parallel_write_safe' : True } | Wrapper for the setup functions of each individual extension module . |
12,063 | def task_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : node = pending_task_xref ( rawsource = text ) return [ node ] , [ ] | Process a role that references the target nodes created by the lsst - task directive . |
12,064 | def process_pending_task_xref_nodes ( app , doctree , fromdocname ) : logger = getLogger ( __name__ ) env = app . builder . env for node in doctree . traverse ( pending_task_xref ) : content = [ ] role_parts = split_role_content ( node . rawsource ) task_id = format_task_id ( role_parts [ 'ref' ] ) if role_parts [ 'display' ] : display_text = role_parts [ 'display' ] elif role_parts [ 'last_component' ] : display_text = role_parts [ 'ref' ] . split ( '.' ) [ - 1 ] else : display_text = role_parts [ 'ref' ] link_label = nodes . literal ( ) link_label += nodes . Text ( display_text , display_text ) if hasattr ( env , 'lsst_task_topics' ) and task_id in env . lsst_task_topics : task_data = env . lsst_task_topics [ task_id ] ref_node = nodes . reference ( '' , '' ) ref_node [ 'refdocname' ] = task_data [ 'docname' ] ref_node [ 'refuri' ] = app . builder . get_relative_uri ( fromdocname , task_data [ 'docname' ] ) ref_node [ 'refuri' ] += '#' + task_data [ 'target' ] [ 'refid' ] ref_node += link_label content . append ( ref_node ) else : content . append ( link_label ) message = 'lsst-task could not find a reference to %s' logger . warning ( message , role_parts [ 'ref' ] , location = node ) node . replace_self ( content ) | Process the pending_task_xref nodes during the doctree - resolved event to insert links to the locations of lsst - task - topic directives . |
12,065 | def config_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : node = pending_config_xref ( rawsource = text ) return [ node ] , [ ] | Process a role that references the target nodes created by the lsst - config - topic directive . |
12,066 | def process_pending_config_xref_nodes ( app , doctree , fromdocname ) : logger = getLogger ( __name__ ) env = app . builder . env for node in doctree . traverse ( pending_config_xref ) : content = [ ] role_parts = split_role_content ( node . rawsource ) config_id = format_config_id ( role_parts [ 'ref' ] ) if role_parts [ 'display' ] : display_text = role_parts [ 'display' ] elif role_parts [ 'last_component' ] : display_text = role_parts [ 'ref' ] . split ( '.' ) [ - 1 ] else : display_text = role_parts [ 'ref' ] link_label = nodes . literal ( ) link_label += nodes . Text ( display_text , display_text ) if hasattr ( env , 'lsst_task_topics' ) and config_id in env . lsst_task_topics : config_data = env . lsst_task_topics [ config_id ] ref_node = nodes . reference ( '' , '' ) ref_node [ 'refdocname' ] = config_data [ 'docname' ] ref_node [ 'refuri' ] = app . builder . get_relative_uri ( fromdocname , config_data [ 'docname' ] ) ref_node [ 'refuri' ] += '#' + config_data [ 'target' ] [ 'refid' ] ref_node += link_label content . append ( ref_node ) else : content . append ( link_label ) message = 'lsst-config could not find a reference to %s' logger . warning ( message , role_parts [ 'ref' ] , location = node ) node . replace_self ( content ) | Process the pending_config_xref nodes during the doctree - resolved event to insert links to the locations of lsst - config - topic directives . |
12,067 | def configfield_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : node = pending_configfield_xref ( rawsource = text ) return [ node ] , [ ] | Process a role that references the Task configuration field nodes created by the lsst - config - fields lsst - task - config - subtasks and lsst - task - config - subtasks directives . |
12,068 | def process_pending_configfield_xref_nodes ( app , doctree , fromdocname ) : logger = getLogger ( __name__ ) env = app . builder . env for node in doctree . traverse ( pending_configfield_xref ) : content = [ ] role_parts = split_role_content ( node . rawsource ) namespace_components = role_parts [ 'ref' ] . split ( '.' ) field_name = namespace_components [ - 1 ] class_namespace = namespace_components [ : - 1 ] configfield_id = format_configfield_id ( class_namespace , field_name ) if role_parts [ 'display' ] : display_text = role_parts [ 'display' ] elif role_parts [ 'last_component' ] : display_text = role_parts [ 'ref' ] . split ( '.' ) [ - 1 ] else : display_text = role_parts [ 'ref' ] link_label = nodes . literal ( ) link_label += nodes . Text ( display_text , display_text ) if hasattr ( env , 'lsst_configfields' ) and configfield_id in env . lsst_configfields : configfield_data = env . lsst_configfields [ configfield_id ] ref_node = nodes . reference ( '' , '' ) ref_node [ 'refdocname' ] = configfield_data [ 'docname' ] ref_node [ 'refuri' ] = app . builder . get_relative_uri ( fromdocname , configfield_data [ 'docname' ] ) ref_node [ 'refuri' ] += '#' + configfield_id ref_node += link_label content . append ( ref_node ) else : literal_node = nodes . literal ( ) link_label = nodes . Text ( field_name , field_name ) literal_node += link_label content . append ( literal_node ) message = 'lsst-config-field could not find a reference to %s' logger . warning ( message , role_parts [ 'ref' ] , location = node ) node . replace_self ( content ) | Process the pending_configfield_xref nodes during the doctree - resolved event to insert links to the locations of configuration field nodes . |
12,069 | def to_bytesize ( value , default_unit = None , base = DEFAULT_BASE ) : if isinstance ( value , ( int , float ) ) : return unitized ( value , default_unit , base ) if value is None : return None try : if value [ - 1 ] . lower ( ) == "b" : value = value [ : - 1 ] unit = value [ - 1 : ] . lower ( ) if unit . isdigit ( ) : unit = default_unit else : value = value [ : - 1 ] return unitized ( to_number ( float , value ) , unit , base ) except ( IndexError , TypeError , ValueError ) : return None | Convert value to bytes accepts notations such as 4k to mean 4096 bytes |
12,070 | def to_number ( result_type , value , default = None , minimum = None , maximum = None ) : try : return capped ( result_type ( value ) , minimum , maximum ) except ( TypeError , ValueError ) : return default | Cast value to numeric result_type if possible |
12,071 | def set_providers ( self , * providers ) : if self . providers : self . clear ( ) for provider in providers : self . add ( provider ) | Replace current providers with given ones |
12,072 | def get_bytesize ( self , key , default = None , minimum = None , maximum = None , default_unit = None , base = DEFAULT_BASE ) : value = to_bytesize ( self . get_str ( key ) , default_unit , base ) if value is None : return to_bytesize ( default , default_unit , base ) return capped ( value , to_bytesize ( minimum , default_unit , base ) , to_bytesize ( maximum , default_unit , base ) ) | Size in bytes expressed by value configured under key |
12,073 | def install ( application , ** kwargs ) : if getattr ( application , 'statsd' , None ) is not None : LOGGER . warning ( 'Statsd collector is already installed' ) return False if 'host' not in kwargs : kwargs [ 'host' ] = os . environ . get ( 'STATSD_HOST' , '127.0.0.1' ) if 'port' not in kwargs : kwargs [ 'port' ] = os . environ . get ( 'STATSD_PORT' , '8125' ) if 'protocol' not in kwargs : kwargs [ 'protocol' ] = os . environ . get ( 'STATSD_PROTOCOL' , 'udp' ) setattr ( application , 'statsd' , StatsDCollector ( ** kwargs ) ) return True | Call this to install StatsD for the Tornado application . |
12,074 | def record_timing ( self , duration , * path ) : self . application . statsd . send ( path , duration * 1000.0 , 'ms' ) | Record a timing . |
12,075 | def increase_counter ( self , * path , ** kwargs ) : self . application . statsd . send ( path , kwargs . get ( 'amount' , '1' ) , 'c' ) | Increase a counter . |
12,076 | def execution_timer ( self , * path ) : start = time . time ( ) try : yield finally : self . record_timing ( max ( start , time . time ( ) ) - start , * path ) | Record the time it takes to perform an arbitrary code block . |
12,077 | def on_finish ( self ) : super ( ) . on_finish ( ) self . record_timing ( self . request . request_time ( ) , self . __class__ . __name__ , self . request . method , self . get_status ( ) ) | Records the time taken to process the request . |
12,078 | async def _tcp_on_closed ( self ) : LOGGER . warning ( 'Not connected to statsd, connecting in %s seconds' , self . _tcp_reconnect_sleep ) await asyncio . sleep ( self . _tcp_reconnect_sleep ) self . _sock = self . _tcp_socket ( ) | Invoked when the socket is closed . |
12,079 | def send ( self , path , value , metric_type ) : msg = self . _msg_format . format ( path = self . _build_path ( path , metric_type ) , value = value , metric_type = metric_type ) LOGGER . debug ( 'Sending %s to %s:%s' , msg . encode ( 'ascii' ) , self . _host , self . _port ) try : if self . _tcp : if self . _sock . closed ( ) : return return self . _sock . write ( msg . encode ( 'ascii' ) ) self . _sock . sendto ( msg . encode ( 'ascii' ) , ( self . _host , self . _port ) ) except iostream . StreamClosedError as error : LOGGER . warning ( 'Error sending TCP statsd metric: %s' , error ) except ( OSError , socket . error ) as error : LOGGER . exception ( 'Error sending statsd metric: %s' , error ) | Send a metric to Statsd . |
12,080 | def _build_path ( self , path , metric_type ) : path = self . _get_prefixes ( metric_type ) + list ( path ) return '{}.{}' . format ( self . _namespace , '.' . join ( str ( p ) . replace ( '.' , '-' ) for p in path ) ) | Return a normalized path . |
12,081 | def _get_prefixes ( self , metric_type ) : prefixes = [ ] if self . _prepend_metric_type : prefixes . append ( self . METRIC_TYPES [ metric_type ] ) return prefixes | Get prefixes where applicable |
12,082 | def _show_feedback_label ( self , message , seconds = None ) : if seconds is None : seconds = CONFIG [ 'MESSAGE_DURATION' ] logger . debug ( 'Label feedback: "{}"' . format ( message ) ) self . feedback_label_timer . timeout . connect ( self . _hide_feedback_label ) self . lbl_feedback . setText ( str ( message ) ) self . lbl_feedback . show ( ) self . feedback_label_timer . start ( 1000 * seconds ) | Display a message in lbl_feedback which times out after some number of seconds . |
12,083 | def update_user_type ( self ) : if self . rb_tutor . isChecked ( ) : self . user_type = 'tutor' elif self . rb_student . isChecked ( ) : self . user_type = 'student' self . accept ( ) | Return either tutor or student based on which radio button is selected . |
12,084 | def shuffle_sattolo ( items ) : _randrange = random . randrange for i in reversed ( range ( 1 , len ( items ) ) ) : j = _randrange ( i ) items [ j ] , items [ i ] = items [ i ] , items [ j ] | Shuffle items in place using Sattolo s algorithm . |
12,085 | def column_list ( string ) : try : columns = list ( map ( int , string . split ( ',' ) ) ) except ValueError as e : raise argparse . ArgumentTypeError ( * e . args ) for column in columns : if column < 1 : raise argparse . ArgumentTypeError ( 'Invalid column {!r}: column numbers start at 1.' . format ( column ) ) return columns | Validate and convert comma - separated list of column numbers . |
12,086 | def main ( ) : parser = argparse . ArgumentParser ( description = 'Shuffle columns in a CSV file' ) parser . add_argument ( metavar = "FILE" , dest = 'input_file' , type = argparse . FileType ( 'r' ) , nargs = '?' , default = sys . stdin , help = 'Input CSV file. If omitted, read standard input.' ) parser . add_argument ( '-s' , '--sattolo' , action = 'store_const' , const = shuffle_sattolo , dest = 'shuffle' , default = random . shuffle , help = "Use Sattolo's shuffle algorithm." ) col_group = parser . add_mutually_exclusive_group ( ) col_group . add_argument ( '-c' , '--columns' , type = column_list , help = 'Comma-separated list of columns to include.' ) col_group . add_argument ( '-C' , '--no-columns' , type = column_list , help = 'Comma-separated list of columns to exclude.' ) delim_group = parser . add_mutually_exclusive_group ( ) delim_group . add_argument ( '-d' , '--delimiter' , type = str , default = ',' , help = 'Input column delimiter.' ) delim_group . add_argument ( '-t' , '--tabbed' , dest = 'delimiter' , action = 'store_const' , const = '\t' , help = 'Delimit input with tabs.' ) parser . add_argument ( '-q' , '--quotechar' , type = str , default = '"' , help = 'Quote character.' ) parser . add_argument ( '-o' , '--output-delimiter' , type = str , default = ',' , help = 'Output column delimiter.' ) parser . add_argument ( '-v' , '--version' , action = 'version' , version = '%(prog)s {version}' . format ( version = __version__ ) ) args = parser . parse_args ( ) reader = csv . reader ( args . input_file , delimiter = args . delimiter , quotechar = args . quotechar ) headers = next ( reader ) table = [ ] for c in range ( len ( headers ) ) : table . append ( [ ] ) for row in reader : for c in range ( len ( headers ) ) : table [ c ] . append ( row [ c ] ) cols = args . columns if args . no_columns : cols = list ( set ( range ( len ( headers ) ) ) - set ( args . no_columns ) ) elif not cols : cols = range ( len ( headers ) ) for c in cols : if c > len ( headers ) : sys . stderr . write ( 'Invalid column {0}. Last column is {1}.\n' . format ( c , len ( headers ) ) ) exit ( 1 ) args . shuffle ( table [ c - 1 ] ) table = zip ( * table ) writer = csv . writer ( sys . stdout , delimiter = args . output_delimiter ) writer . writerow ( headers ) for row in table : writer . writerow ( row ) | Get the first row and use it as column headers |
12,087 | def get ( self , keyword ) : if not keyword . startswith ( ':' ) : keyword = ':' + keyword for i , s in enumerate ( self . data ) : if s . to_string ( ) . upper ( ) == keyword . upper ( ) : if i < len ( self . data ) - 1 : return self . data [ i + 1 ] else : return None return None | Return the element of the list after the given keyword . |
12,088 | def gets ( self , keyword ) : param = self . get ( keyword ) if param is not None : return safe_decode ( param . string_value ( ) ) return None | Return the element of the list after the given keyword as string . |
12,089 | def append ( self , obj ) : if isinstance ( obj , str ) : obj = KQMLToken ( obj ) self . data . append ( obj ) | Append an element to the end of the list . |
12,090 | def push ( self , obj ) : if isinstance ( obj , str ) : obj = KQMLToken ( obj ) self . data . insert ( 0 , obj ) | Prepend an element to the beginnging of the list . |
12,091 | def set ( self , keyword , value ) : if not keyword . startswith ( ':' ) : keyword = ':' + keyword if isinstance ( value , str ) : value = KQMLToken ( value ) if isinstance ( keyword , str ) : keyword = KQMLToken ( keyword ) found = False for i , key in enumerate ( self . data ) : if key . to_string ( ) . lower ( ) == keyword . lower ( ) : found = True if i < len ( self . data ) - 1 : self . data [ i + 1 ] = value break if not found : self . data . append ( keyword ) self . data . append ( value ) | Set the element of the list after the given keyword . |
12,092 | def sets ( self , keyword , value ) : if isinstance ( value , str ) : value = KQMLString ( value ) self . set ( keyword , value ) | Set the element of the list after the given keyword as string . |
12,093 | def read_recipe ( self , filename ) : Global . LOGGER . debug ( f"reading recipe {filename}" ) if not os . path . isfile ( filename ) : Global . LOGGER . error ( filename + " recipe not found, skipping" ) return config = configparser . ConfigParser ( allow_no_value = True , delimiters = "=" ) config . read ( filename ) for section in config . sections ( ) : self . sections [ section ] = config [ section ] Global . LOGGER . debug ( "Read recipe " + filename ) | Read a recipe file from disk |
12,094 | def set_socket_address ( self ) : Global . LOGGER . debug ( 'defining socket addresses for zmq' ) random . seed ( ) default_port = random . randrange ( 5001 , 5999 ) internal_0mq_address = "tcp://127.0.0.1" internal_0mq_port_subscriber = str ( default_port ) internal_0mq_port_publisher = str ( default_port ) Global . LOGGER . info ( str . format ( f"zmq subsystem subscriber on {internal_0mq_port_subscriber} port" ) ) Global . LOGGER . info ( str . format ( f"zmq subsystem publisher on {internal_0mq_port_publisher} port" ) ) self . subscriber_socket_address = f"{internal_0mq_address}:{internal_0mq_port_subscriber}" self . publisher_socket_address = f"{internal_0mq_address}:{internal_0mq_port_publisher}" | Set a random port to be used by zmq |
12,095 | def get_quantities ( self , quantities , filters = None , native_filters = None , return_iterator = False ) : quantities = self . _preprocess_requested_quantities ( quantities ) filters = self . _preprocess_filters ( filters ) native_filters = self . _preprocess_native_filters ( native_filters ) it = self . _get_quantities_iter ( quantities , filters , native_filters ) if return_iterator : return it data_all = defaultdict ( list ) for data in it : for q in quantities : data_all [ q ] . append ( data [ q ] ) return { q : concatenate_1d ( data_all [ q ] ) for q in quantities } | Fetch quantities from this catalog . |
12,096 | def list_all_quantities ( self , include_native = False , with_info = False ) : q = set ( self . _quantity_modifiers ) if include_native : q . update ( self . _native_quantities ) return { k : self . get_quantity_info ( k ) for k in q } if with_info else list ( q ) | Return a list of all available quantities in this catalog . |
12,097 | def list_all_native_quantities ( self , with_info = False ) : q = self . _native_quantities return { k : self . get_quantity_info ( k ) for k in q } if with_info else list ( q ) | Return a list of all available native quantities in this catalog . |
12,098 | def first_available ( self , * quantities ) : for i , q in enumerate ( quantities ) : if self . has_quantity ( q ) : if i : warnings . warn ( '{} not available; using {} instead' . format ( quantities [ 0 ] , q ) ) return q | Return the first available quantity in the input arguments . Return None if none of them is available . |
12,099 | def get_input_kwargs ( self , key = None , default = None ) : warnings . warn ( "`get_input_kwargs` is deprecated; use `get_catalog_info` instead." , DeprecationWarning ) return self . get_catalog_info ( key , default ) | Deprecated . Use get_catalog_info instead . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.