query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Starts the scheduler to check for scheduled calls and execute them at the correct time . | def scheduler ( self , sleep_time = 0.2 ) : while self . listening : # If we have any scheduled calls, execute them and remove them from # our list of scheduled calls. 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..." ) | 12,000 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L244-L267 | [
"def",
"_convert_strls",
"(",
"self",
",",
"data",
")",
":",
"convert_cols",
"=",
"[",
"col",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"data",
")",
"if",
"self",
".",
"typlist",
"[",
"i",
"]",
"==",
"32768",
"or",
"col",
"in",
"self",
".",
"_convert_strl",
"]",
"if",
"convert_cols",
":",
"ssw",
"=",
"StataStrLWriter",
"(",
"data",
",",
"convert_cols",
")",
"tab",
",",
"new_data",
"=",
"ssw",
".",
"generate_table",
"(",
")",
"data",
"=",
"new_data",
"self",
".",
"_strl_blob",
"=",
"ssw",
".",
"generate_blob",
"(",
"tab",
")",
"return",
"data"
] |
Schedules a function to be run x number of seconds from now . | 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 ) | 12,001 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L269-L292 | [
"def",
"serialize_array",
"(",
"array",
",",
"force_list",
"=",
"False",
",",
"buffers",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"array",
",",
"np",
".",
"ma",
".",
"MaskedArray",
")",
":",
"array",
"=",
"array",
".",
"filled",
"(",
"np",
".",
"nan",
")",
"# Set masked values to nan",
"if",
"(",
"array_encoding_disabled",
"(",
"array",
")",
"or",
"force_list",
")",
":",
"return",
"transform_array_to_list",
"(",
"array",
")",
"if",
"not",
"array",
".",
"flags",
"[",
"'C_CONTIGUOUS'",
"]",
":",
"array",
"=",
"np",
".",
"ascontiguousarray",
"(",
"array",
")",
"if",
"buffers",
"is",
"None",
":",
"return",
"encode_base64_dict",
"(",
"array",
")",
"else",
":",
"return",
"encode_binary_dict",
"(",
"array",
",",
"buffers",
")"
] |
Checks to see if it s time to run a scheduled call or not . | 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 | 12,002 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L294-L322 | [
"def",
"export_public_keys",
"(",
"self",
",",
"identities",
")",
":",
"public_keys",
"=",
"[",
"]",
"with",
"self",
".",
"device",
":",
"for",
"i",
"in",
"identities",
":",
"pubkey",
"=",
"self",
".",
"device",
".",
"pubkey",
"(",
"identity",
"=",
"i",
")",
"vk",
"=",
"formats",
".",
"decompress_pubkey",
"(",
"pubkey",
"=",
"pubkey",
",",
"curve_name",
"=",
"i",
".",
"curve_name",
")",
"public_key",
"=",
"formats",
".",
"export_public_key",
"(",
"vk",
"=",
"vk",
",",
"label",
"=",
"i",
".",
"to_string",
"(",
")",
")",
"public_keys",
".",
"append",
"(",
"public_key",
")",
"return",
"public_keys"
] |
Sends a UDP datagram packet to the requested address . | 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." ) | 12,003 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L324-L360 | [
"def",
"get_atoms",
"(",
"self",
",",
"inc_alt_states",
"=",
"False",
")",
":",
"if",
"inc_alt_states",
":",
"return",
"itertools",
".",
"chain",
"(",
"*",
"[",
"x",
"[",
"1",
"]",
".",
"values",
"(",
")",
"for",
"x",
"in",
"sorted",
"(",
"list",
"(",
"self",
".",
"states",
".",
"items",
"(",
")",
")",
")",
"]",
")",
"return",
"self",
".",
"atoms",
".",
"values",
"(",
")"
] |
Executes when UDP data has been received and sends the packet data to our app to process the request . | def receive_datagram ( self , data , address ) : # If we do not specify an application, just print the data. if not self . app : logger . debug ( "Packet received" , address , data ) return False # Send the data we've recieved from the network and send it # to our application for processing. 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 our application generated a response to this message, # send it to the original sender. if response : self . send_datagram ( response , address ) | 12,004 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L362-L394 | [
"def",
"_database",
"(",
"self",
",",
"writable",
"=",
"False",
")",
":",
"if",
"self",
".",
"path",
"==",
"MEMORY_DB_NAME",
":",
"if",
"not",
"self",
".",
"inmemory_db",
":",
"self",
".",
"inmemory_db",
"=",
"xapian",
".",
"inmemory_open",
"(",
")",
"return",
"self",
".",
"inmemory_db",
"if",
"writable",
":",
"database",
"=",
"xapian",
".",
"WritableDatabase",
"(",
"self",
".",
"path",
",",
"xapian",
".",
"DB_CREATE_OR_OPEN",
")",
"else",
":",
"try",
":",
"database",
"=",
"xapian",
".",
"Database",
"(",
"self",
".",
"path",
")",
"except",
"xapian",
".",
"DatabaseOpeningError",
":",
"raise",
"InvalidIndexError",
"(",
"'Unable to open index at %s'",
"%",
"self",
".",
"path",
")",
"return",
"database"
] |
Create a application configured to send metrics . | def make_application ( ) : settings = { } application = web . Application ( [ web . url ( '/' , SimpleHandler ) ] , * * settings ) statsd . install ( application , * * { 'namespace' : 'testing' } ) return application | 12,005 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/examples/statsd.py#L34-L48 | [
"def",
"TxKazooClient",
"(",
"reactor",
",",
"pool",
",",
"client",
")",
":",
"make_thimble",
"=",
"partial",
"(",
"Thimble",
",",
"reactor",
",",
"pool",
")",
"wrapper",
"=",
"_RunCallbacksInReactorThreadWrapper",
"(",
"reactor",
",",
"client",
")",
"client_thimble",
"=",
"make_thimble",
"(",
"wrapper",
",",
"_blocking_client_methods",
")",
"def",
"_Lock",
"(",
"path",
",",
"identifier",
"=",
"None",
")",
":",
"\"\"\"Return a wrapped :class:`kazoo.recipe.lock.Lock` for this client.\"\"\"",
"lock",
"=",
"client",
".",
"Lock",
"(",
"path",
",",
"identifier",
")",
"return",
"Thimble",
"(",
"reactor",
",",
"pool",
",",
"lock",
",",
"_blocking_lock_methods",
")",
"client_thimble",
".",
"Lock",
"=",
"_Lock",
"client_thimble",
".",
"SetPartitioner",
"=",
"partial",
"(",
"_SetPartitionerWrapper",
",",
"reactor",
",",
"pool",
",",
"client",
")",
"# Expose these so e.g. recipes can access them from the kzclient",
"client",
".",
"reactor",
"=",
"reactor",
"client",
".",
"pool",
"=",
"pool",
"client",
".",
"kazoo_client",
"=",
"client",
"return",
"client_thimble"
] |
Generate analysis output as html page | def plots_html_page ( query_module ) : # page template template = jenv . get_template ( "analysis.html" ) # container for template context context = dict ( extended = config . EXTENDED ) # a database client/session to run queries in cl = client . get_client ( ) session = cl . create_session ( ) # general styling seaborn . set_style ( 'whitegrid' ) # # plot: painting area by decade, with linear regression # 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' ) # # plot: painting area by gender, with logistic regression # 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' ) # # render template # out_file = path . join ( out_dir , "analysis.html" ) html_content = template . render ( * * context ) with open ( out_file , 'w' ) as f : f . write ( html_content ) # done, clean up plt . close ( 'all' ) session . close ( ) | 12,006 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/leonardo/leonardo/common/analysis.py#L50-L113 | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
convert values in a row to types accepted by excel | 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 ] | 12,007 | https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/worksheet.py#L640-L666 | [
"def",
"make_config",
"(",
"self",
",",
"instance_relative",
":",
"bool",
"=",
"False",
")",
"->",
"Config",
":",
"config",
"=",
"self",
".",
"config_class",
"(",
"self",
".",
"instance_path",
"if",
"instance_relative",
"else",
"self",
".",
"root_path",
",",
"DEFAULT_CONFIG",
",",
")",
"config",
"[",
"'ENV'",
"]",
"=",
"get_env",
"(",
")",
"config",
"[",
"'DEBUG'",
"]",
"=",
"get_debug_flag",
"(",
")",
"return",
"config"
] |
Yield rows as lists of data . | def iterrows ( self , workbook = None ) : resolved_tables = [ ] max_height = 0 max_width = 0 # while yielding rows __formula_values is updated with any formula values set on Expressions self . __formula_values = { } for name , ( table , ( row , col ) ) in list ( self . __tables . items ( ) ) : # get the resolved 2d data array from the table # # expressions with no explicit table will use None when calling # get_table/get_table_pos, which should return the current table. # 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 ) # Build the whole table up-front. Doing it row by row is too slow. 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 | 12,008 | https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/worksheet.py#L115-L169 | [
"def",
"v6_nd_suppress_ra",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"int_type",
"=",
"str",
"(",
"kwargs",
".",
"pop",
"(",
"'int_type'",
")",
".",
"lower",
"(",
")",
")",
"name",
"=",
"str",
"(",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
")",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"int_types",
"=",
"[",
"'gigabitethernet'",
",",
"'tengigabitethernet'",
",",
"'fortygigabitethernet'",
",",
"'hundredgigabitethernet'",
",",
"'ve'",
"]",
"if",
"int_type",
"not",
"in",
"int_types",
":",
"raise",
"ValueError",
"(",
"\"`int_type` must be one of: %s\"",
"%",
"repr",
"(",
"int_types",
")",
")",
"if",
"int_type",
"==",
"\"ve\"",
":",
"if",
"not",
"pynos",
".",
"utilities",
".",
"valid_vlan_id",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"`name` must be between `1` and `8191`\"",
")",
"rbridge_id",
"=",
"kwargs",
".",
"pop",
"(",
"'rbridge_id'",
",",
"\"1\"",
")",
"nd_suppress_args",
"=",
"dict",
"(",
"name",
"=",
"name",
",",
"rbridge_id",
"=",
"rbridge_id",
")",
"nd_suppress",
"=",
"getattr",
"(",
"self",
".",
"_rbridge",
",",
"'rbridge_id_interface_ve_ipv6_'",
"'ipv6_nd_ra_ipv6_intf_cmds_'",
"'nd_suppress_ra_suppress_ra_all'",
")",
"config",
"=",
"nd_suppress",
"(",
"*",
"*",
"nd_suppress_args",
")",
"else",
":",
"if",
"not",
"pynos",
".",
"utilities",
".",
"valid_interface",
"(",
"int_type",
",",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"`name` must match \"",
"\"`^[0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3}$`\"",
")",
"nd_suppress_args",
"=",
"dict",
"(",
"name",
"=",
"name",
")",
"nd_suppress",
"=",
"getattr",
"(",
"self",
".",
"_interface",
",",
"'interface_%s_ipv6_ipv6_nd_ra_'",
"'ipv6_intf_cmds_nd_suppress_ra_'",
"'suppress_ra_all'",
"%",
"int_type",
")",
"config",
"=",
"nd_suppress",
"(",
"*",
"*",
"nd_suppress_args",
")",
"return",
"callback",
"(",
"config",
")"
] |
Method to create a file on the Control - Server | 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 ) | 12,009 | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/api/file.py#L26-L65 | [
"def",
"bundles",
"(",
")",
":",
"per_page",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'per_page'",
",",
"30",
")",
")",
"page",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'page'",
",",
"1",
")",
")",
"query",
"=",
"store",
".",
"bundles",
"(",
")",
"query_page",
"=",
"query",
".",
"paginate",
"(",
"page",
",",
"per_page",
"=",
"per_page",
")",
"data",
"=",
"[",
"]",
"for",
"bundle_obj",
"in",
"query_page",
".",
"items",
":",
"bundle_data",
"=",
"bundle_obj",
".",
"to_dict",
"(",
")",
"bundle_data",
"[",
"'versions'",
"]",
"=",
"[",
"version",
".",
"to_dict",
"(",
")",
"for",
"version",
"in",
"bundle_obj",
".",
"versions",
"]",
"data",
".",
"append",
"(",
"bundle_data",
")",
"return",
"jsonify",
"(",
"bundles",
"=",
"data",
")"
] |
Decorate a configuration field formatter function to register it with the get_field_formatter accessor . | 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 ] # Before running the formatter, do type checking 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 ) ) ) # Run the formatter itself nodes = formatter ( * args , * * kwargs ) # Package nodes from the formatter into a section section = make_section ( section_id = field_id + '-section' , contents = nodes ) return section FIELD_FORMATTERS [ field_typestr ] = wrapped_formatter return wrapped_formatter return decorator_register | 12,010 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L281-L319 | [
"def",
"delete_file",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"validate_type",
"(",
"path",
",",
"*",
"six",
".",
"string_types",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"path",
"=",
"\"/\"",
"+",
"path",
"self",
".",
"_conn",
".",
"delete",
"(",
"\"/ws/FileData{path}\"",
".",
"format",
"(",
"path",
"=",
"path",
")",
")"
] |
Create a section node that documents a ConfigurableField config field . | def format_configurablefield_nodes ( field_name , field , field_id , state , lineno ) : # Custom default target definition list that links to Task topics 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 # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += default_item dl += create_field_type_item_node ( field , state ) # Doc for this ConfigurableField, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,011 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L380-L424 | [
"def",
"readme_verify",
"(",
")",
":",
"expected",
"=",
"populate_readme",
"(",
"REVISION",
",",
"RTD_VERSION",
")",
"# Actually get the stored contents.",
"with",
"open",
"(",
"README_FILE",
",",
"\"r\"",
")",
"as",
"file_obj",
":",
"contents",
"=",
"file_obj",
".",
"read",
"(",
")",
"if",
"contents",
"!=",
"expected",
":",
"err_msg",
"=",
"\"\\n\"",
"+",
"get_diff",
"(",
"contents",
",",
"expected",
",",
"\"README.rst.actual\"",
",",
"\"README.rst.expected\"",
")",
"raise",
"ValueError",
"(",
"err_msg",
")",
"else",
":",
"print",
"(",
"\"README contents are as expected.\"",
")"
] |
Create a section node that documents a ListField config field . | def format_listfield_nodes ( field_name , field , field_id , state , lineno ) : # ListField's store their item types in the itemtype attribute 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 # Type description 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 # Reference target env = state . document . settings . env ref_target = create_configfield_ref_target_node ( field_id , env , lineno ) # Title is the field's attribute name title = nodes . title ( text = field_name ) title += ref_target # Definition list for key-value metadata 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 # Doc for this ConfigurableField, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,012 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L428-L529 | [
"def",
"get_market_gainers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"WNG_MSG",
",",
"(",
"\"get_market_gainers\"",
",",
"\"stocks.get_market_gainers\"",
")",
")",
"return",
"stocks",
".",
"get_market_gainers",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Create a section node that documents a ChoiceField config field . | def format_choicefield_nodes ( field_name , field , field_id , state , lineno ) : # Create a definition list for the choices 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 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 # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += choices_node # Doc for this ConfigurableField, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,013 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L533-L605 | [
"def",
"__create_price_for",
"(",
"self",
",",
"commodity",
":",
"Commodity",
",",
"price",
":",
"PriceModel",
")",
":",
"logging",
".",
"info",
"(",
"\"Adding a new price for %s, %s, %s\"",
",",
"commodity",
".",
"mnemonic",
",",
"price",
".",
"datetime",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
",",
"price",
".",
"value",
")",
"# safety check. Compare currencies.",
"sec_svc",
"=",
"SecurityAggregate",
"(",
"self",
".",
"book",
",",
"commodity",
")",
"currency",
"=",
"sec_svc",
".",
"get_currency",
"(",
")",
"if",
"currency",
"!=",
"price",
".",
"currency",
":",
"raise",
"ValueError",
"(",
"\"Requested currency does not match the currency previously used\"",
",",
"currency",
",",
"price",
".",
"currency",
")",
"# Description of the source field values:",
"# https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html",
"new_price",
"=",
"Price",
"(",
"commodity",
",",
"currency",
",",
"price",
".",
"datetime",
".",
"date",
"(",
")",
",",
"price",
".",
"value",
",",
"source",
"=",
"\"Finance::Quote\"",
")",
"commodity",
".",
"prices",
".",
"append",
"(",
"new_price",
")"
] |
Create a section node that documents a RangeField config field . | def format_rangefield_nodes ( field_name , field , field_id , state , lineno ) : # Field type 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 # Format definition list item for the range 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 # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += create_default_item_node ( field , state ) dl += field_type_item dl += range_node # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,014 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L609-L670 | [
"def",
"_execute_and_process_stdout",
"(",
"self",
",",
"args",
",",
"shell",
",",
"handler",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"shell",
",",
"bufsize",
"=",
"1",
")",
"out",
"=",
"'[elided, processed via handler]'",
"try",
":",
"# Even if the process dies, stdout.readline still works",
"# and will continue until it runs out of stdout to process.",
"while",
"True",
":",
"line",
"=",
"proc",
".",
"stdout",
".",
"readline",
"(",
")",
"if",
"line",
":",
"handler",
"(",
"line",
")",
"else",
":",
"break",
"finally",
":",
"# Note, communicate will not contain any buffered output.",
"(",
"unexpected_out",
",",
"err",
")",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"unexpected_out",
":",
"out",
"=",
"'[unexpected stdout] %s'",
"%",
"unexpected_out",
"for",
"line",
"in",
"unexpected_out",
".",
"splitlines",
"(",
")",
":",
"handler",
"(",
"line",
")",
"ret",
"=",
"proc",
".",
"returncode",
"logging",
".",
"debug",
"(",
"'cmd: %s, stdout: %s, stderr: %s, ret: %s'",
",",
"utils",
".",
"cli_cmd_to_string",
"(",
"args",
")",
",",
"out",
",",
"err",
",",
"ret",
")",
"if",
"ret",
"==",
"0",
":",
"return",
"err",
"else",
":",
"raise",
"AdbError",
"(",
"cmd",
"=",
"args",
",",
"stdout",
"=",
"out",
",",
"stderr",
"=",
"err",
",",
"ret_code",
"=",
"ret",
")"
] |
Create a section node that documents a DictField config field . | def format_dictfield_nodes ( field_name , field , field_id , state , lineno ) : # Custom value type field for definition list 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 # Definition list for key-value metadata 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 # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,015 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L674-L720 | [
"def",
"calc_actualremoterelease_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"aid",
"=",
"self",
".",
"sequences",
".",
"aides",
".",
"fastaccess",
"flu",
".",
"actualremoterelease",
"=",
"(",
"flu",
".",
"requiredremoterelease",
"*",
"smoothutils",
".",
"smooth_logistic1",
"(",
"aid",
".",
"waterlevel",
"-",
"con",
".",
"waterlevelminimumremotethreshold",
",",
"der",
".",
"waterlevelminimumremotesmoothpar",
")",
")"
] |
Create a section node that documents a ConfigField config field . | def format_configfield_nodes ( field_name , field , field_id , state , lineno ) : # Default data type node 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 # Definition list for key-value metadata dl = nodes . definition_list ( ) dl += dtype_node dl += create_field_type_item_node ( field , state ) # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,016 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L724-L768 | [
"def",
"HandleMessageBundles",
"(",
"self",
",",
"request_comms",
",",
"response_comms",
")",
":",
"messages",
",",
"source",
",",
"timestamp",
"=",
"self",
".",
"_communicator",
".",
"DecodeMessages",
"(",
"request_comms",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"messages",
":",
"# Receive messages in line.",
"self",
".",
"ReceiveMessages",
"(",
"source",
",",
"messages",
")",
"# We send the client a maximum of self.max_queue_size messages",
"required_count",
"=",
"max",
"(",
"0",
",",
"self",
".",
"max_queue_size",
"-",
"request_comms",
".",
"queue_size",
")",
"tasks",
"=",
"[",
"]",
"message_list",
"=",
"rdf_flows",
".",
"MessageList",
"(",
")",
"# Only give the client messages if we are able to receive them in a",
"# reasonable time.",
"if",
"time",
".",
"time",
"(",
")",
"-",
"now",
"<",
"10",
":",
"tasks",
"=",
"self",
".",
"DrainTaskSchedulerQueueForClient",
"(",
"source",
",",
"required_count",
")",
"message_list",
".",
"job",
"=",
"tasks",
"# Encode the message_list in the response_comms using the same API version",
"# the client used.",
"self",
".",
"_communicator",
".",
"EncodeMessages",
"(",
"message_list",
",",
"response_comms",
",",
"destination",
"=",
"source",
",",
"timestamp",
"=",
"timestamp",
",",
"api_version",
"=",
"request_comms",
".",
"api_version",
")",
"return",
"source",
",",
"len",
"(",
"messages",
")"
] |
Create a section node that documents a ConfigChoiceField config field . | def format_configchoicefield_nodes ( field_name , field , field_id , state , lineno ) : # Create a definition list for the choices 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 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 # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,017 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L772-L846 | [
"def",
"get_free_gpus",
"(",
"max_procs",
"=",
"0",
")",
":",
"# Try connect with NVIDIA drivers",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"py3nvml",
".",
"nvmlInit",
"(",
")",
"except",
":",
"str_",
"=",
"\"\"\"Couldn't connect to nvml drivers. Check they are installed correctly.\"\"\"",
"warnings",
".",
"warn",
"(",
"str_",
",",
"RuntimeWarning",
")",
"logger",
".",
"warn",
"(",
"str_",
")",
"return",
"[",
"]",
"num_gpus",
"=",
"py3nvml",
".",
"nvmlDeviceGetCount",
"(",
")",
"gpu_free",
"=",
"[",
"False",
"]",
"*",
"num_gpus",
"for",
"i",
"in",
"range",
"(",
"num_gpus",
")",
":",
"try",
":",
"h",
"=",
"py3nvml",
".",
"nvmlDeviceGetHandleByIndex",
"(",
"i",
")",
"except",
":",
"continue",
"procs",
"=",
"try_get_info",
"(",
"py3nvml",
".",
"nvmlDeviceGetComputeRunningProcesses",
",",
"h",
",",
"[",
"'something'",
"]",
")",
"if",
"len",
"(",
"procs",
")",
"<=",
"max_procs",
":",
"gpu_free",
"[",
"i",
"]",
"=",
"True",
"py3nvml",
".",
"nvmlShutdown",
"(",
")",
"return",
"gpu_free"
] |
Create a section node that documents a ConfigDictField config field . | def format_configdictfield_nodes ( field_name , field , field_id , state , lineno ) : # Valuetype links to a Config task topic 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 # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,018 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L850-L895 | [
"def",
"calc_actualremoterelease_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"aid",
"=",
"self",
".",
"sequences",
".",
"aides",
".",
"fastaccess",
"flu",
".",
"actualremoterelease",
"=",
"(",
"flu",
".",
"requiredremoterelease",
"*",
"smoothutils",
".",
"smooth_logistic1",
"(",
"aid",
".",
"waterlevel",
"-",
"con",
".",
"waterlevelminimumremotethreshold",
",",
"der",
".",
"waterlevelminimumremotesmoothpar",
")",
")"
] |
Create a section node that documents a RegistryField config field . | def format_registryfield_nodes ( field_name , field , field_id , state , lineno ) : from lsst . pex . config . registry import ConfigurableWrapper # Create a definition list for the choices # This iteration is over field.registry.items(), not field.items(), so # that the directive shows the configurables, not their ConfigClasses. choice_dl = nodes . definition_list ( ) for choice_value , choice_class in field . registry . items ( ) : # Introspect the class name from item in the registry. This is harder # than it should be. Most registry items seem to fall in the first # category. Some are ConfigurableWrapper types that expose the # underlying task class through the _target attribute. 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 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 # Doc for this field, parsed as rst desc_node = create_description_node ( field , state ) # Title for configuration field title = create_title_node ( field_name , field , field_id , state , lineno ) return [ title , dl , desc_node ] | 12,019 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L899-L990 | [
"def",
"get_market_iex_volume",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"WNG_MSG",
",",
"(",
"\"get_market_iex_volume\"",
",",
"\"stocks.get_market_iex_volume\"",
")",
")",
"return",
"stocks",
".",
"get_market_iex_volume",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Create a definition list item node that describes a field s type . | 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 | 12,020 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L993-L1020 | [
"def",
"quandl_bundle",
"(",
"environ",
",",
"asset_db_writer",
",",
"minute_bar_writer",
",",
"daily_bar_writer",
",",
"adjustment_writer",
",",
"calendar",
",",
"start_session",
",",
"end_session",
",",
"cache",
",",
"show_progress",
",",
"output_dir",
")",
":",
"api_key",
"=",
"environ",
".",
"get",
"(",
"'QUANDL_API_KEY'",
")",
"if",
"api_key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Please set your QUANDL_API_KEY environment variable and retry.\"",
")",
"raw_data",
"=",
"fetch_data_table",
"(",
"api_key",
",",
"show_progress",
",",
"environ",
".",
"get",
"(",
"'QUANDL_DOWNLOAD_ATTEMPTS'",
",",
"5",
")",
")",
"asset_metadata",
"=",
"gen_asset_metadata",
"(",
"raw_data",
"[",
"[",
"'symbol'",
",",
"'date'",
"]",
"]",
",",
"show_progress",
")",
"asset_db_writer",
".",
"write",
"(",
"asset_metadata",
")",
"symbol_map",
"=",
"asset_metadata",
".",
"symbol",
"sessions",
"=",
"calendar",
".",
"sessions_in_range",
"(",
"start_session",
",",
"end_session",
")",
"raw_data",
".",
"set_index",
"(",
"[",
"'date'",
",",
"'symbol'",
"]",
",",
"inplace",
"=",
"True",
")",
"daily_bar_writer",
".",
"write",
"(",
"parse_pricing_and_vol",
"(",
"raw_data",
",",
"sessions",
",",
"symbol_map",
")",
",",
"show_progress",
"=",
"show_progress",
")",
"raw_data",
".",
"reset_index",
"(",
"inplace",
"=",
"True",
")",
"raw_data",
"[",
"'symbol'",
"]",
"=",
"raw_data",
"[",
"'symbol'",
"]",
".",
"astype",
"(",
"'category'",
")",
"raw_data",
"[",
"'sid'",
"]",
"=",
"raw_data",
".",
"symbol",
".",
"cat",
".",
"codes",
"adjustment_writer",
".",
"write",
"(",
"splits",
"=",
"parse_splits",
"(",
"raw_data",
"[",
"[",
"'sid'",
",",
"'date'",
",",
"'split_ratio'",
",",
"]",
"]",
".",
"loc",
"[",
"raw_data",
".",
"split_ratio",
"!=",
"1",
"]",
",",
"show_progress",
"=",
"show_progress",
")",
",",
"dividends",
"=",
"parse_dividends",
"(",
"raw_data",
"[",
"[",
"'sid'",
",",
"'date'",
",",
"'ex_dividend'",
",",
"]",
"]",
".",
"loc",
"[",
"raw_data",
".",
"ex_dividend",
"!=",
"0",
"]",
",",
"show_progress",
"=",
"show_progress",
")",
")"
] |
Create a definition list item node that describes the default value of a Field config . | 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 | 12,021 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1023-L1047 | [
"def",
"delete_types_s",
"(",
"s",
",",
"types",
")",
":",
"patt",
"=",
"'(?s)'",
"+",
"'|'",
".",
"join",
"(",
"'(?<=\\n)'",
"+",
"s",
"+",
"'\\n.+?\\n(?=\\S+|$)'",
"for",
"s",
"in",
"types",
")",
"return",
"re",
".",
"sub",
"(",
"patt",
",",
"''",
",",
"'\\n'",
"+",
"s",
".",
"strip",
"(",
")",
"+",
"'\\n'",
",",
")",
".",
"strip",
"(",
")"
] |
Create a definition list item node that describes the key type of a dict - type config field . | 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 | 12,022 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1050-L1074 | [
"def",
"open",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"self",
".",
"is_opened",
"(",
")",
"and",
"self",
".",
"workbook",
".",
"file_path",
"==",
"file_path",
":",
"self",
".",
"_logger",
".",
"logger",
".",
"debug",
"(",
"\"workbook already opened: {}\"",
".",
"format",
"(",
"self",
".",
"workbook",
".",
"file_path",
")",
")",
"return",
"self",
".",
"close",
"(",
")",
"self",
".",
"_open",
"(",
"file_path",
")"
] |
Creates docutils nodes for the Field s description built from the field s doc and optional attributes . | def create_description_node ( field , state ) : doc_container_node = nodes . container ( ) doc_container_node += parse_rst_content ( field . doc , state ) return doc_container_node | 12,023 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1077-L1096 | [
"def",
"handle_input",
"(",
"self",
")",
":",
"difference",
"=",
"self",
".",
"check_state",
"(",
")",
"if",
"not",
"difference",
":",
"return",
"self",
".",
"events",
"=",
"[",
"]",
"self",
".",
"handle_new_events",
"(",
"difference",
")",
"self",
".",
"update_timeval",
"(",
")",
"self",
".",
"events",
".",
"append",
"(",
"self",
".",
"sync_marker",
"(",
"self",
".",
"timeval",
")",
")",
"self",
".",
"write_to_pipe",
"(",
"self",
".",
"events",
")"
] |
Create docutils nodes for the configuration field s title and reference target node . | def create_title_node ( field_name , field , field_id , state , lineno ) : # Reference target env = state . document . settings . env ref_target = create_configfield_ref_target_node ( field_id , env , lineno ) # Title is the field's attribute name title = nodes . title ( text = field_name ) title += ref_target return title | 12,024 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1099-L1124 | [
"def",
"no_block_read",
"(",
"output",
")",
":",
"_buffer",
"=",
"\"\"",
"if",
"not",
"fcntl",
":",
"return",
"_buffer",
"o_fd",
"=",
"output",
".",
"fileno",
"(",
")",
"o_fl",
"=",
"fcntl",
".",
"fcntl",
"(",
"o_fd",
",",
"fcntl",
".",
"F_GETFL",
")",
"fcntl",
".",
"fcntl",
"(",
"o_fd",
",",
"fcntl",
".",
"F_SETFL",
",",
"o_fl",
"|",
"os",
".",
"O_NONBLOCK",
")",
"try",
":",
"_buffer",
"=",
"output",
".",
"read",
"(",
")",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"pass",
"return",
"_buffer"
] |
Create a target node that marks a configuration field . | def create_configfield_ref_target_node ( target_id , env , lineno ) : target_node = nodes . target ( '' , '' , ids = [ target_id ] ) # Store these task/configurable topic nodes in the environment for later # cross referencing. 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 | 12,025 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1127-L1150 | [
"def",
"get_file_object",
"(",
"username",
",",
"password",
",",
"utc_start",
"=",
"None",
",",
"utc_stop",
"=",
"None",
")",
":",
"if",
"not",
"utc_start",
":",
"utc_start",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"not",
"utc_stop",
":",
"utc_stop",
"=",
"utc_start",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
"logging",
".",
"info",
"(",
"\"Downloading schedules for username [%s] in range [%s] to \"",
"\"[%s].\"",
"%",
"(",
"username",
",",
"utc_start",
",",
"utc_stop",
")",
")",
"replacements",
"=",
"{",
"'start_time'",
":",
"utc_start",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
",",
"'stop_time'",
":",
"utc_stop",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
"}",
"soap_message_xml",
"=",
"(",
"soap_message_xml_template",
"%",
"replacements",
")",
"authinfo",
"=",
"urllib2",
".",
"HTTPDigestAuthHandler",
"(",
")",
"authinfo",
".",
"add_password",
"(",
"realm",
",",
"url",
",",
"username",
",",
"password",
")",
"try",
":",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"soap_message_xml",
",",
"request_headers",
")",
"response",
"=",
"urllib2",
".",
"build_opener",
"(",
"authinfo",
")",
".",
"open",
"(",
"request",
")",
"if",
"response",
".",
"headers",
"[",
"'Content-Encoding'",
"]",
"==",
"'gzip'",
":",
"response",
"=",
"GzipStream",
"(",
"response",
")",
"except",
":",
"logging",
".",
"exception",
"(",
"\"Could not acquire connection to Schedules Direct.\"",
")",
"raise",
"return",
"response"
] |
Enables conversion from system arguments . | 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 | 12,026 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_module.py#L22-L75 | [
"def",
"optional",
"(",
"e",
",",
"default",
"=",
"Ignore",
")",
":",
"def",
"match_optional",
"(",
"s",
",",
"grm",
"=",
"None",
",",
"pos",
"=",
"0",
")",
":",
"try",
":",
"return",
"e",
"(",
"s",
",",
"grm",
",",
"pos",
")",
"except",
"PegreError",
":",
"return",
"PegreResult",
"(",
"s",
",",
"default",
",",
"(",
"pos",
",",
"pos",
")",
")",
"return",
"match_optional"
] |
Create a hidden toctree node with the contents of a directory prefixed by the directory name specified by the toctree directive option . | 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 ) ] # Sort docnames alphabetically based on **class** name. # The standard we assume is that task doc pages are named after # their Python namespace. # NOTE: this ordering only applies to the toctree; the visual ordering # is set by `process_task_topic_list`. # NOTE: docnames are **always** POSIX-like paths 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 | 12,027 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/topiclists.py#L74-L104 | [
"def",
"_sync_with_file",
"(",
"self",
")",
":",
"self",
".",
"_records",
"=",
"[",
"]",
"i",
"=",
"-",
"1",
"for",
"i",
",",
"line",
"in",
"self",
".",
"_enum_lines",
"(",
")",
":",
"self",
".",
"_records",
".",
"append",
"(",
"None",
")",
"self",
".",
"_last_synced_index",
"=",
"i"
] |
Handle GET WebMethod | 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" ) ) | 12,028 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/WebserverAction.py#L76-L84 | [
"def",
"table_apply",
"(",
"table",
",",
"func",
",",
"subset",
"=",
"None",
")",
":",
"from",
".",
"import",
"Table",
"df",
"=",
"table",
".",
"to_df",
"(",
")",
"if",
"subset",
"is",
"not",
"None",
":",
"# Iterate through columns",
"subset",
"=",
"np",
".",
"atleast_1d",
"(",
"subset",
")",
"if",
"any",
"(",
"[",
"i",
"not",
"in",
"df",
".",
"columns",
"for",
"i",
"in",
"subset",
"]",
")",
":",
"err",
"=",
"np",
".",
"where",
"(",
"[",
"i",
"not",
"in",
"df",
".",
"columns",
"for",
"i",
"in",
"subset",
"]",
")",
"[",
"0",
"]",
"err",
"=",
"\"Column mismatch: {0}\"",
".",
"format",
"(",
"[",
"subset",
"[",
"i",
"]",
"for",
"i",
"in",
"err",
"]",
")",
"raise",
"ValueError",
"(",
"err",
")",
"for",
"col",
"in",
"subset",
":",
"df",
"[",
"col",
"]",
"=",
"df",
"[",
"col",
"]",
".",
"apply",
"(",
"func",
")",
"else",
":",
"df",
"=",
"df",
".",
"apply",
"(",
"func",
")",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"Series",
")",
":",
"# Reshape it so that we can easily convert back",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"df",
")",
".",
"T",
"tab",
"=",
"Table",
".",
"from_df",
"(",
"df",
")",
"return",
"tab"
] |
Cycle for webserer | def serve_forever ( self , poll_interval = 0.5 ) : while self . is_alive : self . handle_request ( ) time . sleep ( poll_interval ) | 12,029 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/WebserverAction.py#L100-L106 | [
"def",
"get_capability_definitions",
"(",
"profile_manager",
")",
":",
"res_type",
"=",
"pbm",
".",
"profile",
".",
"ResourceType",
"(",
"resourceType",
"=",
"pbm",
".",
"profile",
".",
"ResourceTypeEnum",
".",
"STORAGE",
")",
"try",
":",
"cap_categories",
"=",
"profile_manager",
".",
"FetchCapabilityMetadata",
"(",
"res_type",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"cap_definitions",
"=",
"[",
"]",
"for",
"cat",
"in",
"cap_categories",
":",
"cap_definitions",
".",
"extend",
"(",
"cat",
".",
"capabilityMetadata",
")",
"return",
"cap_definitions"
] |
Stop the webserver | def stop ( self ) : self . is_alive = False self . server_close ( ) flows . Global . LOGGER . info ( "Server Stops " + ( str ( self . server_address ) ) ) | 12,030 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/WebserverAction.py#L108-L114 | [
"def",
"get_capability_definitions",
"(",
"profile_manager",
")",
":",
"res_type",
"=",
"pbm",
".",
"profile",
".",
"ResourceType",
"(",
"resourceType",
"=",
"pbm",
".",
"profile",
".",
"ResourceTypeEnum",
".",
"STORAGE",
")",
"try",
":",
"cap_categories",
"=",
"profile_manager",
".",
"FetchCapabilityMetadata",
"(",
"res_type",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"cap_definitions",
"=",
"[",
"]",
"for",
"cat",
"in",
"cap_categories",
":",
"cap_definitions",
".",
"extend",
"(",
"cat",
".",
"capabilityMetadata",
")",
"return",
"cap_definitions"
] |
check if scalar_dict satisfy query | def check_scalar ( self , scalar_dict ) : table = { k : np . array ( [ v ] ) for k , v in scalar_dict . items ( ) } return self . mask ( table ) [ 0 ] | 12,031 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/query.py#L28-L33 | [
"def",
"_upload",
"(",
"self",
",",
"obj_name",
",",
"content",
",",
"content_type",
",",
"content_encoding",
",",
"content_length",
",",
"etag",
",",
"chunked",
",",
"chunk_size",
",",
"headers",
")",
":",
"if",
"content_type",
"is",
"not",
"None",
":",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"content_type",
"if",
"content_encoding",
"is",
"not",
"None",
":",
"headers",
"[",
"\"Content-Encoding\"",
"]",
"=",
"content_encoding",
"if",
"isinstance",
"(",
"content",
",",
"six",
".",
"string_types",
")",
":",
"fsize",
"=",
"len",
"(",
"content",
")",
"else",
":",
"if",
"chunked",
":",
"fsize",
"=",
"None",
"elif",
"content_length",
"is",
"None",
":",
"fsize",
"=",
"get_file_size",
"(",
"content",
")",
"else",
":",
"fsize",
"=",
"content_length",
"if",
"fsize",
"is",
"None",
"or",
"fsize",
"<=",
"MAX_FILE_SIZE",
":",
"# We can just upload it as-is.",
"return",
"self",
".",
"_store_object",
"(",
"obj_name",
",",
"content",
"=",
"content",
",",
"etag",
"=",
"etag",
",",
"chunked",
"=",
"chunked",
",",
"chunk_size",
"=",
"chunk_size",
",",
"headers",
"=",
"headers",
")",
"# Files larger than MAX_FILE_SIZE must be segmented",
"# and uploaded separately.",
"num_segments",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"fsize",
")",
"/",
"MAX_FILE_SIZE",
")",
")",
"digits",
"=",
"int",
"(",
"math",
".",
"log10",
"(",
"num_segments",
")",
")",
"+",
"1",
"# NOTE: This could be greatly improved with threading or other",
"# async design.",
"for",
"segment",
"in",
"range",
"(",
"num_segments",
")",
":",
"sequence",
"=",
"str",
"(",
"segment",
"+",
"1",
")",
".",
"zfill",
"(",
"digits",
")",
"seg_name",
"=",
"\"%s.%s\"",
"%",
"(",
"obj_name",
",",
"sequence",
")",
"with",
"utils",
".",
"SelfDeletingTempfile",
"(",
")",
"as",
"tmpname",
":",
"with",
"open",
"(",
"tmpname",
",",
"\"wb\"",
")",
"as",
"tmp",
":",
"tmp",
".",
"write",
"(",
"content",
".",
"read",
"(",
"MAX_FILE_SIZE",
")",
")",
"with",
"open",
"(",
"tmpname",
",",
"\"rb\"",
")",
"as",
"tmp",
":",
"# We have to calculate the etag for each segment",
"etag",
"=",
"utils",
".",
"get_checksum",
"(",
"tmp",
")",
"self",
".",
"_store_object",
"(",
"seg_name",
",",
"content",
"=",
"tmp",
",",
"etag",
"=",
"etag",
",",
"chunked",
"=",
"False",
",",
"headers",
"=",
"headers",
")",
"# Upload the manifest",
"headers",
".",
"pop",
"(",
"\"ETag\"",
",",
"\"\"",
")",
"headers",
"[",
"\"X-Object-Manifest\"",
"]",
"=",
"\"%s/%s.\"",
"%",
"(",
"self",
".",
"name",
",",
"obj_name",
")",
"self",
".",
"_store_object",
"(",
"obj_name",
",",
"content",
"=",
"None",
",",
"headers",
"=",
"headers",
")"
] |
Dump a file through a Spin instance . | def dumpfile ( self , fd ) : self . start ( ) dump = DumpFile ( fd ) self . queue . append ( dump ) | 12,032 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/stdin.py#L62-L69 | [
"def",
"expect_column_pair_values_A_to_be_greater_than_B",
"(",
"self",
",",
"column_A",
",",
"column_B",
",",
"or_equal",
"=",
"None",
",",
"parse_strings_as_datetimes",
"=",
"None",
",",
"allow_cross_type_comparisons",
"=",
"None",
",",
"ignore_row_if",
"=",
"\"both_values_are_missing\"",
",",
"result_format",
"=",
"None",
",",
"include_config",
"=",
"False",
",",
"catch_exceptions",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] |
Run the remote - code - block directive . | 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 ) # Customized for RemoteCodeBlock 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' ) : # if diff is set, set udiff 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 ) # retnode will be note_implicit_target that is linked from caption # and numref. when options['name'] is provided, it should be # primary ID. self . add_name ( retnode ) return [ retnode ] except Exception as exc : return [ document . reporter . warning ( str ( exc ) , line = self . lineno ) ] | 12,033 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/remotecodeblock.py#L75-L124 | [
"def",
"catalogFactory",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"fn",
"=",
"lambda",
"member",
":",
"inspect",
".",
"isclass",
"(",
"member",
")",
"and",
"member",
".",
"__module__",
"==",
"__name__",
"catalogs",
"=",
"odict",
"(",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
",",
"fn",
")",
")",
"if",
"name",
"not",
"in",
"list",
"(",
"catalogs",
".",
"keys",
"(",
")",
")",
":",
"msg",
"=",
"\"%s not found in catalogs:\\n %s\"",
"%",
"(",
"name",
",",
"list",
"(",
"kernels",
".",
"keys",
"(",
")",
")",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"msg",
"=",
"\"Unrecognized catalog: %s\"",
"%",
"name",
"raise",
"Exception",
"(",
"msg",
")",
"return",
"catalogs",
"[",
"name",
"]",
"(",
"*",
"*",
"kwargs",
")"
] |
Read content from the web by overriding LiteralIncludeReader . read_file . | 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 ) | 12,034 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/remotecodeblock.py#L131-L141 | [
"def",
"get_best_match_zone",
"(",
"all_zones",
",",
"domain",
")",
":",
"# Related: https://github.com/Miserlou/Zappa/issues/459",
"public_zones",
"=",
"[",
"zone",
"for",
"zone",
"in",
"all_zones",
"[",
"'HostedZones'",
"]",
"if",
"not",
"zone",
"[",
"'Config'",
"]",
"[",
"'PrivateZone'",
"]",
"]",
"zones",
"=",
"{",
"zone",
"[",
"'Name'",
"]",
"[",
":",
"-",
"1",
"]",
":",
"zone",
"[",
"'Id'",
"]",
"for",
"zone",
"in",
"public_zones",
"if",
"zone",
"[",
"'Name'",
"]",
"[",
":",
"-",
"1",
"]",
"in",
"domain",
"}",
"if",
"zones",
":",
"keys",
"=",
"max",
"(",
"zones",
".",
"keys",
"(",
")",
",",
"key",
"=",
"lambda",
"a",
":",
"len",
"(",
"a",
")",
")",
"# get longest key -- best match.",
"return",
"zones",
"[",
"keys",
"]",
"else",
":",
"return",
"None"
] |
Verify the time | def verify_time ( self , now ) : return now . time ( ) >= self . start_time and now . time ( ) <= self . end_time | 12,035 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L63-L65 | [
"def",
"get",
"(",
"self",
",",
"external_site",
":",
"str",
",",
"external_id",
":",
"int",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"apiurl",
"+",
"\"/mappings\"",
",",
"params",
"=",
"{",
"\"filter[externalSite]\"",
":",
"external_site",
",",
"\"filter[externalId]\"",
":",
"external_id",
"}",
",",
"headers",
"=",
"self",
".",
"header",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"ServerError",
"jsd",
"=",
"r",
".",
"json",
"(",
")",
"if",
"len",
"(",
"jsd",
"[",
"'data'",
"]",
")",
"<",
"1",
":",
"return",
"None",
"r",
"=",
"requests",
".",
"get",
"(",
"jsd",
"[",
"'data'",
"]",
"[",
"0",
"]",
"[",
"'relationships'",
"]",
"[",
"'item'",
"]",
"[",
"'links'",
"]",
"[",
"'related'",
"]",
",",
"headers",
"=",
"self",
".",
"header",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"return",
"jsd",
"else",
":",
"return",
"r",
".",
"json",
"(",
")"
] |
Verify the weekday | def verify_weekday ( self , now ) : return self . weekdays == "*" or str ( now . weekday ( ) ) in self . weekdays . split ( " " ) | 12,036 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L67-L69 | [
"def",
"_psturng",
"(",
"q",
",",
"r",
",",
"v",
")",
":",
"if",
"q",
"<",
"0.",
":",
"raise",
"ValueError",
"(",
"'q should be >= 0'",
")",
"opt_func",
"=",
"lambda",
"p",
",",
"r",
",",
"v",
":",
"abs",
"(",
"_qsturng",
"(",
"p",
",",
"r",
",",
"v",
")",
"-",
"q",
")",
"if",
"v",
"==",
"1",
":",
"if",
"q",
"<",
"_qsturng",
"(",
".9",
",",
"r",
",",
"1",
")",
":",
"return",
".1",
"elif",
"q",
">",
"_qsturng",
"(",
".999",
",",
"r",
",",
"1",
")",
":",
"return",
".001",
"return",
"1.",
"-",
"fminbound",
"(",
"opt_func",
",",
".9",
",",
".999",
",",
"args",
"=",
"(",
"r",
",",
"v",
")",
")",
"else",
":",
"if",
"q",
"<",
"_qsturng",
"(",
".1",
",",
"r",
",",
"v",
")",
":",
"return",
".9",
"elif",
"q",
">",
"_qsturng",
"(",
".999",
",",
"r",
",",
"v",
")",
":",
"return",
".001",
"return",
"1.",
"-",
"fminbound",
"(",
"opt_func",
",",
".1",
",",
".999",
",",
"args",
"=",
"(",
"r",
",",
"v",
")",
")"
] |
Verify the day | def verify_day ( self , now ) : return self . day == "*" or str ( now . day ) in self . day . split ( " " ) | 12,037 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L71-L73 | [
"def",
"robust_data_range",
"(",
"arr",
",",
"robust",
"=",
"False",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"# from the seaborn code ",
"# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201",
"def",
"_get_vmin_vmax",
"(",
"arr2d",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"if",
"vmin",
"is",
"None",
":",
"vmin",
"=",
"np",
".",
"percentile",
"(",
"arr2d",
",",
"2",
")",
"if",
"robust",
"else",
"arr2d",
".",
"min",
"(",
")",
"if",
"vmax",
"is",
"None",
":",
"vmax",
"=",
"np",
".",
"percentile",
"(",
"arr2d",
",",
"98",
")",
"if",
"robust",
"else",
"arr2d",
".",
"max",
"(",
")",
"return",
"vmin",
",",
"vmax",
"if",
"len",
"(",
"arr",
".",
"shape",
")",
"==",
"3",
"and",
"vmin",
"is",
"None",
"and",
"vmax",
"is",
"None",
":",
"vmin",
"=",
"[",
"]",
"vmax",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"arr",
".",
"shape",
"[",
"2",
"]",
")",
":",
"arr_i",
"=",
"arr",
"[",
":",
",",
":",
",",
"i",
"]",
"vmin_i",
",",
"vmax_i",
"=",
"_get_vmin_vmax",
"(",
"arr_i",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
"vmin",
".",
"append",
"(",
"vmin_i",
")",
"vmax",
".",
"append",
"(",
"vmax_i",
")",
"else",
":",
"vmin",
",",
"vmax",
"=",
"_get_vmin_vmax",
"(",
"arr",
",",
"vmin",
"=",
"vmin",
",",
"vmax",
"=",
"vmax",
")",
"return",
"vmin",
",",
"vmax"
] |
Verify the month | def verify_month ( self , now ) : return self . month == "*" or str ( now . month ) in self . month . split ( " " ) | 12,038 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L75-L77 | [
"def",
"robust_data_range",
"(",
"arr",
",",
"robust",
"=",
"False",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"# from the seaborn code ",
"# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201",
"def",
"_get_vmin_vmax",
"(",
"arr2d",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"if",
"vmin",
"is",
"None",
":",
"vmin",
"=",
"np",
".",
"percentile",
"(",
"arr2d",
",",
"2",
")",
"if",
"robust",
"else",
"arr2d",
".",
"min",
"(",
")",
"if",
"vmax",
"is",
"None",
":",
"vmax",
"=",
"np",
".",
"percentile",
"(",
"arr2d",
",",
"98",
")",
"if",
"robust",
"else",
"arr2d",
".",
"max",
"(",
")",
"return",
"vmin",
",",
"vmax",
"if",
"len",
"(",
"arr",
".",
"shape",
")",
"==",
"3",
"and",
"vmin",
"is",
"None",
"and",
"vmax",
"is",
"None",
":",
"vmin",
"=",
"[",
"]",
"vmax",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"arr",
".",
"shape",
"[",
"2",
"]",
")",
":",
"arr_i",
"=",
"arr",
"[",
":",
",",
":",
",",
"i",
"]",
"vmin_i",
",",
"vmax_i",
"=",
"_get_vmin_vmax",
"(",
"arr_i",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
"vmin",
".",
"append",
"(",
"vmin_i",
")",
"vmax",
".",
"append",
"(",
"vmax_i",
")",
"else",
":",
"vmin",
",",
"vmax",
"=",
"_get_vmin_vmax",
"(",
"arr",
",",
"vmin",
"=",
"vmin",
",",
"vmax",
"=",
"vmax",
")",
"return",
"vmin",
",",
"vmax"
] |
A function that will attempt to collapse duplicates in domain space X by aggregating values over the range space Y . | 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 | 12,039 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L19-L94 | [
"def",
"parse_requirements",
"(",
"path",
")",
":",
"requirements",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
",",
"\"rt\"",
")",
"as",
"reqs_f",
":",
"for",
"line",
"in",
"reqs_f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"\"-r\"",
")",
":",
"fname",
"=",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
"inner_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"fname",
")",
"requirements",
"+=",
"parse_requirements",
"(",
"inner_path",
")",
"elif",
"line",
"!=",
"\"\"",
"and",
"not",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"requirements",
".",
"append",
"(",
"line",
")",
"return",
"requirements"
] |
Internally assigns the input data and normalizes it according to the user s specifications | 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" : # This doesn't work with one-dimensional arrays on older # versions of sklearn 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 ) | 12,040 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L168-L198 | [
"async",
"def",
"renew",
"(",
"self",
",",
"session",
",",
"*",
",",
"dc",
"=",
"None",
")",
":",
"session_id",
"=",
"extract_attr",
"(",
"session",
",",
"keys",
"=",
"[",
"\"ID\"",
"]",
")",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"put",
"(",
"\"/v1/session/renew\"",
",",
"session_id",
",",
"params",
"=",
"{",
"\"dc\"",
":",
"dc",
"}",
")",
"try",
":",
"result",
"=",
"response",
".",
"body",
"[",
"0",
"]",
"except",
"IndexError",
":",
"meta",
"=",
"extract_meta",
"(",
"response",
".",
"headers",
")",
"raise",
"NotFound",
"(",
"\"No session for %r\"",
"%",
"session_id",
",",
"meta",
"=",
"meta",
")",
"return",
"consul",
"(",
"result",
",",
"meta",
"=",
"extract_meta",
"(",
"response",
".",
"headers",
")",
")"
] |
Assigns data to this object and builds the requested topological structure | 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 ) ) | 12,041 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L200-L234 | [
"def",
"parse_wrap_facets",
"(",
"facets",
")",
":",
"valid_forms",
"=",
"[",
"'~ var1'",
",",
"'~ var1 + var2'",
"]",
"error_msg",
"=",
"(",
"\"Valid formula for 'facet_wrap' look like\"",
"\" {}\"",
".",
"format",
"(",
"valid_forms",
")",
")",
"if",
"isinstance",
"(",
"facets",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"facets",
"if",
"not",
"isinstance",
"(",
"facets",
",",
"str",
")",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"if",
"'~'",
"in",
"facets",
":",
"variables_pattern",
"=",
"r'(\\w+(?:\\s*\\+\\s*\\w+)*|\\.)'",
"pattern",
"=",
"r'\\s*~\\s*{0}\\s*'",
".",
"format",
"(",
"variables_pattern",
")",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"facets",
")",
"if",
"not",
"match",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"facets",
"=",
"[",
"var",
".",
"strip",
"(",
")",
"for",
"var",
"in",
"match",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"'+'",
")",
"]",
"elif",
"re",
".",
"match",
"(",
"r'\\w+'",
",",
"facets",
")",
":",
"# allow plain string as the variable name",
"facets",
"=",
"[",
"facets",
"]",
"else",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"return",
"facets"
] |
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 | 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 ) | 12,042 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L236-L250 | [
"def",
"delete_server_cert",
"(",
"cert_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"try",
":",
"return",
"conn",
".",
"delete_server_cert",
"(",
"cert_name",
")",
"except",
"boto",
".",
"exception",
".",
"BotoServerError",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"e",
")",
"log",
".",
"error",
"(",
"'Failed to delete certificate %s.'",
",",
"cert_name",
")",
"return",
"False"
] |
Returns the normalized input data requested by the user | 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 ] | 12,043 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L252-L272 | [
"def",
"destroy",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Destroying page: %s\"",
"%",
"self",
")",
"if",
"self",
".",
"doc",
".",
"nb_pages",
"<=",
"1",
":",
"self",
".",
"doc",
".",
"destroy",
"(",
")",
"return",
"doc_pages",
"=",
"self",
".",
"doc",
".",
"pages",
"[",
":",
"]",
"current_doc_nb_pages",
"=",
"self",
".",
"doc",
".",
"nb_pages",
"paths",
"=",
"[",
"self",
".",
"__get_box_path",
"(",
")",
",",
"self",
".",
"__get_img_path",
"(",
")",
",",
"self",
".",
"_get_thumb_path",
"(",
")",
",",
"]",
"for",
"path",
"in",
"paths",
":",
"if",
"self",
".",
"fs",
".",
"exists",
"(",
"path",
")",
":",
"self",
".",
"fs",
".",
"unlink",
"(",
"path",
")",
"for",
"page_nb",
"in",
"range",
"(",
"self",
".",
"page_nb",
"+",
"1",
",",
"current_doc_nb_pages",
")",
":",
"page",
"=",
"doc_pages",
"[",
"page_nb",
"]",
"page",
".",
"change_index",
"(",
"offset",
"=",
"-",
"1",
")"
] |
Returns the input data requested by the user | 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 ] | 12,044 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L274-L295 | [
"def",
"create_temporary_ca_path",
"(",
"anchor_list",
",",
"folder",
")",
":",
"# We should probably avoid writing duplicate anchors and also",
"# check if they are all certs.",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"folder",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"except",
":",
"return",
"None",
"l",
"=",
"len",
"(",
"anchor_list",
")",
"if",
"l",
"==",
"0",
":",
"return",
"None",
"fmtstr",
"=",
"\"%%0%sd.pem\"",
"%",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"l",
",",
"10",
")",
")",
"i",
"=",
"0",
"try",
":",
"for",
"a",
"in",
"anchor_list",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"fmtstr",
"%",
"i",
")",
"f",
"=",
"open",
"(",
"fname",
",",
"\"w\"",
")",
"s",
"=",
"a",
".",
"output",
"(",
"fmt",
"=",
"\"PEM\"",
")",
"f",
".",
"write",
"(",
"s",
")",
"f",
".",
"close",
"(",
")",
"i",
"+=",
"1",
"except",
":",
"return",
"None",
"r",
",",
"w",
",",
"e",
"=",
"popen3",
"(",
"[",
"\"c_rehash\"",
",",
"folder",
"]",
")",
"r",
".",
"close",
"(",
")",
"w",
".",
"close",
"(",
")",
"e",
".",
"close",
"(",
")",
"return",
"l"
] |
Returns the output data requested by the user | 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 ] | 12,045 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L297-L313 | [
"def",
"arcball_constrain_to_axis",
"(",
"point",
",",
"axis",
")",
":",
"v",
"=",
"np",
".",
"array",
"(",
"point",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"a",
"=",
"np",
".",
"array",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"v",
"-=",
"a",
"*",
"np",
".",
"dot",
"(",
"a",
",",
"v",
")",
"# on plane",
"n",
"=",
"vector_norm",
"(",
"v",
")",
"if",
"n",
">",
"_EPS",
":",
"if",
"v",
"[",
"2",
"]",
"<",
"0.0",
":",
"np",
".",
"negative",
"(",
"v",
",",
"v",
")",
"v",
"/=",
"n",
"return",
"v",
"if",
"a",
"[",
"2",
"]",
"==",
"1.0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"0.0",
",",
"0.0",
"]",
")",
"return",
"unit_vector",
"(",
"[",
"-",
"a",
"[",
"1",
"]",
",",
"a",
"[",
"0",
"]",
",",
"0.0",
"]",
")"
] |
Returns the weights requested by the user | 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 ] | 12,046 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L315-L330 | [
"def",
"_titancna_summary",
"(",
"call",
",",
"data",
")",
":",
"out",
"=",
"{",
"}",
"for",
"svtype",
",",
"coords",
"in",
"get_coords",
"(",
"data",
")",
":",
"cur_calls",
"=",
"{",
"k",
":",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"k",
"in",
"coords",
".",
"keys",
"(",
")",
"}",
"with",
"open",
"(",
"call",
"[",
"\"subclones\"",
"]",
")",
"as",
"in_handle",
":",
"header",
"=",
"in_handle",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"for",
"line",
"in",
"in_handle",
":",
"val",
"=",
"dict",
"(",
"zip",
"(",
"header",
",",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"start",
"=",
"int",
"(",
"val",
"[",
"\"Start_Position.bp.\"",
"]",
")",
"end",
"=",
"int",
"(",
"val",
"[",
"\"End_Position.bp.\"",
"]",
")",
"for",
"region",
",",
"cur_coords",
"in",
"coords",
".",
"items",
"(",
")",
":",
"if",
"val",
"[",
"\"Chromosome\"",
"]",
"==",
"cur_coords",
"[",
"0",
"]",
"and",
"are_overlapping",
"(",
"(",
"start",
",",
"end",
")",
",",
"cur_coords",
"[",
"1",
":",
"]",
")",
":",
"cur_calls",
"[",
"region",
"]",
"[",
"_check_copy_number_changes",
"(",
"svtype",
",",
"_to_cn",
"(",
"val",
"[",
"\"Copy_Number\"",
"]",
")",
",",
"_to_cn",
"(",
"val",
"[",
"\"MinorCN\"",
"]",
")",
",",
"data",
")",
"]",
"+=",
"1",
"out",
"[",
"svtype",
"]",
"=",
"{",
"r",
":",
"_merge_cn_calls",
"(",
"c",
",",
"svtype",
")",
"for",
"r",
",",
"c",
"in",
"cur_calls",
".",
"items",
"(",
")",
"}",
"with",
"open",
"(",
"call",
"[",
"\"hetsummary\"",
"]",
")",
"as",
"in_handle",
":",
"vals",
"=",
"dict",
"(",
"zip",
"(",
"in_handle",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
",",
"in_handle",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
")",
")",
"out",
"[",
"\"purity\"",
"]",
"=",
"vals",
"[",
"\"purity\"",
"]",
"out",
"[",
"\"ploidy\"",
"]",
"=",
"vals",
"[",
"\"ploidy\"",
"]",
"return",
"out"
] |
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 | 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 ) ) # unique_ys = len(np.unique(self.Y, axis=0)) # if len(self.Y) != unique_ys: # warnings.warn('Range space has duplicates. Simulation of ' # 'simplicity may help, but artificial noise may ' # 'occur in flat regions of the domain. Sample size:' # '{} vs. Unique Records: {}'.format(len(self.Y), # unique_ys)) 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 ) ) | 12,047 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L353-L392 | [
"def",
"reset_flags",
"(",
"self",
")",
":",
"self",
".",
"C",
"=",
"None",
"self",
".",
"Z",
"=",
"None",
"self",
".",
"P",
"=",
"None",
"self",
".",
"S",
"=",
"None"
] |
Perform column - stacking on a list of 2d data blocks . | def column_stack_2d ( data ) : return list ( list ( itt . chain . from_iterable ( _ ) ) for _ in zip ( * data ) ) | 12,048 | https://github.com/bskinn/pent/blob/7a81e55f46bc3aed3f09d96449d59a770b4730c2/pent/utils.py#L30-L32 | [
"def",
"user_agent",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"UserAgent",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] |
Discover the directory containing the conf . py file . | def discover_conf_py_directory ( initial_dir ) : # Create an absolute Path to work with initial_dir = pathlib . Path ( initial_dir ) . resolve ( ) # Search upwards until a conf.py is found try : return str ( _search_parents ( initial_dir ) ) except FileNotFoundError : raise | 12,049 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/rootdiscovery.py#L51-L81 | [
"def",
"output_keys",
"(",
"self",
",",
"source_keys",
")",
":",
"keys",
"=",
"list",
"(",
"source_keys",
")",
"# Remove the aggregated axis from the keys.",
"del",
"keys",
"[",
"self",
".",
"axis",
"]",
"return",
"tuple",
"(",
"keys",
")"
] |
Search the initial and parent directories for a conf . py Sphinx configuration file that represents the root of a Sphinx project . | 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 ) | 12,050 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/rootdiscovery.py#L91-L118 | [
"def",
"_check_timestamp",
"(",
"self",
",",
"timestamp",
")",
":",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"now",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"lapsed",
"=",
"now",
"-",
"timestamp",
"if",
"lapsed",
">",
"self",
".",
"timestamp_threshold",
":",
"raise",
"Error",
"(",
"'Expired timestamp: given %d and now %s has a '",
"'greater difference than threshold %d'",
"%",
"(",
"timestamp",
",",
"now",
",",
"self",
".",
"timestamp_threshold",
")",
")"
] |
Requests a WebSocket session for the Real - Time Messaging API . Returns a SessionMetadata object containing the information retrieved from the API call . | 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 ) | 12,051 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L208-L221 | [
"def",
"set_tax_benefit_systems",
"(",
"self",
",",
"tax_benefit_system",
"=",
"None",
",",
"baseline_tax_benefit_system",
"=",
"None",
")",
":",
"assert",
"tax_benefit_system",
"is",
"not",
"None",
"self",
".",
"tax_benefit_system",
"=",
"tax_benefit_system",
"if",
"self",
".",
"cache_blacklist",
"is",
"not",
"None",
":",
"self",
".",
"tax_benefit_system",
".",
"cache_blacklist",
"=",
"self",
".",
"cache_blacklist",
"if",
"baseline_tax_benefit_system",
"is",
"not",
"None",
":",
"self",
".",
"baseline_tax_benefit_system",
"=",
"baseline_tax_benefit_system",
"if",
"self",
".",
"cache_blacklist",
"is",
"not",
"None",
":",
"self",
".",
"baseline_tax_benefit_system",
".",
"cache_blacklist",
"=",
"self",
".",
"cache_blacklist"
] |
Finds a resource by key first case insensitive match . | 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 | 12,052 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L61-L75 | [
"def",
"dnd_endSnooze",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"self",
".",
"_validate_xoxp_token",
"(",
")",
"return",
"self",
".",
"api_call",
"(",
"\"dnd.endSnooze\"",
",",
"json",
"=",
"kwargs",
")"
] |
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 . | 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 : # IM does not exist, create it? if auto_create : response = self . api . im . open ( token = self . token , user = uid ) return response [ u'channel' ] [ u'id' ] else : raise | 12,053 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L92-L106 | [
"def",
"write_backup_state_to_json_file",
"(",
"self",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"state_file_path",
"=",
"self",
".",
"config",
"[",
"\"json_state_file_path\"",
"]",
"self",
".",
"state",
"[",
"\"walreceivers\"",
"]",
"=",
"{",
"key",
":",
"{",
"\"latest_activity\"",
":",
"value",
".",
"latest_activity",
",",
"\"running\"",
":",
"value",
".",
"running",
",",
"\"last_flushed_lsn\"",
":",
"value",
".",
"last_flushed_lsn",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"walreceivers",
".",
"items",
"(",
")",
"}",
"self",
".",
"state",
"[",
"\"pg_receivexlogs\"",
"]",
"=",
"{",
"key",
":",
"{",
"\"latest_activity\"",
":",
"value",
".",
"latest_activity",
",",
"\"running\"",
":",
"value",
".",
"running",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"receivexlogs",
".",
"items",
"(",
")",
"}",
"self",
".",
"state",
"[",
"\"pg_basebackups\"",
"]",
"=",
"{",
"key",
":",
"{",
"\"latest_activity\"",
":",
"value",
".",
"latest_activity",
",",
"\"running\"",
":",
"value",
".",
"running",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"basebackups",
".",
"items",
"(",
")",
"}",
"self",
".",
"state",
"[",
"\"compressors\"",
"]",
"=",
"[",
"compressor",
".",
"state",
"for",
"compressor",
"in",
"self",
".",
"compressors",
"]",
"self",
".",
"state",
"[",
"\"transfer_agents\"",
"]",
"=",
"[",
"ta",
".",
"state",
"for",
"ta",
"in",
"self",
".",
"transfer_agents",
"]",
"self",
".",
"state",
"[",
"\"queues\"",
"]",
"=",
"{",
"\"compression_queue\"",
":",
"self",
".",
"compression_queue",
".",
"qsize",
"(",
")",
",",
"\"transfer_queue\"",
":",
"self",
".",
"transfer_queue",
".",
"qsize",
"(",
")",
",",
"}",
"self",
".",
"log",
".",
"debug",
"(",
"\"Writing JSON state file to %r\"",
",",
"state_file_path",
")",
"write_json_file",
"(",
"state_file_path",
",",
"self",
".",
"state",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"Wrote JSON state file to disk, took %.4fs\"",
",",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")"
] |
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 . | def update ( self , event ) : # Create our own copy of the event data, as we'll be pushing that to # another data structure and we don't want it mangled by user code later # on. event = event . copy ( ) # Now just defer the work to later. reactor . callInThread ( self . _update_deferred , event ) | 12,054 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L108-L125 | [
"def",
"get_stores_secrets_volumes",
"(",
"cls",
",",
"stores_secrets",
")",
":",
"volumes",
"=",
"[",
"]",
"volume_mounts",
"=",
"[",
"]",
"for",
"store_secret",
"in",
"stores_secrets",
":",
"store",
"=",
"store_secret",
"[",
"'store'",
"]",
"if",
"store",
"in",
"{",
"GCS",
",",
"S3",
"}",
":",
"secrets_volumes",
",",
"secrets_volume_mounts",
"=",
"get_volume_from_secret",
"(",
"volume_name",
"=",
"cls",
".",
"STORE_SECRET_VOLUME_NAME",
".",
"format",
"(",
"store",
")",
",",
"mount_path",
"=",
"cls",
".",
"STORE_SECRET_KEY_MOUNT_PATH",
".",
"format",
"(",
"store",
")",
",",
"secret_name",
"=",
"store_secret",
"[",
"'persistence_secret'",
"]",
",",
")",
"volumes",
"+=",
"secrets_volumes",
"volume_mounts",
"+=",
"secrets_volume_mounts",
"return",
"volumes",
",",
"volume_mounts"
] |
Yield series dictionaries with values resolved to the final excel formulas . | 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 | 12,055 | https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/chart.py#L85-L94 | [
"def",
"communityvisibilitystate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_communityvisibilitystate",
"==",
"None",
":",
"return",
"None",
"elif",
"self",
".",
"_communityvisibilitystate",
"in",
"self",
".",
"VisibilityState",
":",
"return",
"self",
".",
"VisibilityState",
"[",
"self",
".",
"_communityvisibilitystate",
"]",
"else",
":",
"#Invalid State",
"return",
"None"
] |
Method to get current user s name mobile email and position . | 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 | 12,056 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L30-L34 | [
"def",
"hide",
"(",
"self",
",",
"selections",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'atoms'",
"]",
"=",
"selections",
"[",
"'atoms'",
"]",
"self",
".",
"on_atom_hidden_changed",
"(",
")",
"if",
"'bonds'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'bonds'",
"]",
"=",
"selections",
"[",
"'bonds'",
"]",
"self",
".",
"on_bond_hidden_changed",
"(",
")",
"if",
"'box'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'box'",
"]",
"=",
"box_s",
"=",
"selections",
"[",
"'box'",
"]",
"if",
"box_s",
".",
"mask",
"[",
"0",
"]",
":",
"if",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"remove_renderer",
"(",
"self",
".",
"box_renderer",
")",
"else",
":",
"if",
"not",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"add_renderer",
"(",
"self",
".",
"box_renderer",
")",
"return",
"self",
".",
"hidden_state"
] |
Method to get the administrator id list . | 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 | 12,057 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L54-L58 | [
"def",
"Open",
"(",
"self",
",",
"file_object",
")",
":",
"file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"signature_data",
"=",
"file_object",
".",
"read",
"(",
"6",
")",
"self",
".",
"file_format",
"=",
"None",
"if",
"len",
"(",
"signature_data",
")",
">",
"2",
":",
"if",
"signature_data",
"[",
":",
"2",
"]",
"==",
"self",
".",
"_CPIO_SIGNATURE_BINARY_BIG_ENDIAN",
":",
"self",
".",
"file_format",
"=",
"'bin-big-endian'",
"elif",
"signature_data",
"[",
":",
"2",
"]",
"==",
"self",
".",
"_CPIO_SIGNATURE_BINARY_LITTLE_ENDIAN",
":",
"self",
".",
"file_format",
"=",
"'bin-little-endian'",
"elif",
"signature_data",
"==",
"self",
".",
"_CPIO_SIGNATURE_PORTABLE_ASCII",
":",
"self",
".",
"file_format",
"=",
"'odc'",
"elif",
"signature_data",
"==",
"self",
".",
"_CPIO_SIGNATURE_NEW_ASCII",
":",
"self",
".",
"file_format",
"=",
"'newc'",
"elif",
"signature_data",
"==",
"self",
".",
"_CPIO_SIGNATURE_NEW_ASCII_WITH_CHECKSUM",
":",
"self",
".",
"file_format",
"=",
"'crc'",
"if",
"self",
".",
"file_format",
"is",
"None",
":",
"raise",
"IOError",
"(",
"'Unsupported CPIO format.'",
")",
"self",
".",
"_file_object",
"=",
"file_object",
"self",
".",
"_file_size",
"=",
"file_object",
".",
"get_size",
"(",
")",
"self",
".",
"_ReadFileEntries",
"(",
"self",
".",
"_file_object",
")"
] |
Run program with args | 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 ) # nosec 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 ) | 12,058 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/program.py#L100-L143 | [
"def",
"_get_max_page",
"(",
"self",
",",
"url",
")",
":",
"html",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"text",
"pq",
"=",
"PyQuery",
"(",
"html",
")",
"try",
":",
"tds",
"=",
"int",
"(",
"pq",
"(",
"\"h2\"",
")",
".",
"text",
"(",
")",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
")",
"if",
"tds",
"%",
"25",
":",
"return",
"tds",
"/",
"25",
"+",
"1",
"return",
"tds",
"/",
"25",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"No results found!\"",
")"
] |
Method to get the department name | def get_dept_name ( self ) : self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) ) return self . json_response . get ( "name" , None ) | 12,059 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L22-L25 | [
"def",
"get_traindata",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"traindata",
"=",
"None",
"for",
"key",
",",
"value",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"'__header__'",
",",
"'__version__'",
",",
"'__globals__'",
"]",
":",
"if",
"traindata",
"is",
"None",
":",
"traindata",
"=",
"value",
"[",
"np",
".",
"where",
"(",
"value",
"[",
":",
",",
"4",
"]",
"!=",
"0",
")",
"]",
"else",
":",
"traindata",
"=",
"np",
".",
"concatenate",
"(",
"(",
"traindata",
",",
"value",
"[",
"np",
".",
"where",
"(",
"value",
"[",
":",
",",
"4",
"]",
"!=",
"0",
")",
"]",
")",
")",
"return",
"traindata"
] |
Method to get the id list of department manager . | 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 ) | 12,060 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L27-L30 | [
"def",
"StoreCSRFCookie",
"(",
"user",
",",
"response",
")",
":",
"csrf_token",
"=",
"GenerateCSRFToken",
"(",
"user",
",",
"None",
")",
"response",
".",
"set_cookie",
"(",
"\"csrftoken\"",
",",
"csrf_token",
",",
"max_age",
"=",
"CSRF_TOKEN_DURATION",
".",
"seconds",
")"
] |
Method to get department by name . | 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 ] | 12,061 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L52-L61 | [
"def",
"get_traindata",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"traindata",
"=",
"None",
"for",
"key",
",",
"value",
"in",
"self",
".",
"data",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"'__header__'",
",",
"'__version__'",
",",
"'__globals__'",
"]",
":",
"if",
"traindata",
"is",
"None",
":",
"traindata",
"=",
"value",
"[",
"np",
".",
"where",
"(",
"value",
"[",
":",
",",
"4",
"]",
"!=",
"0",
")",
"]",
"else",
":",
"traindata",
"=",
"np",
".",
"concatenate",
"(",
"(",
"traindata",
",",
"value",
"[",
"np",
".",
"where",
"(",
"value",
"[",
":",
",",
"4",
"]",
"!=",
"0",
")",
"]",
")",
")",
"return",
"traindata"
] |
Wrapper for the setup functions of each individual extension module . | 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 : # package is not installed __version__ = 'unknown' return { 'version' : __version__ , 'parallel_read_safe' : True , 'parallel_write_safe' : True } | 12,062 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/__init__.py#L25-L41 | [
"def",
"getRenderModelThumbnailURL",
"(",
"self",
",",
"pchRenderModelName",
",",
"pchThumbnailURL",
",",
"unThumbnailURLLen",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getRenderModelThumbnailURL",
"peError",
"=",
"EVRRenderModelError",
"(",
")",
"result",
"=",
"fn",
"(",
"pchRenderModelName",
",",
"pchThumbnailURL",
",",
"unThumbnailURLLen",
",",
"byref",
"(",
"peError",
")",
")",
"return",
"result",
",",
"peError"
] |
Process a role that references the target nodes created by the lsst - task directive . | def task_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : # app = inliner.document.settings.env.app node = pending_task_xref ( rawsource = text ) return [ node ] , [ ] | 12,063 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L89-L120 | [
"def",
"event_availability_array",
"(",
"events",
")",
":",
"array",
"=",
"np",
".",
"ones",
"(",
"(",
"len",
"(",
"events",
")",
",",
"len",
"(",
"events",
")",
")",
")",
"for",
"row",
",",
"event",
"in",
"enumerate",
"(",
"events",
")",
":",
"for",
"col",
",",
"other_event",
"in",
"enumerate",
"(",
"events",
")",
":",
"if",
"row",
"!=",
"col",
":",
"tags",
"=",
"set",
"(",
"event",
".",
"tags",
")",
"events_share_tag",
"=",
"len",
"(",
"tags",
".",
"intersection",
"(",
"other_event",
".",
"tags",
")",
")",
">",
"0",
"if",
"(",
"other_event",
"in",
"event",
".",
"unavailability",
")",
"or",
"events_share_tag",
":",
"array",
"[",
"row",
",",
"col",
"]",
"=",
"0",
"array",
"[",
"col",
",",
"row",
"]",
"=",
"0",
"return",
"array"
] |
Process the pending_task_xref nodes during the doctree - resolved event to insert links to the locations of lsst - task - topic directives . | 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 = [ ] # The source of the node is the class name the user entered via the # lsst-task-topic role. For example: # lsst.pipe.tasks.processCcd.ProcessCcdTask role_parts = split_role_content ( node . rawsource ) task_id = format_task_id ( role_parts [ 'ref' ] ) if role_parts [ 'display' ] : # user's custom display text display_text = role_parts [ 'display' ] elif role_parts [ 'last_component' ] : # just the name of the class 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 : # A task topic, marked up with the lsst-task-topic directive is # available 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 : # Fallback if the task topic isn't known. Just print the label text content . append ( link_label ) message = 'lsst-task could not find a reference to %s' logger . warning ( message , role_parts [ 'ref' ] , location = node ) # replacing the pending_task_xref node with this reference node . replace_self ( content ) | 12,064 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L123-L173 | [
"def",
"group_values",
"(",
"self",
",",
"group_name",
")",
":",
"group_index",
"=",
"self",
".",
"groups",
".",
"index",
"(",
"group_name",
")",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"data_keys",
":",
"if",
"key",
"[",
"group_index",
"]",
"not",
"in",
"values",
":",
"values",
".",
"append",
"(",
"key",
"[",
"group_index",
"]",
")",
"return",
"values"
] |
Process a role that references the target nodes created by the lsst - config - topic directive . | def config_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : node = pending_config_xref ( rawsource = text ) return [ node ] , [ ] | 12,065 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L176-L212 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_socket",
"is",
"not",
"None",
"and",
"self",
".",
"_conn",
"is",
"not",
"None",
":",
"message_input",
"=",
"UnityMessage",
"(",
")",
"message_input",
".",
"header",
".",
"status",
"=",
"400",
"self",
".",
"_communicator_send",
"(",
"message_input",
".",
"SerializeToString",
"(",
")",
")",
"if",
"self",
".",
"_socket",
"is",
"not",
"None",
":",
"self",
".",
"_socket",
".",
"close",
"(",
")",
"self",
".",
"_socket",
"=",
"None",
"if",
"self",
".",
"_socket",
"is",
"not",
"None",
":",
"self",
".",
"_conn",
".",
"close",
"(",
")",
"self",
".",
"_conn",
"=",
"None"
] |
Process the pending_config_xref nodes during the doctree - resolved event to insert links to the locations of lsst - config - topic directives . | 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 = [ ] # The source of the node is the content the authored entered in the # lsst-config role role_parts = split_role_content ( node . rawsource ) config_id = format_config_id ( role_parts [ 'ref' ] ) if role_parts [ 'display' ] : # user's custom display text display_text = role_parts [ 'display' ] elif role_parts [ 'last_component' ] : # just the name of the class 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 : # A config topic, marked up with the lsst-task directive is # available 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 : # Fallback if the config topic isn't known. Just print the # role's formatted content. content . append ( link_label ) message = 'lsst-config could not find a reference to %s' logger . warning ( message , role_parts [ 'ref' ] , location = node ) # replacing the pending_config_xref node with this reference node . replace_self ( content ) | 12,066 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L215-L271 | [
"def",
"group_values",
"(",
"self",
",",
"group_name",
")",
":",
"group_index",
"=",
"self",
".",
"groups",
".",
"index",
"(",
"group_name",
")",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"data_keys",
":",
"if",
"key",
"[",
"group_index",
"]",
"not",
"in",
"values",
":",
"values",
".",
"append",
"(",
"key",
"[",
"group_index",
"]",
")",
"return",
"values"
] |
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 . | def configfield_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) : node = pending_configfield_xref ( rawsource = text ) return [ node ] , [ ] | 12,067 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L274-L311 | [
"def",
"unshare",
"(",
"flags",
")",
":",
"res",
"=",
"lib",
".",
"unshare",
"(",
"flags",
")",
"if",
"res",
"!=",
"0",
":",
"_check_error",
"(",
"ffi",
".",
"errno",
")"
] |
Process the pending_configfield_xref nodes during the doctree - resolved event to insert links to the locations of configuration field nodes . | 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 = [ ] # The source is the text the user entered into the role, which is # the importable name of the config class's and the attribute 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' ] : # user's custom display text display_text = role_parts [ 'display' ] elif role_parts [ 'last_component' ] : # just the name of the class 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 : # A config field topic is available 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 : # Fallback if the config field isn't known. Just print the Config # field attribute name 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 ) # replacing the pending_configfield_xref node with this reference node . replace_self ( content ) | 12,068 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L314-L377 | [
"def",
"removeAllEntitlements",
"(",
"self",
",",
"appId",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appId\"",
":",
"appId",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/licenses/removeAllEntitlements\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Convert value to bytes accepts notations such as 4k to mean 4096 bytes | 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" : # Accept notations such as "1mb", as they get used out of habit 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 | 12,069 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L372-L404 | [
"def",
"context_completion_checker",
"(",
"async",
")",
":",
"store_async_marker",
"(",
"async",
".",
"id",
",",
"async",
".",
"result",
".",
"status",
"if",
"async",
".",
"result",
"else",
"-",
"1",
")",
"logging",
".",
"debug",
"(",
"\"Async check completion for: %s\"",
",",
"async",
".",
"context_id",
")",
"current_queue",
"=",
"_get_current_queue",
"(",
")",
"from",
"furious",
".",
"async",
"import",
"Async",
"logging",
".",
"debug",
"(",
"\"Completion Check queue:%s\"",
",",
"current_queue",
")",
"Async",
"(",
"_completion_checker",
",",
"queue",
"=",
"current_queue",
",",
"args",
"=",
"(",
"async",
".",
"id",
",",
"async",
".",
"context_id",
")",
")",
".",
"start",
"(",
")",
"return",
"True"
] |
Cast value to numeric result_type if possible | 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 | 12,070 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L451-L468 | [
"def",
"cfg",
"(",
"self",
")",
":",
"config",
"=",
"LStruct",
"(",
"self",
".",
"defaults",
")",
"module",
"=",
"config",
"[",
"'CONFIG'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"CONFIGURATION_ENVIRON_VARIABLE",
",",
"config",
"[",
"'CONFIG'",
"]",
")",
"if",
"module",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"module",
")",
"config",
".",
"update",
"(",
"{",
"name",
":",
"getattr",
"(",
"module",
",",
"name",
")",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
"if",
"name",
"==",
"name",
".",
"upper",
"(",
")",
"and",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"}",
")",
"except",
"ImportError",
"as",
"exc",
":",
"config",
".",
"CONFIG",
"=",
"None",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error importing %s: %s\"",
",",
"module",
",",
"exc",
")",
"# Patch configuration from ENV",
"for",
"name",
"in",
"config",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"name",
"!=",
"name",
".",
"upper",
"(",
")",
"or",
"name",
"not",
"in",
"os",
".",
"environ",
":",
"continue",
"try",
":",
"config",
"[",
"name",
"]",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
"[",
"name",
"]",
")",
"except",
"ValueError",
":",
"pass",
"return",
"config"
] |
Replace current providers with given ones | def set_providers ( self , * providers ) : if self . providers : self . clear ( ) for provider in providers : self . add ( provider ) | 12,071 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L62-L67 | [
"def",
"console_set_custom_font",
"(",
"fontFile",
":",
"AnyStr",
",",
"flags",
":",
"int",
"=",
"FONT_LAYOUT_ASCII_INCOL",
",",
"nb_char_horiz",
":",
"int",
"=",
"0",
",",
"nb_char_vertic",
":",
"int",
"=",
"0",
",",
")",
"->",
"None",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fontFile",
")",
":",
"raise",
"RuntimeError",
"(",
"\"File not found:\\n\\t%s\"",
"%",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"fontFile",
")",
",",
")",
")",
"lib",
".",
"TCOD_console_set_custom_font",
"(",
"_bytes",
"(",
"fontFile",
")",
",",
"flags",
",",
"nb_char_horiz",
",",
"nb_char_vertic",
")"
] |
Size in bytes expressed by value configured under key | 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 ) ) | 12,072 | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L196-L213 | [
"def",
"make_random_models_table",
"(",
"n_sources",
",",
"param_ranges",
",",
"random_state",
"=",
"None",
")",
":",
"prng",
"=",
"check_random_state",
"(",
"random_state",
")",
"sources",
"=",
"Table",
"(",
")",
"for",
"param_name",
",",
"(",
"lower",
",",
"upper",
")",
"in",
"param_ranges",
".",
"items",
"(",
")",
":",
"# Generate a column for every item in param_ranges, even if it",
"# is not in the model (e.g. flux). However, such columns will",
"# be ignored when rendering the image.",
"sources",
"[",
"param_name",
"]",
"=",
"prng",
".",
"uniform",
"(",
"lower",
",",
"upper",
",",
"n_sources",
")",
"return",
"sources"
] |
Call this to install StatsD for the Tornado application . | 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 | 12,073 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L202-L234 | [
"def",
"generic_filename",
"(",
"path",
")",
":",
"for",
"sep",
"in",
"common_path_separators",
":",
"if",
"sep",
"in",
"path",
":",
"_",
",",
"path",
"=",
"path",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"return",
"path"
] |
Record a timing . | def record_timing ( self , duration , * path ) : self . application . statsd . send ( path , duration * 1000.0 , 'ms' ) | 12,074 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L19-L32 | [
"def",
"delete_snl",
"(",
"self",
",",
"snl_ids",
")",
":",
"try",
":",
"payload",
"=",
"{",
"\"ids\"",
":",
"json",
".",
"dumps",
"(",
"snl_ids",
")",
"}",
"response",
"=",
"self",
".",
"session",
".",
"post",
"(",
"\"{}/snl/delete\"",
".",
"format",
"(",
"self",
".",
"preamble",
")",
",",
"data",
"=",
"payload",
")",
"if",
"response",
".",
"status_code",
"in",
"[",
"200",
",",
"400",
"]",
":",
"resp",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"text",
",",
"cls",
"=",
"MontyDecoder",
")",
"if",
"resp",
"[",
"\"valid_response\"",
"]",
":",
"if",
"resp",
".",
"get",
"(",
"\"warning\"",
")",
":",
"warnings",
".",
"warn",
"(",
"resp",
"[",
"\"warning\"",
"]",
")",
"return",
"resp",
"else",
":",
"raise",
"MPRestError",
"(",
"resp",
"[",
"\"error\"",
"]",
")",
"raise",
"MPRestError",
"(",
"\"REST error with status code {} and error {}\"",
".",
"format",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"text",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"MPRestError",
"(",
"str",
"(",
"ex",
")",
")"
] |
Increase a counter . | def increase_counter ( self , * path , * * kwargs ) : self . application . statsd . send ( path , kwargs . get ( 'amount' , '1' ) , 'c' ) | 12,075 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L34-L48 | [
"def",
"union",
"(",
"self",
",",
"*",
"dstreams",
")",
":",
"if",
"not",
"dstreams",
":",
"raise",
"ValueError",
"(",
"\"should have at least one DStream to union\"",
")",
"if",
"len",
"(",
"dstreams",
")",
"==",
"1",
":",
"return",
"dstreams",
"[",
"0",
"]",
"if",
"len",
"(",
"set",
"(",
"s",
".",
"_jrdd_deserializer",
"for",
"s",
"in",
"dstreams",
")",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All DStreams should have same serializer\"",
")",
"if",
"len",
"(",
"set",
"(",
"s",
".",
"_slideDuration",
"for",
"s",
"in",
"dstreams",
")",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All DStreams should have same slide duration\"",
")",
"cls",
"=",
"SparkContext",
".",
"_jvm",
".",
"org",
".",
"apache",
".",
"spark",
".",
"streaming",
".",
"api",
".",
"java",
".",
"JavaDStream",
"jdstreams",
"=",
"SparkContext",
".",
"_gateway",
".",
"new_array",
"(",
"cls",
",",
"len",
"(",
"dstreams",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"dstreams",
")",
")",
":",
"jdstreams",
"[",
"i",
"]",
"=",
"dstreams",
"[",
"i",
"]",
".",
"_jdstream",
"return",
"DStream",
"(",
"self",
".",
"_jssc",
".",
"union",
"(",
"jdstreams",
")",
",",
"self",
",",
"dstreams",
"[",
"0",
"]",
".",
"_jrdd_deserializer",
")"
] |
Record the time it takes to perform an arbitrary code block . | def execution_timer ( self , * path ) : start = time . time ( ) try : yield finally : self . record_timing ( max ( start , time . time ( ) ) - start , * path ) | 12,076 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L51-L66 | [
"def",
"delete_classifier",
"(",
"self",
",",
"classifier_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"classifier_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'classifier_id must be provided'",
")",
"headers",
"=",
"{",
"}",
"if",
"'headers'",
"in",
"kwargs",
":",
"headers",
".",
"update",
"(",
"kwargs",
".",
"get",
"(",
"'headers'",
")",
")",
"sdk_headers",
"=",
"get_sdk_headers",
"(",
"'watson_vision_combined'",
",",
"'V3'",
",",
"'delete_classifier'",
")",
"headers",
".",
"update",
"(",
"sdk_headers",
")",
"params",
"=",
"{",
"'version'",
":",
"self",
".",
"version",
"}",
"url",
"=",
"'/v3/classifiers/{0}'",
".",
"format",
"(",
"*",
"self",
".",
"_encode_path_vars",
"(",
"classifier_id",
")",
")",
"response",
"=",
"self",
".",
"request",
"(",
"method",
"=",
"'DELETE'",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"headers",
",",
"params",
"=",
"params",
",",
"accept_json",
"=",
"True",
")",
"return",
"response"
] |
Records the time taken to process the request . | def on_finish ( self ) : super ( ) . on_finish ( ) self . record_timing ( self . request . request_time ( ) , self . __class__ . __name__ , self . request . method , self . get_status ( ) ) | 12,077 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L68-L83 | [
"def",
"delete_object",
"(",
"container_name",
",",
"object_name",
",",
"profile",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"libcloud_kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"libcloud_kwargs",
")",
"obj",
"=",
"conn",
".",
"get_object",
"(",
"container_name",
",",
"object_name",
",",
"*",
"*",
"libcloud_kwargs",
")",
"return",
"conn",
".",
"delete_object",
"(",
"obj",
")"
] |
Invoked when the socket is closed . | 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 ( ) | 12,078 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L135-L140 | [
"def",
"load_archive",
"(",
"archive_file",
":",
"str",
",",
"cuda_device",
":",
"int",
"=",
"-",
"1",
",",
"overrides",
":",
"str",
"=",
"\"\"",
",",
"weights_file",
":",
"str",
"=",
"None",
")",
"->",
"Archive",
":",
"# redirect to the cache, if necessary",
"resolved_archive_file",
"=",
"cached_path",
"(",
"archive_file",
")",
"if",
"resolved_archive_file",
"==",
"archive_file",
":",
"logger",
".",
"info",
"(",
"f\"loading archive file {archive_file}\"",
")",
"else",
":",
"logger",
".",
"info",
"(",
"f\"loading archive file {archive_file} from cache at {resolved_archive_file}\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"resolved_archive_file",
")",
":",
"serialization_dir",
"=",
"resolved_archive_file",
"else",
":",
"# Extract archive to temp dir",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"logger",
".",
"info",
"(",
"f\"extracting archive file {resolved_archive_file} to temp dir {tempdir}\"",
")",
"with",
"tarfile",
".",
"open",
"(",
"resolved_archive_file",
",",
"'r:gz'",
")",
"as",
"archive",
":",
"archive",
".",
"extractall",
"(",
"tempdir",
")",
"# Postpone cleanup until exit in case the unarchived contents are needed outside",
"# this function.",
"atexit",
".",
"register",
"(",
"_cleanup_archive_dir",
",",
"tempdir",
")",
"serialization_dir",
"=",
"tempdir",
"# Check for supplemental files in archive",
"fta_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"serialization_dir",
",",
"_FTA_NAME",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fta_filename",
")",
":",
"with",
"open",
"(",
"fta_filename",
",",
"'r'",
")",
"as",
"fta_file",
":",
"files_to_archive",
"=",
"json",
".",
"loads",
"(",
"fta_file",
".",
"read",
"(",
")",
")",
"# Add these replacements to overrides",
"replacements_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"for",
"key",
",",
"original_filename",
"in",
"files_to_archive",
".",
"items",
"(",
")",
":",
"replacement_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"serialization_dir",
",",
"f\"fta/{key}\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"replacement_filename",
")",
":",
"replacements_dict",
"[",
"key",
"]",
"=",
"replacement_filename",
"else",
":",
"logger",
".",
"warning",
"(",
"f\"Archived file {replacement_filename} not found! At train time \"",
"f\"this file was located at {original_filename}. This may be \"",
"\"because you are loading a serialization directory. Attempting to \"",
"\"load the file from its train-time location.\"",
")",
"overrides_dict",
"=",
"parse_overrides",
"(",
"overrides",
")",
"combined_dict",
"=",
"with_fallback",
"(",
"preferred",
"=",
"overrides_dict",
",",
"fallback",
"=",
"unflatten",
"(",
"replacements_dict",
")",
")",
"overrides",
"=",
"json",
".",
"dumps",
"(",
"combined_dict",
")",
"# Load config",
"config",
"=",
"Params",
".",
"from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"serialization_dir",
",",
"CONFIG_NAME",
")",
",",
"overrides",
")",
"config",
".",
"loading_from_archive",
"=",
"True",
"if",
"weights_file",
":",
"weights_path",
"=",
"weights_file",
"else",
":",
"weights_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"serialization_dir",
",",
"_WEIGHTS_NAME",
")",
"# Fallback for serialization directories.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"weights_path",
")",
":",
"weights_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"serialization_dir",
",",
"_DEFAULT_WEIGHTS",
")",
"# Instantiate model. Use a duplicate of the config, as it will get consumed.",
"model",
"=",
"Model",
".",
"load",
"(",
"config",
".",
"duplicate",
"(",
")",
",",
"weights_file",
"=",
"weights_path",
",",
"serialization_dir",
"=",
"serialization_dir",
",",
"cuda_device",
"=",
"cuda_device",
")",
"return",
"Archive",
"(",
"model",
"=",
"model",
",",
"config",
"=",
"config",
")"
] |
Send a metric to Statsd . | 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 : # pragma: nocover LOGGER . warning ( 'Error sending TCP statsd metric: %s' , error ) except ( OSError , socket . error ) as error : # pragma: nocover LOGGER . exception ( 'Error sending statsd metric: %s' , error ) | 12,079 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L146-L172 | [
"def",
"cancel",
"(",
"self",
",",
"accountID",
",",
"orderSpecifier",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"Request",
"(",
"'PUT'",
",",
"'/v3/accounts/{accountID}/orders/{orderSpecifier}/cancel'",
")",
"request",
".",
"set_path_param",
"(",
"'accountID'",
",",
"accountID",
")",
"request",
".",
"set_path_param",
"(",
"'orderSpecifier'",
",",
"orderSpecifier",
")",
"response",
"=",
"self",
".",
"ctx",
".",
"request",
"(",
"request",
")",
"if",
"response",
".",
"content_type",
"is",
"None",
":",
"return",
"response",
"if",
"not",
"response",
".",
"content_type",
".",
"startswith",
"(",
"\"application/json\"",
")",
":",
"return",
"response",
"jbody",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"raw_body",
")",
"parsed_body",
"=",
"{",
"}",
"#",
"# Parse responses as defined by the API specification",
"#",
"if",
"str",
"(",
"response",
".",
"status",
")",
"==",
"\"200\"",
":",
"if",
"jbody",
".",
"get",
"(",
"'orderCancelTransaction'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'orderCancelTransaction'",
"]",
"=",
"self",
".",
"ctx",
".",
"transaction",
".",
"OrderCancelTransaction",
".",
"from_dict",
"(",
"jbody",
"[",
"'orderCancelTransaction'",
"]",
",",
"self",
".",
"ctx",
")",
"if",
"jbody",
".",
"get",
"(",
"'relatedTransactionIDs'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'relatedTransactionIDs'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'relatedTransactionIDs'",
")",
"if",
"jbody",
".",
"get",
"(",
"'lastTransactionID'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'lastTransactionID'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'lastTransactionID'",
")",
"elif",
"str",
"(",
"response",
".",
"status",
")",
"==",
"\"401\"",
":",
"if",
"jbody",
".",
"get",
"(",
"'errorCode'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'errorCode'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'errorCode'",
")",
"if",
"jbody",
".",
"get",
"(",
"'errorMessage'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'errorMessage'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'errorMessage'",
")",
"elif",
"str",
"(",
"response",
".",
"status",
")",
"==",
"\"404\"",
":",
"if",
"jbody",
".",
"get",
"(",
"'orderCancelRejectTransaction'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'orderCancelRejectTransaction'",
"]",
"=",
"self",
".",
"ctx",
".",
"transaction",
".",
"OrderCancelRejectTransaction",
".",
"from_dict",
"(",
"jbody",
"[",
"'orderCancelRejectTransaction'",
"]",
",",
"self",
".",
"ctx",
")",
"if",
"jbody",
".",
"get",
"(",
"'relatedTransactionIDs'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'relatedTransactionIDs'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'relatedTransactionIDs'",
")",
"if",
"jbody",
".",
"get",
"(",
"'lastTransactionID'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'lastTransactionID'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'lastTransactionID'",
")",
"if",
"jbody",
".",
"get",
"(",
"'errorCode'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'errorCode'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'errorCode'",
")",
"if",
"jbody",
".",
"get",
"(",
"'errorMessage'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'errorMessage'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'errorMessage'",
")",
"elif",
"str",
"(",
"response",
".",
"status",
")",
"==",
"\"405\"",
":",
"if",
"jbody",
".",
"get",
"(",
"'errorCode'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'errorCode'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'errorCode'",
")",
"if",
"jbody",
".",
"get",
"(",
"'errorMessage'",
")",
"is",
"not",
"None",
":",
"parsed_body",
"[",
"'errorMessage'",
"]",
"=",
"jbody",
".",
"get",
"(",
"'errorMessage'",
")",
"#",
"# Unexpected response status",
"#",
"else",
":",
"parsed_body",
"=",
"jbody",
"response",
".",
"body",
"=",
"parsed_body",
"return",
"response"
] |
Return a normalized path . | 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 ) ) | 12,080 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L174-L184 | [
"def",
"_fit_temporal",
"(",
"noise",
",",
"mask",
",",
"template",
",",
"stimfunction_tr",
",",
"tr_duration",
",",
"spatial_sd",
",",
"temporal_proportion",
",",
"temporal_sd",
",",
"noise_dict",
",",
"fit_thresh",
",",
"fit_delta",
",",
"iterations",
",",
")",
":",
"# Pull out the",
"dim_tr",
"=",
"noise",
".",
"shape",
"dim",
"=",
"dim_tr",
"[",
"0",
":",
"3",
"]",
"base",
"=",
"template",
"*",
"noise_dict",
"[",
"'max_activity'",
"]",
"base",
"=",
"base",
".",
"reshape",
"(",
"dim",
"[",
"0",
"]",
",",
"dim",
"[",
"1",
"]",
",",
"dim",
"[",
"2",
"]",
",",
"1",
")",
"mean_signal",
"=",
"(",
"base",
"[",
"mask",
">",
"0",
"]",
")",
".",
"mean",
"(",
")",
"# Iterate through different parameters to fit SNR and SFNR",
"temp_sd_orig",
"=",
"np",
".",
"copy",
"(",
"temporal_sd",
")",
"# Make a copy of the dictionary so it can be modified",
"new_nd",
"=",
"copy",
".",
"deepcopy",
"(",
"noise_dict",
")",
"# What SFNR do you want",
"target_sfnr",
"=",
"noise_dict",
"[",
"'sfnr'",
"]",
"# What AR do you want?",
"target_ar",
"=",
"noise_dict",
"[",
"'auto_reg_rho'",
"]",
"[",
"0",
"]",
"# Iterate through different MA parameters to fit AR",
"for",
"iteration",
"in",
"list",
"(",
"range",
"(",
"iterations",
")",
")",
":",
"# If there are iterations left to perform then recalculate the",
"# metrics and try again",
"# Calculate the new SFNR",
"new_sfnr",
"=",
"_calc_sfnr",
"(",
"noise",
",",
"mask",
")",
"# Calculate the AR",
"new_ar",
",",
"_",
"=",
"_calc_ARMA_noise",
"(",
"noise",
",",
"mask",
",",
"len",
"(",
"noise_dict",
"[",
"'auto_reg_rho'",
"]",
")",
",",
"len",
"(",
"noise_dict",
"[",
"'ma_rho'",
"]",
")",
",",
")",
"# Calculate the difference between the real and simulated data",
"sfnr_diff",
"=",
"abs",
"(",
"new_sfnr",
"-",
"target_sfnr",
")",
"/",
"target_sfnr",
"# Calculate the difference in the first AR component",
"ar_diff",
"=",
"new_ar",
"[",
"0",
"]",
"-",
"target_ar",
"# If the SFNR and AR is sufficiently close then break the loop",
"if",
"(",
"abs",
"(",
"ar_diff",
")",
"/",
"target_ar",
")",
"<",
"fit_thresh",
"and",
"sfnr_diff",
"<",
"fit_thresh",
":",
"msg",
"=",
"'Terminated AR fit after '",
"+",
"str",
"(",
"iteration",
")",
"+",
"' iterations.'",
"logger",
".",
"info",
"(",
"msg",
")",
"break",
"# Otherwise update the noise metrics. Get the new temporal noise value",
"temp_sd_new",
"=",
"mean_signal",
"/",
"new_sfnr",
"temporal_sd",
"-=",
"(",
"(",
"temp_sd_new",
"-",
"temp_sd_orig",
")",
"*",
"fit_delta",
")",
"# Prevent these going out of range",
"if",
"temporal_sd",
"<",
"0",
"or",
"np",
".",
"isnan",
"(",
"temporal_sd",
")",
":",
"temporal_sd",
"=",
"10e-3",
"# Set the new system noise",
"temp_sd_system_new",
"=",
"np",
".",
"sqrt",
"(",
"(",
"temporal_sd",
"**",
"2",
")",
"*",
"temporal_proportion",
")",
"# Get the new AR value",
"new_nd",
"[",
"'auto_reg_rho'",
"]",
"[",
"0",
"]",
"-=",
"(",
"ar_diff",
"*",
"fit_delta",
")",
"# Don't let the AR coefficient exceed 1",
"if",
"new_nd",
"[",
"'auto_reg_rho'",
"]",
"[",
"0",
"]",
">=",
"1",
":",
"new_nd",
"[",
"'auto_reg_rho'",
"]",
"[",
"0",
"]",
"=",
"0.99",
"# Generate the noise. The appropriate",
"noise_temporal",
"=",
"_generate_noise_temporal",
"(",
"stimfunction_tr",
",",
"tr_duration",
",",
"dim",
",",
"template",
",",
"mask",
",",
"new_nd",
",",
")",
"# Set up the machine noise",
"noise_system",
"=",
"_generate_noise_system",
"(",
"dimensions_tr",
"=",
"dim_tr",
",",
"spatial_sd",
"=",
"spatial_sd",
",",
"temporal_sd",
"=",
"temp_sd_system_new",
",",
")",
"# Sum up the noise of the brain",
"noise",
"=",
"base",
"+",
"(",
"noise_temporal",
"*",
"temporal_sd",
")",
"+",
"noise_system",
"# Reject negative values (only happens outside of the brain)",
"noise",
"[",
"noise",
"<",
"0",
"]",
"=",
"0",
"# Failed to converge",
"if",
"iterations",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"'No fitting iterations were run'",
")",
"elif",
"iteration",
"==",
"iterations",
":",
"logger",
".",
"warning",
"(",
"'AR failed to converge.'",
")",
"# Return the updated noise",
"return",
"noise"
] |
Get prefixes where applicable | def _get_prefixes ( self , metric_type ) : prefixes = [ ] if self . _prepend_metric_type : prefixes . append ( self . METRIC_TYPES [ metric_type ] ) return prefixes | 12,081 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L186-L199 | [
"def",
"create_sprint",
"(",
"self",
",",
"name",
",",
"board_id",
",",
"startDate",
"=",
"None",
",",
"endDate",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"startDate",
":",
"payload",
"[",
"\"startDate\"",
"]",
"=",
"startDate",
"if",
"endDate",
":",
"payload",
"[",
"\"endDate\"",
"]",
"=",
"endDate",
"if",
"self",
".",
"_options",
"[",
"'agile_rest_path'",
"]",
"==",
"GreenHopperResource",
".",
"GREENHOPPER_REST_PATH",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'sprint/%s'",
"%",
"board_id",
",",
"base",
"=",
"self",
".",
"AGILE_BASE_URL",
")",
"r",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"url",
")",
"raw_issue_json",
"=",
"json_loads",
"(",
"r",
")",
"\"\"\" now r contains something like:\n {\n \"id\": 742,\n \"name\": \"Sprint 89\",\n \"state\": \"FUTURE\",\n \"linkedPagesCount\": 0,\n \"startDate\": \"None\",\n \"endDate\": \"None\",\n \"completeDate\": \"None\",\n \"remoteLinks\": []\n }\"\"\"",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'sprint/%s'",
"%",
"raw_issue_json",
"[",
"'id'",
"]",
",",
"base",
"=",
"self",
".",
"AGILE_BASE_URL",
")",
"r",
"=",
"self",
".",
"_session",
".",
"put",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"raw_issue_json",
"=",
"json_loads",
"(",
"r",
")",
"else",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'sprint'",
",",
"base",
"=",
"self",
".",
"AGILE_BASE_URL",
")",
"payload",
"[",
"'originBoardId'",
"]",
"=",
"board_id",
"r",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"raw_issue_json",
"=",
"json_loads",
"(",
"r",
")",
"return",
"Sprint",
"(",
"self",
".",
"_options",
",",
"self",
".",
"_session",
",",
"raw",
"=",
"raw_issue_json",
")"
] |
Display a message in lbl_feedback which times out after some number of seconds . | 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 ) | 12,082 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/qtview.py#L137-L149 | [
"def",
"event_id",
"(",
"name",
",",
"encode_types",
")",
":",
"event_types",
"=",
"[",
"_canonical_type",
"(",
"type_",
")",
"for",
"type_",
"in",
"encode_types",
"]",
"event_signature",
"=",
"'{event_name}({canonical_types})'",
".",
"format",
"(",
"event_name",
"=",
"name",
",",
"canonical_types",
"=",
"','",
".",
"join",
"(",
"event_types",
")",
",",
")",
"return",
"big_endian_to_int",
"(",
"utils",
".",
"sha3",
"(",
"event_signature",
")",
")"
] |
Return either tutor or student based on which radio button is selected . | 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 ( ) | 12,083 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/qtview.py#L278-L286 | [
"def",
"_insert",
"(",
"self",
",",
"namespace",
",",
"stream",
",",
"events",
",",
"configuration",
")",
":",
"index",
"=",
"self",
".",
"index_manager",
".",
"get_index",
"(",
"namespace",
")",
"start_dts_to_add",
"=",
"set",
"(",
")",
"def",
"actions",
"(",
")",
":",
"for",
"_id",
",",
"event",
"in",
"events",
":",
"dt",
"=",
"kronos_time_to_datetime",
"(",
"uuid_to_kronos_time",
"(",
"_id",
")",
")",
"start_dts_to_add",
".",
"add",
"(",
"_round_datetime_down",
"(",
"dt",
")",
")",
"event",
"[",
"'_index'",
"]",
"=",
"index",
"event",
"[",
"'_type'",
"]",
"=",
"stream",
"event",
"[",
"LOGSTASH_TIMESTAMP_FIELD",
"]",
"=",
"dt",
".",
"isoformat",
"(",
")",
"yield",
"event",
"list",
"(",
"es_helpers",
".",
"streaming_bulk",
"(",
"self",
".",
"es",
",",
"actions",
"(",
")",
",",
"chunk_size",
"=",
"1000",
",",
"refresh",
"=",
"self",
".",
"force_refresh",
")",
")",
"self",
".",
"index_manager",
".",
"add_aliases",
"(",
"namespace",
",",
"index",
",",
"start_dts_to_add",
")"
] |
Shuffle items in place using Sattolo s algorithm . | def shuffle_sattolo ( items ) : _randrange = random . randrange for i in reversed ( range ( 1 , len ( items ) ) ) : j = _randrange ( i ) # 0 <= j < i items [ j ] , items [ i ] = items [ i ] , items [ j ] | 12,084 | https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L19-L24 | [
"def",
"wrap_get_stream",
"(",
"cls",
",",
"response",
")",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"s",
"=",
"cls",
".",
"wrap_json",
"(",
"json",
"[",
"'stream'",
"]",
")",
"return",
"s"
] |
Validate and convert comma - separated list of column numbers . | 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 | 12,085 | https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L27-L38 | [
"def",
"add_connection_args",
"(",
"parser",
":",
"FileAwareParser",
",",
"strong_config_file",
":",
"bool",
"=",
"True",
")",
"->",
"FileAwareParser",
":",
"# TODO: Decide what to do with this",
"parser",
".",
"add_file_argument",
"(",
"\"--conf\"",
",",
"metavar",
"=",
"\"CONFIG FILE\"",
",",
"help",
"=",
"\"Configuration file\"",
",",
"action",
"=",
"ConfigFile",
"if",
"strong_config_file",
"else",
"None",
")",
"parser",
".",
"add_argument",
"(",
"\"-db\"",
",",
"\"--dburl\"",
",",
"help",
"=",
"\"Default database URL\"",
",",
"default",
"=",
"Default_DB_Connection",
")",
"parser",
".",
"add_argument",
"(",
"\"--user\"",
",",
"help",
"=",
"\"Default user name\"",
",",
"default",
"=",
"Default_User",
")",
"parser",
".",
"add_argument",
"(",
"\"--password\"",
",",
"help",
"=",
"\"Default password\"",
",",
"default",
"=",
"Default_Password",
")",
"parser",
".",
"add_argument",
"(",
"\"--crcdb\"",
",",
"help",
"=",
"\"CRC database URL. (default: dburl)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--crcuser\"",
",",
"help",
"=",
"\"User name for CRC database. (default: user)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--crcpassword\"",
",",
"help",
"=",
"\"Password for CRC database. (default: password)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--ontodb\"",
",",
"help",
"=",
"\"Ontology database URL. (default: dburl)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--ontouser\"",
",",
"help",
"=",
"\"User name for ontology database. (default: user)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--ontopassword\"",
",",
"help",
"=",
"\"Password for ontology database. (default: password)\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--onttable\"",
",",
"metavar",
"=",
"\"ONTOLOGY TABLE NAME\"",
",",
"help",
"=",
"\"Ontology table name (default: {})\"",
".",
"format",
"(",
"DEFAULT_ONTOLOGY_TABLE",
")",
",",
"default",
"=",
"DEFAULT_ONTOLOGY_TABLE",
")",
"return",
"parser"
] |
Get the first row and use it as column headers | 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 ) """Create a matrix of lists of columns""" 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 : """If columns to exclude are provided, get a list of all other columns""" cols = list ( set ( range ( len ( headers ) ) ) - set ( args . no_columns ) ) elif not cols : """If no columns are provided all columns will be shuffled""" 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 ] ) """Transpose the matrix""" table = zip ( * table ) writer = csv . writer ( sys . stdout , delimiter = args . output_delimiter ) writer . writerow ( headers ) for row in table : writer . writerow ( row ) | 12,086 | https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L41-L101 | [
"def",
"unregister_vm",
"(",
"vm_ref",
")",
":",
"vm_name",
"=",
"get_managed_object_name",
"(",
"vm_ref",
")",
"log",
".",
"trace",
"(",
"'Destroying vm \\'%s\\''",
",",
"vm_name",
")",
"try",
":",
"vm_ref",
".",
"UnregisterVM",
"(",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")"
] |
Return the element of the list after the given keyword . | 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 | 12,087 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L44-L72 | [
"def",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
":",
"registries",
"=",
"[",
"]",
"for",
"path",
"in",
"chain",
"(",
"registries_path",
"(",
"fs0",
".",
"fsroot",
")",
",",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
")",
":",
"if",
"fs0",
".",
"checksum",
"(",
"path",
")",
"!=",
"fs1",
".",
"checksum",
"(",
"path",
")",
":",
"registries",
".",
"append",
"(",
"path",
")",
"return",
"registries"
] |
Return the element of the list after the given keyword as string . | def gets ( self , keyword ) : param = self . get ( keyword ) if param is not None : return safe_decode ( param . string_value ( ) ) return None | 12,088 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L74-L97 | [
"def",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
":",
"registries",
"=",
"[",
"]",
"for",
"path",
"in",
"chain",
"(",
"registries_path",
"(",
"fs0",
".",
"fsroot",
")",
",",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
")",
":",
"if",
"fs0",
".",
"checksum",
"(",
"path",
")",
"!=",
"fs1",
".",
"checksum",
"(",
"path",
")",
":",
"registries",
".",
"append",
"(",
"path",
")",
"return",
"registries"
] |
Append an element to the end of the list . | def append ( self , obj ) : if isinstance ( obj , str ) : obj = KQMLToken ( obj ) self . data . append ( obj ) | 12,089 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L100-L111 | [
"def",
"roles_dict",
"(",
"path",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"\"\"",
")",
":",
"exit_if_path_not_found",
"(",
"path",
")",
"aggregated_roles",
"=",
"{",
"}",
"roles",
"=",
"os",
".",
"walk",
"(",
"path",
")",
".",
"next",
"(",
")",
"[",
"1",
"]",
"# First scan all directories",
"for",
"role",
"in",
"roles",
":",
"for",
"sub_role",
"in",
"roles_dict",
"(",
"path",
"+",
"\"/\"",
"+",
"role",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"role",
"+",
"\"/\"",
")",
":",
"aggregated_roles",
"[",
"role",
"+",
"\"/\"",
"+",
"sub_role",
"]",
"=",
"role",
"+",
"\"/\"",
"+",
"sub_role",
"# Then format them",
"for",
"role",
"in",
"roles",
":",
"if",
"is_role",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"role",
")",
")",
":",
"if",
"isinstance",
"(",
"role",
",",
"basestring",
")",
":",
"role_repo",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"repo_prefix",
",",
"role_name",
"(",
"role",
")",
")",
"aggregated_roles",
"[",
"role",
"]",
"=",
"role_repo",
"return",
"aggregated_roles"
] |
Prepend an element to the beginnging of the list . | def push ( self , obj ) : if isinstance ( obj , str ) : obj = KQMLToken ( obj ) self . data . insert ( 0 , obj ) | 12,090 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L113-L124 | [
"def",
"roles_dict",
"(",
"path",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"\"\"",
")",
":",
"exit_if_path_not_found",
"(",
"path",
")",
"aggregated_roles",
"=",
"{",
"}",
"roles",
"=",
"os",
".",
"walk",
"(",
"path",
")",
".",
"next",
"(",
")",
"[",
"1",
"]",
"# First scan all directories",
"for",
"role",
"in",
"roles",
":",
"for",
"sub_role",
"in",
"roles_dict",
"(",
"path",
"+",
"\"/\"",
"+",
"role",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"role",
"+",
"\"/\"",
")",
":",
"aggregated_roles",
"[",
"role",
"+",
"\"/\"",
"+",
"sub_role",
"]",
"=",
"role",
"+",
"\"/\"",
"+",
"sub_role",
"# Then format them",
"for",
"role",
"in",
"roles",
":",
"if",
"is_role",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"role",
")",
")",
":",
"if",
"isinstance",
"(",
"role",
",",
"basestring",
")",
":",
"role_repo",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"repo_prefix",
",",
"role_name",
"(",
"role",
")",
")",
"aggregated_roles",
"[",
"role",
"]",
"=",
"role_repo",
"return",
"aggregated_roles"
] |
Set the element of the list after the given keyword . | 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 ) | 12,091 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L149-L182 | [
"def",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
":",
"registries",
"=",
"[",
"]",
"for",
"path",
"in",
"chain",
"(",
"registries_path",
"(",
"fs0",
".",
"fsroot",
")",
",",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
")",
":",
"if",
"fs0",
".",
"checksum",
"(",
"path",
")",
"!=",
"fs1",
".",
"checksum",
"(",
"path",
")",
":",
"registries",
".",
"append",
"(",
"path",
")",
"return",
"registries"
] |
Set the element of the list after the given keyword as string . | def sets ( self , keyword , value ) : if isinstance ( value , str ) : value = KQMLString ( value ) self . set ( keyword , value ) | 12,092 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L184-L204 | [
"def",
"compare_hives",
"(",
"fs0",
",",
"fs1",
")",
":",
"registries",
"=",
"[",
"]",
"for",
"path",
"in",
"chain",
"(",
"registries_path",
"(",
"fs0",
".",
"fsroot",
")",
",",
"user_registries",
"(",
"fs0",
",",
"fs1",
")",
")",
":",
"if",
"fs0",
".",
"checksum",
"(",
"path",
")",
"!=",
"fs1",
".",
"checksum",
"(",
"path",
")",
":",
"registries",
".",
"append",
"(",
"path",
")",
"return",
"registries"
] |
Read a recipe file from disk | 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 ) | 12,093 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/ConfigManager.py#L56-L73 | [
"def",
"get_bars",
"(",
"self",
",",
"assets",
",",
"data_frequency",
",",
"bar_count",
"=",
"500",
")",
":",
"assets_is_scalar",
"=",
"not",
"isinstance",
"(",
"assets",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
"is_daily",
"=",
"'d'",
"in",
"data_frequency",
"# 'daily' or '1d'",
"if",
"assets_is_scalar",
":",
"symbols",
"=",
"[",
"assets",
".",
"symbol",
"]",
"else",
":",
"symbols",
"=",
"[",
"asset",
".",
"symbol",
"for",
"asset",
"in",
"assets",
"]",
"symbol_bars",
"=",
"self",
".",
"_symbol_bars",
"(",
"symbols",
",",
"'day'",
"if",
"is_daily",
"else",
"'minute'",
",",
"limit",
"=",
"bar_count",
")",
"if",
"is_daily",
":",
"intra_bars",
"=",
"{",
"}",
"symbol_bars_minute",
"=",
"self",
".",
"_symbol_bars",
"(",
"symbols",
",",
"'minute'",
",",
"limit",
"=",
"1000",
")",
"for",
"symbol",
",",
"df",
"in",
"symbol_bars_minute",
".",
"items",
"(",
")",
":",
"agged",
"=",
"df",
".",
"resample",
"(",
"'1D'",
")",
".",
"agg",
"(",
"dict",
"(",
"open",
"=",
"'first'",
",",
"high",
"=",
"'max'",
",",
"low",
"=",
"'min'",
",",
"close",
"=",
"'last'",
",",
"volume",
"=",
"'sum'",
",",
")",
")",
".",
"dropna",
"(",
")",
"intra_bars",
"[",
"symbol",
"]",
"=",
"agged",
"dfs",
"=",
"[",
"]",
"for",
"asset",
"in",
"assets",
"if",
"not",
"assets_is_scalar",
"else",
"[",
"assets",
"]",
":",
"symbol",
"=",
"asset",
".",
"symbol",
"df",
"=",
"symbol_bars",
".",
"get",
"(",
"symbol",
")",
"if",
"df",
"is",
"None",
":",
"dfs",
".",
"append",
"(",
"pd",
".",
"DataFrame",
"(",
"[",
"]",
",",
"columns",
"=",
"[",
"'open'",
",",
"'high'",
",",
"'low'",
",",
"'close'",
",",
"'volume'",
"]",
")",
")",
"continue",
"if",
"is_daily",
":",
"agged",
"=",
"intra_bars",
".",
"get",
"(",
"symbol",
")",
"if",
"agged",
"is",
"not",
"None",
"and",
"len",
"(",
"agged",
".",
"index",
")",
">",
"0",
"and",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
"not",
"in",
"df",
".",
"index",
":",
"if",
"not",
"(",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
">",
"df",
".",
"index",
"[",
"-",
"1",
"]",
")",
":",
"log",
".",
"warn",
"(",
"(",
"'agged.index[-1] = {}, df.index[-1] = {} '",
"'for {}'",
")",
".",
"format",
"(",
"agged",
".",
"index",
"[",
"-",
"1",
"]",
",",
"df",
".",
"index",
"[",
"-",
"1",
"]",
",",
"symbol",
")",
")",
"df",
"=",
"df",
".",
"append",
"(",
"agged",
".",
"iloc",
"[",
"-",
"1",
"]",
")",
"df",
".",
"columns",
"=",
"pd",
".",
"MultiIndex",
".",
"from_product",
"(",
"[",
"[",
"asset",
",",
"]",
",",
"df",
".",
"columns",
"]",
")",
"dfs",
".",
"append",
"(",
"df",
")",
"return",
"pd",
".",
"concat",
"(",
"dfs",
",",
"axis",
"=",
"1",
")"
] |
Set a random port to be used by zmq | 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}" | 12,094 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/ConfigManager.py#L75-L93 | [
"def",
"_parse_materials",
"(",
"header",
",",
"views",
")",
":",
"try",
":",
"import",
"PIL",
".",
"Image",
"except",
"ImportError",
":",
"log",
".",
"warning",
"(",
"\"unable to load textures without pillow!\"",
")",
"return",
"None",
"# load any images",
"images",
"=",
"None",
"if",
"\"images\"",
"in",
"header",
":",
"# images are referenced by index",
"images",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"header",
"[",
"\"images\"",
"]",
")",
"# loop through images",
"for",
"i",
",",
"img",
"in",
"enumerate",
"(",
"header",
"[",
"\"images\"",
"]",
")",
":",
"# get the bytes representing an image",
"blob",
"=",
"views",
"[",
"img",
"[",
"\"bufferView\"",
"]",
"]",
"# i.e. 'image/jpeg'",
"# mime = img['mimeType']",
"try",
":",
"# load the buffer into a PIL image",
"images",
"[",
"i",
"]",
"=",
"PIL",
".",
"Image",
".",
"open",
"(",
"util",
".",
"wrap_as_stream",
"(",
"blob",
")",
")",
"except",
"BaseException",
":",
"log",
".",
"error",
"(",
"\"failed to load image!\"",
",",
"exc_info",
"=",
"True",
")",
"# store materials which reference images",
"materials",
"=",
"[",
"]",
"if",
"\"materials\"",
"in",
"header",
":",
"for",
"mat",
"in",
"header",
"[",
"\"materials\"",
"]",
":",
"# flatten key structure so we can loop it",
"loopable",
"=",
"mat",
".",
"copy",
"(",
")",
"# this key stores another dict of crap",
"if",
"\"pbrMetallicRoughness\"",
"in",
"loopable",
":",
"# add keys of keys to top level dict",
"loopable",
".",
"update",
"(",
"loopable",
".",
"pop",
"(",
"\"pbrMetallicRoughness\"",
")",
")",
"# save flattened keys we can use for kwargs",
"pbr",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"loopable",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"pbr",
"[",
"k",
"]",
"=",
"v",
"elif",
"\"index\"",
"in",
"v",
":",
"# get the index of image for texture",
"idx",
"=",
"header",
"[",
"\"textures\"",
"]",
"[",
"v",
"[",
"\"index\"",
"]",
"]",
"[",
"\"source\"",
"]",
"# store the actual image as the value",
"pbr",
"[",
"k",
"]",
"=",
"images",
"[",
"idx",
"]",
"# create a PBR material object for the GLTF material",
"materials",
".",
"append",
"(",
"visual",
".",
"texture",
".",
"PBRMaterial",
"(",
"*",
"*",
"pbr",
")",
")",
"return",
"materials"
] |
Fetch quantities from this catalog . | 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 } | 12,095 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L41-L77 | [
"def",
"wrap",
"(",
"self",
",",
"wrapper",
")",
":",
"if",
"self",
".",
"_recv_thread",
"and",
"self",
".",
"_send_thread",
":",
"# Have to suspend the send/recv threads",
"self",
".",
"_recv_lock",
".",
"acquire",
"(",
")",
"self",
".",
"_send_lock",
".",
"acquire",
"(",
")",
"# Wrap the socket",
"self",
".",
"_sock",
"=",
"wrapper",
"(",
"self",
".",
"_sock",
")",
"# OK, restart the send/recv threads",
"if",
"self",
".",
"_recv_thread",
"and",
"self",
".",
"_send_thread",
":",
"# Release our locks",
"self",
".",
"_send_lock",
".",
"release",
"(",
")",
"self",
".",
"_recv_lock",
".",
"release",
"(",
")"
] |
Return a list of all available quantities in this catalog . | 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 ) | 12,096 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L126-L138 | [
"def",
"wrap",
"(",
"self",
",",
"wrapper",
")",
":",
"if",
"self",
".",
"_recv_thread",
"and",
"self",
".",
"_send_thread",
":",
"# Have to suspend the send/recv threads",
"self",
".",
"_recv_lock",
".",
"acquire",
"(",
")",
"self",
".",
"_send_lock",
".",
"acquire",
"(",
")",
"# Wrap the socket",
"self",
".",
"_sock",
"=",
"wrapper",
"(",
"self",
".",
"_sock",
")",
"# OK, restart the send/recv threads",
"if",
"self",
".",
"_recv_thread",
"and",
"self",
".",
"_send_thread",
":",
"# Release our locks",
"self",
".",
"_send_lock",
".",
"release",
"(",
")",
"self",
".",
"_recv_lock",
".",
"release",
"(",
")"
] |
Return a list of all available native quantities in this catalog . | 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 ) | 12,097 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L140-L149 | [
"def",
"wrap_conn",
"(",
"conn_func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cursor_func",
"=",
"getattr",
"(",
"conn",
",",
"CURSOR_WRAP_METHOD",
")",
"wrapped",
"=",
"wrap_cursor",
"(",
"cursor_func",
")",
"setattr",
"(",
"conn",
",",
"cursor_func",
".",
"__name__",
",",
"wrapped",
")",
"return",
"conn",
"except",
"Exception",
":",
"# pragma: NO COVER",
"logging",
".",
"warning",
"(",
"'Fail to wrap conn, mysql not traced.'",
")",
"return",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"call"
] |
Return the first available quantity in the input arguments . Return None if none of them is available . | 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 | 12,098 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L151-L160 | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"union",
"=",
"Rect",
"(",
")",
"lib",
".",
"SDL_UnionRect",
"(",
"self",
".",
"_ptr",
",",
"other",
".",
"_ptr",
",",
"union",
".",
"_ptr",
")",
"return",
"union"
] |
Deprecated . Use get_catalog_info instead . | 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 ) | 12,099 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L162-L170 | [
"def",
"leave_room",
"(",
"self",
",",
"sid",
",",
"namespace",
",",
"room",
")",
":",
"try",
":",
"del",
"self",
".",
"rooms",
"[",
"namespace",
"]",
"[",
"room",
"]",
"[",
"sid",
"]",
"if",
"len",
"(",
"self",
".",
"rooms",
"[",
"namespace",
"]",
"[",
"room",
"]",
")",
"==",
"0",
":",
"del",
"self",
".",
"rooms",
"[",
"namespace",
"]",
"[",
"room",
"]",
"if",
"len",
"(",
"self",
".",
"rooms",
"[",
"namespace",
"]",
")",
"==",
"0",
":",
"del",
"self",
".",
"rooms",
"[",
"namespace",
"]",
"except",
"KeyError",
":",
"pass"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.