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 sche... | 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... | 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 ) ) log... | 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 , 4... | 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 isins... | 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... | 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 ... | 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 =... | 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__... | 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 ... | 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... | 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... | 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 = Fa... | 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 . __... | 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 ... | 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__ ,... | 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_cla... | 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 ) , st... | 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... | 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 k... | 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_no... | 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_para... | 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_na... | 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 = Re... | 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 aggregato... | 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 ... | 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 , sel... | 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 ... | 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 [ r... | 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 ( ... | 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 i... |
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 Sphi... | 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 ... | 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 ] de... | 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__ , 'pa... | 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 [ 'dis... | 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_part... | 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 ( '.... | 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 ( ) ... | 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 , de... | 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... | 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 . c... | 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 ) ) sel... | 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 ) ) retur... | 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_argumen... | 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 ( ) == ... | 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 )... | 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 . L... | 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_quanti... | 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.