query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Given a dictionary mapping each feature to the pathways overrepresented in the feature build a CoNetwork by creating edges for every pairwise combination of pathways in a feature . | def _edges_from_permutation ( self , feature_pathway_dict ) : network_edges = { } for feature , pathway_list in feature_pathway_dict . items ( ) : for i in range ( len ( pathway_list ) ) : for j in range ( i + 1 , len ( pathway_list ) ) : vertex_i = pathway_list [ i ] vertex_j = pathway_list [ j ] new_edge = self . edge_tuple ( vertex_i , vertex_j ) if new_edge not in network_edges : network_edges [ new_edge ] = [ ] network_edges [ new_edge ] . append ( feature ) self . _augment_network ( network_edges ) | 10,300 | https://github.com/greenelab/PathCORE-T/blob/9d079d5ebffea2fe9fb9ab557588d51ad67d2c9c/pathcore/network.py#L522-L537 | [
"def",
"remove_stale_javascripts",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing stale javascripts ...\"",
")",
"for",
"js",
"in",
"JAVASCRIPTS_TO_REMOVE",
":",
"logger",
".",
"info",
"(",
"\"Unregistering JS %s\"",
"%",
"js",
")",
"portal",
".",
"portal_javascripts",
".",
"unregisterResource",
"(",
"js",
")"
] |
Normalize text when fixed format is ON replace the first 6 chars by a space . | def normalize_text ( self , text ) : if not self . editor . free_format : text = ' ' * 6 + text [ 6 : ] return text . upper ( ) | 10,301 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/folding.py#L43-L49 | [
"def",
"get_files",
"(",
"self",
",",
"file_paths",
")",
":",
"results",
"=",
"[",
"]",
"def",
"get_file_thunk",
"(",
"path",
",",
"interface",
")",
":",
"result",
"=",
"error",
"=",
"None",
"try",
":",
"result",
"=",
"interface",
".",
"get_file",
"(",
"path",
")",
"except",
"Exception",
"as",
"err",
":",
"error",
"=",
"err",
"# important to print immediately because ",
"# errors are collected at the end",
"print",
"(",
"err",
")",
"content",
",",
"encoding",
"=",
"result",
"content",
"=",
"compression",
".",
"decompress",
"(",
"content",
",",
"encoding",
")",
"results",
".",
"append",
"(",
"{",
"\"filename\"",
":",
"path",
",",
"\"content\"",
":",
"content",
",",
"\"error\"",
":",
"error",
",",
"}",
")",
"for",
"path",
"in",
"file_paths",
":",
"if",
"len",
"(",
"self",
".",
"_threads",
")",
":",
"self",
".",
"put",
"(",
"partial",
"(",
"get_file_thunk",
",",
"path",
")",
")",
"else",
":",
"get_file_thunk",
"(",
"path",
",",
"self",
".",
"_interface",
")",
"desc",
"=",
"'Downloading'",
"if",
"self",
".",
"progress",
"else",
"None",
"self",
".",
"wait",
"(",
"desc",
")",
"return",
"results"
] |
Get the neighborhood graph of a node . | def get_neighborhood_network ( self , node_name : str , order : int = 1 ) -> Graph : logger . info ( "In get_neighborhood_graph()" ) neighbors = list ( self . get_neighbor_names ( node_name , order ) ) neighbor_network = self . graph . copy ( ) neighbor_network . delete_vertices ( self . graph . vs . select ( name_notin = neighbors ) ) return neighbor_network | 10,302 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/neighborhood_network.py#L26-L36 | [
"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"
] |
Get the names of all neighbors of a node and the node itself . | def get_neighbor_names ( self , node_name : str , order : int = 1 ) -> list : logger . info ( "In get_neighbor_names()" ) node = self . graph . vs . find ( name = node_name ) neighbors = self . graph . neighborhood ( node , order = order ) names = self . graph . vs [ neighbors ] [ "name" ] names . append ( node_name ) return list ( names ) | 10,303 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/neighborhood_network.py#L38-L49 | [
"def",
"insert_recording",
"(",
"hw",
")",
":",
"mysql",
"=",
"utils",
".",
"get_mysql_cfg",
"(",
")",
"connection",
"=",
"pymysql",
".",
"connect",
"(",
"host",
"=",
"mysql",
"[",
"'host'",
"]",
",",
"user",
"=",
"mysql",
"[",
"'user'",
"]",
",",
"passwd",
"=",
"mysql",
"[",
"'passwd'",
"]",
",",
"db",
"=",
"mysql",
"[",
"'db'",
"]",
",",
"charset",
"=",
"'utf8mb4'",
",",
"cursorclass",
"=",
"pymysql",
".",
"cursors",
".",
"DictCursor",
")",
"try",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"sql",
"=",
"(",
"\"INSERT INTO `wm_raw_draw_data` (\"",
"\"`user_id`, \"",
"\"`data`, \"",
"\"`md5data`, \"",
"\"`creation_date`, \"",
"\"`device_type`, \"",
"\"`accepted_formula_id`, \"",
"\"`secret`, \"",
"\"`ip`, \"",
"\"`segmentation`, \"",
"\"`internal_id`, \"",
"\"`description` \"",
"\") VALUES (%s, %s, MD5(data), \"",
"\"%s, %s, %s, %s, %s, %s, %s, %s);\"",
")",
"data",
"=",
"(",
"hw",
".",
"user_id",
",",
"hw",
".",
"raw_data_json",
",",
"getattr",
"(",
"hw",
",",
"'creation_date'",
",",
"None",
")",
",",
"getattr",
"(",
"hw",
",",
"'device_type'",
",",
"''",
")",
",",
"getattr",
"(",
"hw",
",",
"'formula_id'",
",",
"None",
")",
",",
"getattr",
"(",
"hw",
",",
"'secret'",
",",
"''",
")",
",",
"getattr",
"(",
"hw",
",",
"'ip'",
",",
"None",
")",
",",
"str",
"(",
"getattr",
"(",
"hw",
",",
"'segmentation'",
",",
"''",
")",
")",
",",
"getattr",
"(",
"hw",
",",
"'internal_id'",
",",
"''",
")",
",",
"getattr",
"(",
"hw",
",",
"'description'",
",",
"''",
")",
")",
"cursor",
".",
"execute",
"(",
"sql",
",",
"data",
")",
"connection",
".",
"commit",
"(",
")",
"for",
"symbol_id",
",",
"strokes",
"in",
"zip",
"(",
"hw",
".",
"symbol_stream",
",",
"hw",
".",
"segmentation",
")",
":",
"insert_symbol_mapping",
"(",
"cursor",
".",
"lastrowid",
",",
"symbol_id",
",",
"hw",
".",
"user_id",
",",
"strokes",
")",
"logging",
".",
"info",
"(",
"\"Insert raw data.\"",
")",
"except",
"pymysql",
".",
"err",
".",
"IntegrityError",
"as",
"e",
":",
"print",
"(",
"\"Error: {} (can probably be ignored)\"",
".",
"format",
"(",
"e",
")",
")"
] |
Get the intersection of two nodes s neighborhoods . | def get_neighborhood_overlap ( self , node1 , node2 , connection_type = None ) : if connection_type is None or connection_type == "direct" : order = 1 elif connection_type == "second-degree" : order = 2 else : raise Exception ( "Invalid option: {}. Valid options are direct and second-degree" . format ( connection_type ) ) neighbors1 = self . graph . neighborhood ( node1 , order = order ) neighbors2 = self . graph . neighborhood ( node2 , order = order ) return set ( neighbors1 ) . intersection ( neighbors2 ) | 10,304 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/neighborhood_network.py#L51-L72 | [
"def",
"setup_main_logger",
"(",
"file_logging",
"=",
"True",
",",
"console",
"=",
"True",
",",
"path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
":",
"if",
"file_logging",
"and",
"console",
":",
"log_config",
"=",
"LOGGING_CONFIGS",
"[",
"\"file_console\"",
"]",
"# type: ignore",
"elif",
"file_logging",
":",
"log_config",
"=",
"LOGGING_CONFIGS",
"[",
"\"file_only\"",
"]",
"elif",
"console",
":",
"log_config",
"=",
"LOGGING_CONFIGS",
"[",
"\"console_only\"",
"]",
"else",
":",
"log_config",
"=",
"LOGGING_CONFIGS",
"[",
"\"none\"",
"]",
"if",
"path",
":",
"log_config",
"[",
"\"handlers\"",
"]",
"[",
"\"rotating\"",
"]",
"[",
"\"filename\"",
"]",
"=",
"path",
"# type: ignore",
"for",
"_",
",",
"handler_config",
"in",
"log_config",
"[",
"'handlers'",
"]",
".",
"items",
"(",
")",
":",
"# type: ignore",
"handler_config",
"[",
"'level'",
"]",
"=",
"level",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"log_config",
")",
"# type: ignore",
"def",
"exception_hook",
"(",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
":",
"if",
"is_python34",
"(",
")",
":",
"# Python3.4 does not seem to handle logger.exception() well",
"import",
"traceback",
"traceback",
"=",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_tb",
"(",
"exc_traceback",
")",
")",
"+",
"exc_type",
".",
"name",
"logging",
".",
"error",
"(",
"\"Uncaught exception\\n%s\"",
",",
"traceback",
")",
"else",
":",
"logging",
".",
"exception",
"(",
"\"Uncaught exception\"",
",",
"exc_info",
"=",
"(",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
")",
")",
"sys",
".",
"excepthook",
"=",
"exception_hook"
] |
Match simple values excluding some Keywords like and and or | def parse ( cls , parser , text , pos ) : # pylint: disable=W0613 if not text . strip ( ) : return text , SyntaxError ( "Invalid value" ) class Rule ( object ) : grammar = attr ( 'value' , SpiresSimpleValue ) , omit ( re . compile ( ".*" ) ) try : tree = pypeg2 . parse ( text , Rule , whitespace = "" ) except SyntaxError : return text , SyntaxError ( "Expected %r" % cls ) else : r = tree . value if r . value . lower ( ) in ( 'and' , 'or' , 'not' ) : return text , SyntaxError ( "Invalid value %s" % r . value ) return text [ len ( r . value ) : ] , r | 10,305 | https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/contrib/spires/parser.py#L64-L82 | [
"def",
"writearff",
"(",
"data",
",",
"filename",
",",
"relation_name",
"=",
"None",
",",
"index",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"relation_name",
"is",
"None",
":",
"relation_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"else",
":",
"fp",
"=",
"filename",
"if",
"relation_name",
"is",
"None",
":",
"relation_name",
"=",
"\"pandas\"",
"try",
":",
"data",
"=",
"_write_header",
"(",
"data",
",",
"fp",
",",
"relation_name",
",",
"index",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")",
"_write_data",
"(",
"data",
",",
"fp",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] |
Gets the list of pic fields information from line |start| to line |end| . | def get_field_infos ( code , free_format ) : offset = 0 field_infos = [ ] lines = _clean_code ( code ) previous_offset = 0 for row in process_cobol ( lines , free_format ) : fi = PicFieldInfo ( ) fi . name = row [ "name" ] fi . level = row [ "level" ] fi . pic = row [ "pic" ] fi . occurs = row [ "occurs" ] fi . redefines = row [ "redefines" ] fi . indexed_by = row [ "indexed_by" ] # find item that was redefined and use its offset if fi . redefines : for fib in field_infos : if fib . name == fi . redefines : offset = fib . offset # level 1 should have their offset set to 1 if fi . level == 1 : offset = 1 # level 78 have no offset if fi . level == 78 : offset = 0 # level 77 have offset always to 1 if fi . level == 77 : offset = 1 # set item offset fi . offset = offset # special case: level 88 have the same level as its parent if fi . level == 88 : fi . offset = previous_offset else : previous_offset = offset field_infos . append ( fi ) # compute offset of next PIC field. if row [ 'pic' ] : offset += row [ 'pic_info' ] [ 'length' ] return field_infos | 10,306 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/pic.py#L47-L103 | [
"def",
"_check_for_boolean_pair_reduction",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"'reduction_forcing_pairs'",
"in",
"self",
".",
"_meta_data",
":",
"for",
"key1",
",",
"key2",
"in",
"self",
".",
"_meta_data",
"[",
"'reduction_forcing_pairs'",
"]",
":",
"kwargs",
"=",
"self",
".",
"_reduce_boolean_pair",
"(",
"kwargs",
",",
"key1",
",",
"key2",
")",
"return",
"kwargs"
] |
Returns a Premier account signed url . | def get_signed_url ( self , params ) : params [ 'client' ] = self . client_id url_params = { 'protocol' : self . protocol , 'domain' : self . domain , 'service' : self . service , 'params' : urlencode ( params ) } secret = base64 . urlsafe_b64decode ( self . secret_key ) url_params [ 'url_part' ] = ( '/maps/api/%(service)s/json?%(params)s' % url_params ) signature = hmac . new ( secret , url_params [ 'url_part' ] , hashlib . sha1 ) url_params [ 'signature' ] = base64 . urlsafe_b64encode ( signature . digest ( ) ) return ( '%(protocol)s://%(domain)s%(url_part)s' '&signature=%(signature)s' % url_params ) | 10,307 | https://github.com/walter426/Python_GoogleMapsApi/blob/4832b293a0027446941a5f00ecc66256f92ddbce/GoogleMapsApi/GoogleMapsServiceParser.py#L85-L98 | [
"def",
"apply_noise",
"(",
"data",
",",
"noise",
")",
":",
"if",
"noise",
">=",
"1",
":",
"noise",
"=",
"noise",
"/",
"100.",
"for",
"i",
"in",
"range",
"(",
"data",
".",
"nRows",
"(",
")",
")",
":",
"ones",
"=",
"data",
".",
"rowNonZeros",
"(",
"i",
")",
"[",
"0",
"]",
"replace_indices",
"=",
"numpy",
".",
"random",
".",
"choice",
"(",
"ones",
",",
"size",
"=",
"int",
"(",
"len",
"(",
"ones",
")",
"*",
"noise",
")",
",",
"replace",
"=",
"False",
")",
"for",
"index",
"in",
"replace_indices",
":",
"data",
"[",
"i",
",",
"index",
"]",
"=",
"0",
"new_indices",
"=",
"numpy",
".",
"random",
".",
"choice",
"(",
"data",
".",
"nCols",
"(",
")",
",",
"size",
"=",
"int",
"(",
"len",
"(",
"ones",
")",
"*",
"noise",
")",
",",
"replace",
"=",
"False",
")",
"for",
"index",
"in",
"new_indices",
":",
"while",
"data",
"[",
"i",
",",
"index",
"]",
"==",
"1",
":",
"index",
"=",
"numpy",
".",
"random",
".",
"randint",
"(",
"0",
",",
"data",
".",
"nCols",
"(",
")",
")",
"data",
"[",
"i",
",",
"index",
"]",
"=",
"1"
] |
Returns json feed . | def parse_json ( self , page ) : if not isinstance ( page , basestring ) : page = util . decode_page ( page ) self . doc = json . loads ( page ) results = self . doc . get ( self . result_name , [ ] ) if not results : self . check_status ( self . doc . get ( 'status' ) ) return None return results | 10,308 | https://github.com/walter426/Python_GoogleMapsApi/blob/4832b293a0027446941a5f00ecc66256f92ddbce/GoogleMapsApi/GoogleMapsServiceParser.py#L112-L125 | [
"def",
"get_storage",
"(",
"self",
",",
"name",
"=",
"'main'",
",",
"file_format",
"=",
"'pickle'",
",",
"TTL",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_unsynced_storages'",
")",
":",
"self",
".",
"_unsynced_storages",
"=",
"{",
"}",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"storage_path",
",",
"name",
")",
"try",
":",
"storage",
"=",
"self",
".",
"_unsynced_storages",
"[",
"filename",
"]",
"log",
".",
"debug",
"(",
"'Loaded storage \"%s\" from memory'",
",",
"name",
")",
"except",
"KeyError",
":",
"if",
"TTL",
":",
"TTL",
"=",
"timedelta",
"(",
"minutes",
"=",
"TTL",
")",
"try",
":",
"storage",
"=",
"TimedStorage",
"(",
"filename",
",",
"file_format",
",",
"TTL",
")",
"except",
"ValueError",
":",
"# Thrown when the storage file is corrupted and can't be read.",
"# Prompt user to delete storage.",
"choices",
"=",
"[",
"'Clear storage'",
",",
"'Cancel'",
"]",
"ret",
"=",
"xbmcgui",
".",
"Dialog",
"(",
")",
".",
"select",
"(",
"'A storage file is corrupted. It'",
"' is recommended to clear it.'",
",",
"choices",
")",
"if",
"ret",
"==",
"0",
":",
"os",
".",
"remove",
"(",
"filename",
")",
"storage",
"=",
"TimedStorage",
"(",
"filename",
",",
"file_format",
",",
"TTL",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Corrupted storage file at %s'",
"%",
"filename",
")",
"self",
".",
"_unsynced_storages",
"[",
"filename",
"]",
"=",
"storage",
"log",
".",
"debug",
"(",
"'Loaded storage \"%s\" from disk'",
",",
"name",
")",
"return",
"storage"
] |
Determine case type of string . | def _determine_case ( was_upper , words , string ) : case_type = 'unknown' if was_upper : case_type = 'upper' elif string . islower ( ) : case_type = 'lower' elif len ( words ) > 0 : camel_case = words [ 0 ] . islower ( ) pascal_case = words [ 0 ] . istitle ( ) or words [ 0 ] . isupper ( ) if camel_case or pascal_case : for word in words [ 1 : ] : c = word . istitle ( ) or word . isupper ( ) camel_case &= c pascal_case &= c if not c : break if camel_case : case_type = 'camel' elif pascal_case : case_type = 'pascal' else : case_type = 'mixed' return case_type | 10,309 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L15-L60 | [
"def",
"dump_webdriver_cookies_into_requestdriver",
"(",
"requestdriver",
",",
"webdriverwrapper",
")",
":",
"for",
"cookie",
"in",
"webdriverwrapper",
".",
"get_cookies",
"(",
")",
":",
"# Wedbriver uses \"expiry\"; requests uses \"expires\", adjust for this",
"expires",
"=",
"cookie",
".",
"pop",
"(",
"'expiry'",
",",
"{",
"'expiry'",
":",
"None",
"}",
")",
"cookie",
".",
"update",
"(",
"{",
"'expires'",
":",
"expires",
"}",
")",
"requestdriver",
".",
"session",
".",
"cookies",
".",
"set",
"(",
"*",
"*",
"cookie",
")"
] |
Detect acronyms by checking against a list of acronyms . | def _advanced_acronym_detection ( s , i , words , acronyms ) : # Combine each letter into single string. acstr = '' . join ( words [ s : i ] ) # List of ranges representing found acronyms. range_list = [ ] # Set of remaining letters. not_range = set ( range ( len ( acstr ) ) ) # Search for each acronym in acstr. for acronym in acronyms : # TODO: Sanitize acronyms to include only letters. rac = regex . compile ( unicode ( acronym ) ) # Loop until all instances of the acronym are found, # instead of just the first. n = 0 while True : m = rac . search ( acstr , n ) if not m : break a , b = m . start ( ) , m . end ( ) n = b # Make sure found acronym doesn't overlap with others. ok = True for r in range_list : if a < r [ 1 ] and b > r [ 0 ] : ok = False break if ok : range_list . append ( ( a , b ) ) for j in xrange ( a , b ) : not_range . remove ( j ) # Add remaining letters as ranges. for nr in not_range : range_list . append ( ( nr , nr + 1 ) ) # No ranges will overlap, so it's safe to sort by lower bound, # which sort() will do by default. range_list . sort ( ) # Remove original letters in word list. for _ in xrange ( s , i ) : del words [ s ] # Replace them with new word grouping. for j in xrange ( len ( range_list ) ) : r = range_list [ j ] words . insert ( s + j , acstr [ r [ 0 ] : r [ 1 ] ] ) return s + len ( range_list ) - 1 | 10,310 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L63-L123 | [
"def",
"stream_template",
"(",
"template_name",
",",
"*",
"*",
"context",
")",
":",
"app",
".",
"update_template_context",
"(",
"context",
")",
"template",
"=",
"app",
".",
"jinja_env",
".",
"get_template",
"(",
"template_name",
")",
"stream",
"=",
"template",
".",
"generate",
"(",
"context",
")",
"return",
"Response",
"(",
"stream_with_context",
"(",
"stream",
")",
")"
] |
Detect acronyms based on runs of upper - case letters . | def _simple_acronym_detection ( s , i , words , * args ) : # Combine each letter into a single string. acronym = '' . join ( words [ s : i ] ) # Remove original letters in word list. for _ in xrange ( s , i ) : del words [ s ] # Replace them with new word grouping. words . insert ( s , '' . join ( acronym ) ) return s | 10,311 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L126-L138 | [
"def",
"merged",
"(",
"self",
")",
":",
"stats",
"=",
"{",
"}",
"for",
"topic",
"in",
"self",
".",
"client",
".",
"topics",
"(",
")",
"[",
"'topics'",
"]",
":",
"for",
"producer",
"in",
"self",
".",
"client",
".",
"lookup",
"(",
"topic",
")",
"[",
"'producers'",
"]",
":",
"hostname",
"=",
"producer",
"[",
"'broadcast_address'",
"]",
"port",
"=",
"producer",
"[",
"'http_port'",
"]",
"host",
"=",
"'%s_%s'",
"%",
"(",
"hostname",
",",
"port",
")",
"stats",
"[",
"host",
"]",
"=",
"nsqd",
".",
"Client",
"(",
"'http://%s:%s/'",
"%",
"(",
"hostname",
",",
"port",
")",
")",
".",
"clean_stats",
"(",
")",
"return",
"stats"
] |
Check acronyms against regex . | def _sanitize_acronyms ( unsafe_acronyms ) : valid_acronym = regex . compile ( u'^[\p{Ll}\p{Lu}\p{Nd}]+$' ) acronyms = [ ] for a in unsafe_acronyms : if valid_acronym . match ( a ) : acronyms . append ( a . upper ( ) ) else : raise InvalidAcronymError ( a ) return acronyms | 10,312 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L150-L164 | [
"def",
"api_start",
"(",
"working_dir",
",",
"host",
",",
"port",
",",
"thread",
"=",
"True",
")",
":",
"api_srv",
"=",
"BlockstackdAPIServer",
"(",
"working_dir",
",",
"host",
",",
"port",
")",
"log",
".",
"info",
"(",
"\"Starting API server on port {}\"",
".",
"format",
"(",
"port",
")",
")",
"if",
"thread",
":",
"api_srv",
".",
"start",
"(",
")",
"return",
"api_srv"
] |
Normalize case of each word to PascalCase . | def _normalize_words ( words , acronyms ) : for i , _ in enumerate ( words ) : # if detect_acronyms: if words [ i ] . upper ( ) in acronyms : # Convert known acronyms to upper-case. words [ i ] = words [ i ] . upper ( ) else : # Fallback behavior: Preserve case on upper-case words. if not words [ i ] . isupper ( ) : words [ i ] = words [ i ] . capitalize ( ) return words | 10,313 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L167-L178 | [
"def",
"is_expired",
"(",
"self",
",",
"max_idle_seconds",
")",
":",
"now",
"=",
"current_time",
"(",
")",
"return",
"(",
"self",
".",
"expiration_time",
"is",
"not",
"None",
"and",
"self",
".",
"expiration_time",
"<",
"now",
")",
"or",
"(",
"max_idle_seconds",
"is",
"not",
"None",
"and",
"self",
".",
"last_access_time",
"+",
"max_idle_seconds",
"<",
"now",
")"
] |
Segment string on separator into list of words . | def _separate_words ( string ) : words = [ ] separator = "" # Index of current character. Initially 1 because we don't want to check # if the 0th character is a boundary. i = 1 # Index of first character in a sequence s = 0 # Previous character. p = string [ 0 : 1 ] # Treat an all-caps stringiable as lower-case, so that every letter isn't # counted as a boundary. was_upper = False if string . isupper ( ) : string = string . lower ( ) was_upper = True # Iterate over each character, checking for boundaries, or places where # the stringiable should divided. while i <= len ( string ) : c = string [ i : i + 1 ] split = False if i < len ( string ) : # Detect upper-case letter as boundary. if UPPER . match ( c ) : split = True # Detect transition from separator to not separator. elif NOTSEP . match ( c ) and SEP . match ( p ) : split = True # Detect transition not separator to separator. elif SEP . match ( c ) and NOTSEP . match ( p ) : split = True else : # The loop goes one extra iteration so that it can handle the # remaining text after the last boundary. split = True if split : if NOTSEP . match ( p ) : words . append ( string [ s : i ] ) else : # stringiable contains at least one separator. # Use the first one as the stringiable's primary separator. if not separator : separator = string [ s : s + 1 ] # Use None to indicate a separator in the word list. words . append ( None ) # If separators weren't included in the list, then breaks # between upper-case sequences ("AAA_BBB") would be # disregarded; the letter-run detector would count them as one # sequence ("AAABBB"). s = i i += 1 p = c return words , separator , was_upper | 10,314 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L181-L252 | [
"def",
"GenerateGaussianNoise",
"(",
"PSD",
")",
":",
"Noise",
"=",
"np",
".",
"zeros",
"(",
"(",
"N_fd",
")",
",",
"complex",
")",
"# Generate noise from PSD ",
"Real",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"N_fd",
")",
"*",
"np",
".",
"sqrt",
"(",
"PSD",
"/",
"(",
"4.",
"*",
"dF",
")",
")",
"Imag",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"N_fd",
")",
"*",
"np",
".",
"sqrt",
"(",
"PSD",
"/",
"(",
"4.",
"*",
"dF",
")",
")",
"Noise",
"=",
"Real",
"+",
"1j",
"*",
"Imag",
"return",
"Noise"
] |
Parse a stringiable into a list of words . | def parse_case ( string , acronyms = None , preserve_case = False ) : words , separator , was_upper = _separate_words ( string ) if acronyms : # Use advanced acronym detection with list acronyms = _sanitize_acronyms ( acronyms ) check_acronym = _advanced_acronym_detection else : acronyms = [ ] # Fallback to simple acronym detection. check_acronym = _simple_acronym_detection # Letter-run detector # Index of current word. i = 0 # Index of first letter in run. s = None # Find runs of single upper-case letters. while i < len ( words ) : word = words [ i ] if word is not None and UPPER . match ( word ) : if s is None : s = i elif s is not None : i = check_acronym ( s , i , words , acronyms ) + 1 s = None i += 1 if s is not None : check_acronym ( s , i , words , acronyms ) # Separators are no longer needed, so they can be removed. They *should* # be removed, since it's supposed to be a *word* list. words = [ w for w in words if w is not None ] # Determine case type. case_type = _determine_case ( was_upper , words , string ) if preserve_case : if was_upper : words = [ w . upper ( ) for w in words ] else : words = _normalize_words ( words , acronyms ) return words , case_type , separator | 10,315 | https://github.com/AlejandroFrias/case-conversion/blob/79ebce1403fbdac949b2da21b8f6fbe3234ddb31/case_conversion/case_parse.py#L255-L319 | [
"def",
"create_results_dirs",
"(",
"base_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"base_path",
")",
":",
"print",
"(",
"\"Creating directory {} for results data.\"",
".",
"format",
"(",
"base_path",
")",
")",
"os",
".",
"mkdir",
"(",
"base_path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'results'",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'results'",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'plots'",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'plots'",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'info'",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'info'",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'log'",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"'log'",
")",
")"
] |
Should be overwritten in the setup | def send_email ( self , user , subject , msg ) : print ( 'To:' , user ) print ( 'Subject:' , subject ) print ( msg ) | 10,316 | https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_views_mixin.py#L67-L71 | [
"def",
"seed",
"(",
"vault_client",
",",
"opt",
")",
":",
"if",
"opt",
".",
"thaw_from",
":",
"opt",
".",
"secrets",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'aomi-thaw'",
")",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
"Context",
".",
"load",
"(",
"get_secretfile",
"(",
"opt",
")",
",",
"opt",
")",
".",
"fetch",
"(",
"vault_client",
")",
".",
"sync",
"(",
"vault_client",
",",
"opt",
")",
"if",
"opt",
".",
"thaw_from",
":",
"rmtree",
"(",
"opt",
".",
"secrets",
")"
] |
Receive an update from the loaders . | def update ( self , new_data : IntentDict ) : for locale , data in new_data . items ( ) : if locale not in self . dict : self . dict [ locale ] = { } self . dict [ locale ] . update ( data ) | 10,317 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/intents.py#L52-L61 | [
"def",
"hicup_truncating_chart",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'Not_Truncated_Reads'",
"]",
"=",
"{",
"'color'",
":",
"'#2f7ed8'",
",",
"'name'",
":",
"'Not Truncated'",
"}",
"keys",
"[",
"'Truncated_Read'",
"]",
"=",
"{",
"'color'",
":",
"'#0d233a'",
",",
"'name'",
":",
"'Truncated'",
"}",
"# Construct a data structure for the plot - duplicate the samples for read 1 and read 2",
"data",
"=",
"{",
"}",
"for",
"s_name",
"in",
"self",
".",
"hicup_data",
":",
"data",
"[",
"'{} Read 1'",
".",
"format",
"(",
"s_name",
")",
"]",
"=",
"{",
"}",
"data",
"[",
"'{} Read 2'",
".",
"format",
"(",
"s_name",
")",
"]",
"=",
"{",
"}",
"data",
"[",
"'{} Read 1'",
".",
"format",
"(",
"s_name",
")",
"]",
"[",
"'Not_Truncated_Reads'",
"]",
"=",
"self",
".",
"hicup_data",
"[",
"s_name",
"]",
"[",
"'Not_Truncated_Reads_1'",
"]",
"data",
"[",
"'{} Read 2'",
".",
"format",
"(",
"s_name",
")",
"]",
"[",
"'Not_Truncated_Reads'",
"]",
"=",
"self",
".",
"hicup_data",
"[",
"s_name",
"]",
"[",
"'Not_Truncated_Reads_2'",
"]",
"data",
"[",
"'{} Read 1'",
".",
"format",
"(",
"s_name",
")",
"]",
"[",
"'Truncated_Read'",
"]",
"=",
"self",
".",
"hicup_data",
"[",
"s_name",
"]",
"[",
"'Truncated_Read_1'",
"]",
"data",
"[",
"'{} Read 2'",
".",
"format",
"(",
"s_name",
")",
"]",
"[",
"'Truncated_Read'",
"]",
"=",
"self",
".",
"hicup_data",
"[",
"s_name",
"]",
"[",
"'Truncated_Read_2'",
"]",
"# Config for the plot",
"config",
"=",
"{",
"'id'",
":",
"'hicup_truncated_reads_plot'",
",",
"'title'",
":",
"'HiCUP: Truncated Reads'",
",",
"'ylab'",
":",
"'# Reads'",
",",
"'cpswitch_counts_label'",
":",
"'Number of Reads'",
"}",
"return",
"bargraph",
".",
"plot",
"(",
"data",
",",
"keys",
",",
"config",
")"
] |
Get a single set of intents . | def get ( self , key : Text , locale : Optional [ Text ] ) -> List [ Tuple [ Text , ... ] ] : locale = self . choose_locale ( locale ) return self . dict [ locale ] [ key ] | 10,318 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/intents.py#L63-L70 | [
"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"
] |
For the given request find the list of strings of that intent . If the intent does not exist it will raise a KeyError . | async def strings ( self , request : Optional [ 'Request' ] = None ) -> List [ Tuple [ Text , ... ] ] : if request : locale = await request . get_locale ( ) else : locale = None return self . db . get ( self . key , locale ) | 10,319 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/intents.py#L90-L102 | [
"def",
"is_sync_table",
"(",
"self",
",",
"archive",
",",
"interval",
",",
"*",
"*",
"import_args",
")",
":",
"return",
"(",
"hasattr",
"(",
"archive",
",",
"\"startswith\"",
")",
"and",
"archive",
".",
"startswith",
"(",
"\"http\"",
")",
"or",
"\"connection\"",
"in",
"import_args",
")",
"and",
"interval",
"is",
"not",
"None"
] |
Returns a list of valid standard_names that are allowed to be unitless | def get_unitless_standard_names ( ) : global _UNITLESS_DB if _UNITLESS_DB is None : with open ( resource_filename ( 'cc_plugin_ncei' , 'data/unitless.json' ) , 'r' ) as f : _UNITLESS_DB = json . load ( f ) return _UNITLESS_DB | 10,320 | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/util.py#L16-L24 | [
"def",
"calc_fft_with_PyCUDA",
"(",
"Signal",
")",
":",
"print",
"(",
"\"starting fft\"",
")",
"Signal",
"=",
"Signal",
".",
"astype",
"(",
"_np",
".",
"float32",
")",
"Signal_gpu",
"=",
"_gpuarray",
".",
"to_gpu",
"(",
"Signal",
")",
"Signalfft_gpu",
"=",
"_gpuarray",
".",
"empty",
"(",
"len",
"(",
"Signal",
")",
"//",
"2",
"+",
"1",
",",
"_np",
".",
"complex64",
")",
"plan",
"=",
"_Plan",
"(",
"Signal",
".",
"shape",
",",
"_np",
".",
"float32",
",",
"_np",
".",
"complex64",
")",
"_fft",
"(",
"Signal_gpu",
",",
"Signalfft_gpu",
",",
"plan",
")",
"Signalfft",
"=",
"Signalfft_gpu",
".",
"get",
"(",
")",
"#only 2N+1 long",
"Signalfft",
"=",
"_np",
".",
"hstack",
"(",
"(",
"Signalfft",
",",
"_np",
".",
"conj",
"(",
"_np",
".",
"flipud",
"(",
"Signalfft",
"[",
"1",
":",
"len",
"(",
"Signal",
")",
"//",
"2",
"]",
")",
")",
")",
")",
"print",
"(",
"\"fft done\"",
")",
"return",
"Signalfft"
] |
Returns the variable for latitude | def get_lat_variable ( nc ) : if 'latitude' in nc . variables : return 'latitude' latitudes = nc . get_variables_by_attributes ( standard_name = "latitude" ) if latitudes : return latitudes [ 0 ] . name return None | 10,321 | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/util.py#L111-L122 | [
"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",
")"
] |
Returns the variable for longitude | def get_lon_variable ( nc ) : if 'longitude' in nc . variables : return 'longitude' longitudes = nc . get_variables_by_attributes ( standard_name = "longitude" ) if longitudes : return longitudes [ 0 ] . name return None | 10,322 | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/util.py#L125-L136 | [
"def",
"set_options",
"(",
"cls",
",",
"obj",
",",
"options",
"=",
"None",
",",
"backend",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note that an alternate, more verbose and less recommended",
"# syntax can also be used:",
"# {'Image.Channel:{'plot': Options(size=50),",
"# 'style': Options('style', cmap='Blues')]}",
"options",
"=",
"cls",
".",
"merge_options",
"(",
"Store",
".",
"options",
"(",
"backend",
"=",
"backend",
")",
".",
"groups",
".",
"keys",
"(",
")",
",",
"options",
",",
"*",
"*",
"kwargs",
")",
"spec",
",",
"compositor_applied",
"=",
"cls",
".",
"expand_compositor_keys",
"(",
"options",
")",
"custom_trees",
",",
"id_mapping",
"=",
"cls",
".",
"create_custom_trees",
"(",
"obj",
",",
"spec",
")",
"cls",
".",
"update_backends",
"(",
"id_mapping",
",",
"custom_trees",
",",
"backend",
"=",
"backend",
")",
"# Propagate ids to the objects",
"not_used",
"=",
"[",
"]",
"for",
"(",
"match_id",
",",
"new_id",
")",
"in",
"id_mapping",
":",
"applied",
"=",
"cls",
".",
"propagate_ids",
"(",
"obj",
",",
"match_id",
",",
"new_id",
",",
"compositor_applied",
"+",
"list",
"(",
"spec",
".",
"keys",
"(",
")",
")",
",",
"backend",
"=",
"backend",
")",
"if",
"not",
"applied",
":",
"not_used",
".",
"append",
"(",
"new_id",
")",
"# Clean up unused custom option trees",
"for",
"new_id",
"in",
"set",
"(",
"not_used",
")",
":",
"cleanup_custom_options",
"(",
"new_id",
")",
"return",
"obj"
] |
Returns the name of the variable identified by a grid_mapping attribute | def get_crs_variable ( ds ) : for var in ds . variables : grid_mapping = getattr ( ds . variables [ var ] , 'grid_mapping' , '' ) if grid_mapping and grid_mapping in ds . variables : return grid_mapping return None | 10,323 | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/util.py#L200-L210 | [
"def",
"_validate_fetch",
"(",
"self",
")",
":",
"for",
"url",
",",
"file_size",
",",
"filename",
"in",
"self",
".",
"fetch_entries",
"(",
")",
":",
"# fetch_entries will raise a BagError for unsafe filenames",
"# so at this point we will check only that the URL is minimally",
"# well formed:",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"# only check for a scheme component since per the spec the URL field is actually a URI per",
"# RFC3986 (https://tools.ietf.org/html/rfc3986)",
"if",
"not",
"all",
"(",
"parsed_url",
".",
"scheme",
")",
":",
"raise",
"BagError",
"(",
"_",
"(",
"'Malformed URL in fetch.txt: %s'",
")",
"%",
"url",
")"
] |
Returns True if the variable is a 2D Regular grid . | def is_2d_regular_grid ( nc , variable ) : # x(x), y(y), t(t) # X(t, y, x) dims = nc . variables [ variable ] . dimensions cmatrix = coordinate_dimension_matrix ( nc ) for req in ( 'x' , 'y' , 't' ) : if req not in cmatrix : return False x = get_lon_variable ( nc ) y = get_lat_variable ( nc ) t = get_time_variable ( nc ) if cmatrix [ 'x' ] != ( x , ) : return False if cmatrix [ 'y' ] != ( y , ) : return False if cmatrix [ 't' ] != ( t , ) : return False # Relaxed dimension ordering if len ( dims ) == 3 and x in dims and y in dims and t in dims : return True return False | 10,324 | https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/util.py#L804-L836 | [
"def",
"__best_intent",
"(",
"self",
",",
"parse_result",
",",
"context",
"=",
"[",
"]",
")",
":",
"best_intent",
"=",
"None",
"best_tags",
"=",
"None",
"context_as_entities",
"=",
"[",
"{",
"'entities'",
":",
"[",
"c",
"]",
"}",
"for",
"c",
"in",
"context",
"]",
"for",
"intent",
"in",
"self",
".",
"intent_parsers",
":",
"i",
",",
"tags",
"=",
"intent",
".",
"validate_with_tags",
"(",
"parse_result",
".",
"get",
"(",
"'tags'",
")",
"+",
"context_as_entities",
",",
"parse_result",
".",
"get",
"(",
"'confidence'",
")",
")",
"if",
"not",
"best_intent",
"or",
"(",
"i",
"and",
"i",
".",
"get",
"(",
"'confidence'",
")",
">",
"best_intent",
".",
"get",
"(",
"'confidence'",
")",
")",
":",
"best_intent",
"=",
"i",
"best_tags",
"=",
"tags",
"return",
"best_intent",
",",
"best_tags"
] |
handles reading repo information | def handle_read ( repo , * * kwargs ) : log . info ( 'read: %s %s' % ( repo , kwargs ) ) if type ( repo ) in [ unicode , str ] : return { 'name' : 'Repo' , 'desc' : 'Welcome to Grit' , 'comment' : '' } else : return repo . serialize ( ) | 10,325 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/handler.py#L24-L30 | [
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Convert a object into dictionary with all of its readable attributes . | def dict_from_object ( obj : object ) : # If object is a dict instance, no need to convert. return ( obj if isinstance ( obj , dict ) else { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( '_' ) } ) | 10,326 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_utils.py#L13-L19 | [
"def",
"delete_email_marketing_campaign",
"(",
"self",
",",
"email_marketing_campaign",
")",
":",
"url",
"=",
"self",
".",
"api",
".",
"join",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"EMAIL_MARKETING_CAMPAIGN_URL",
",",
"str",
"(",
"email_marketing_campaign",
".",
"constant_contact_id",
")",
"]",
")",
")",
"response",
"=",
"url",
".",
"delete",
"(",
")",
"self",
".",
"handle_response_status",
"(",
"response",
")",
"return",
"response"
] |
Get attribute value from object . | def xgetattr ( obj : object , name : str , default = _sentinel , getitem = False ) : if isinstance ( obj , dict ) : if getitem : # In tune with `dict.__getitem__` method. return obj [ name ] else : # In tune with `dict.get` method. val = obj . get ( name , default ) return None if val is _sentinel else val else : # If object is not a dict, in tune with `getattr` method. val = getattr ( obj , name , default ) if val is _sentinel : msg = '%r object has no attribute %r' % ( obj . __class__ , name ) raise AttributeError ( msg ) else : return val | 10,327 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_utils.py#L22-L48 | [
"def",
"update_sandbox_product",
"(",
"self",
",",
"product_id",
",",
"surge_multiplier",
"=",
"None",
",",
"drivers_available",
"=",
"None",
",",
")",
":",
"args",
"=",
"{",
"'surge_multiplier'",
":",
"surge_multiplier",
",",
"'drivers_available'",
":",
"drivers_available",
",",
"}",
"endpoint",
"=",
"'v1.2/sandbox/products/{}'",
".",
"format",
"(",
"product_id",
")",
"return",
"self",
".",
"_api_call",
"(",
"'PUT'",
",",
"endpoint",
",",
"args",
"=",
"args",
")"
] |
This function returns the list of configuration files to load . | def list_config_files ( ) -> List [ Text ] : return [ os . path . join ( os . path . dirname ( __file__ ) , 'default_settings.py' ) , os . getenv ( ENVIRONMENT_VARIABLE , '' ) , ] | 10,328 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/conf/__init__.py#L15-L26 | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"return",
"Event",
".",
"objects",
".",
"filter",
"(",
"Q",
"(",
"startTime__gte",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"days",
"=",
"90",
")",
")",
"&",
"(",
"Q",
"(",
"series__isnull",
"=",
"False",
")",
"|",
"Q",
"(",
"publicevent__isnull",
"=",
"False",
")",
")",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'eventregistration'",
")",
")",
".",
"annotate",
"(",
"*",
"*",
"self",
".",
"get_annotations",
"(",
")",
")",
".",
"exclude",
"(",
"Q",
"(",
"count",
"=",
"0",
")",
"&",
"Q",
"(",
"status__in",
"=",
"[",
"Event",
".",
"RegStatus",
".",
"hidden",
",",
"Event",
".",
"RegStatus",
".",
"regHidden",
",",
"Event",
".",
"RegStatus",
".",
"disabled",
"]",
")",
")"
] |
Takes a camelCased string and converts to snake_case . | def camel_to_snake_case ( name ) : pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])' return '_' . join ( map ( str . lower , re . findall ( pattern , name ) ) ) | 10,329 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L10-L13 | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_md",
".",
"update",
"(",
"data",
")",
"bufpos",
"=",
"self",
".",
"_nbytes",
"&",
"63",
"self",
".",
"_nbytes",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_rarbug",
"and",
"len",
"(",
"data",
")",
">",
"64",
":",
"dpos",
"=",
"self",
".",
"block_size",
"-",
"bufpos",
"while",
"dpos",
"+",
"self",
".",
"block_size",
"<=",
"len",
"(",
"data",
")",
":",
"self",
".",
"_corrupt",
"(",
"data",
",",
"dpos",
")",
"dpos",
"+=",
"self",
".",
"block_size"
] |
Check if the line starts with given prefix and return the position of the end of prefix . If the prefix is not matched return - 1 . | def match_prefix ( prefix , line ) : m = re . match ( prefix , line . expandtabs ( 4 ) ) if not m : if re . match ( prefix , line . expandtabs ( 4 ) . replace ( '\n' , ' ' * 99 + '\n' ) ) : return len ( line ) - 1 return - 1 pos = m . end ( ) if pos == 0 : return 0 for i in range ( 1 , len ( line ) + 1 ) : if len ( line [ : i ] . expandtabs ( 4 ) ) >= pos : return i | 10,330 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L101-L116 | [
"def",
"SetHeaders",
"(",
"self",
",",
"soap_headers",
",",
"http_headers",
")",
":",
"self",
".",
"suds_client",
".",
"set_options",
"(",
"soapheaders",
"=",
"soap_headers",
",",
"headers",
"=",
"http_headers",
")"
] |
Test against the given regular expression and returns the match object . | def expect_re ( self , regexp ) : prefix_len = self . match_prefix ( self . prefix , self . next_line ( require_prefix = False ) ) if prefix_len >= 0 : match = self . _expect_re ( regexp , self . pos + prefix_len ) self . match = match return match else : return None | 10,331 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L118-L132 | [
"def",
"api_start",
"(",
"working_dir",
",",
"host",
",",
"port",
",",
"thread",
"=",
"True",
")",
":",
"api_srv",
"=",
"BlockstackdAPIServer",
"(",
"working_dir",
",",
"host",
",",
"port",
")",
"log",
".",
"info",
"(",
"\"Starting API server on port {}\"",
".",
"format",
"(",
"port",
")",
")",
"if",
"thread",
":",
"api_srv",
".",
"start",
"(",
")",
"return",
"api_srv"
] |
Return the next line in the source . | def next_line ( self , require_prefix = True ) : if require_prefix : m = self . expect_re ( r'(?m)[^\n]*?$\n?' ) else : m = self . _expect_re ( r'(?m)[^\n]*$\n?' , self . pos ) self . match = m if m : return m . group ( ) | 10,332 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L134-L147 | [
"def",
"_get_broadcast_shape",
"(",
"shape1",
",",
"shape2",
")",
":",
"if",
"shape1",
"==",
"shape2",
":",
"return",
"shape1",
"length1",
"=",
"len",
"(",
"shape1",
")",
"length2",
"=",
"len",
"(",
"shape2",
")",
"if",
"length1",
">",
"length2",
":",
"shape",
"=",
"list",
"(",
"shape1",
")",
"else",
":",
"shape",
"=",
"list",
"(",
"shape2",
")",
"i",
"=",
"max",
"(",
"length1",
",",
"length2",
")",
"-",
"1",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"shape1",
"[",
":",
":",
"-",
"1",
"]",
",",
"shape2",
"[",
":",
":",
"-",
"1",
"]",
")",
":",
"if",
"a",
"!=",
"1",
"and",
"b",
"!=",
"1",
"and",
"a",
"!=",
"b",
":",
"raise",
"ValueError",
"(",
"'shape1=%s is not broadcastable to shape2=%s'",
"%",
"(",
"shape1",
",",
"shape2",
")",
")",
"shape",
"[",
"i",
"]",
"=",
"max",
"(",
"a",
",",
"b",
")",
"i",
"-=",
"1",
"return",
"tuple",
"(",
"shape",
")"
] |
Consume the body of source . pos will move forward . | def consume ( self ) : if self . match : self . pos = self . match . end ( ) if self . match . group ( ) [ - 1 ] == '\n' : self . _update_prefix ( ) self . match = None | 10,333 | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/helpers.py#L149-L155 | [
"def",
"_update_secret",
"(",
"namespace",
",",
"name",
",",
"data",
",",
"apiserver_url",
")",
":",
"# Prepare URL",
"url",
"=",
"\"{0}/api/v1/namespaces/{1}/secrets/{2}\"",
".",
"format",
"(",
"apiserver_url",
",",
"namespace",
",",
"name",
")",
"# Prepare data",
"data",
"=",
"[",
"{",
"\"op\"",
":",
"\"replace\"",
",",
"\"path\"",
":",
"\"/data\"",
",",
"\"value\"",
":",
"data",
"}",
"]",
"# Make request",
"ret",
"=",
"_kpatch",
"(",
"url",
",",
"data",
")",
"if",
"ret",
".",
"get",
"(",
"\"status\"",
")",
"==",
"404",
":",
"return",
"\"Node {0} doesn't exist\"",
".",
"format",
"(",
"url",
")",
"return",
"ret"
] |
asDict - Returns a copy of the current state as a dictionary . This copy will not be updated automatically . | def asDict ( self ) : ret = { } for field in BackgroundTaskInfo . FIELDS : ret [ field ] = getattr ( self , field ) return ret | 10,334 | https://github.com/kata198/python-subprocess2/blob/8544b0b651d8e14de9fdd597baa704182e248b01/subprocess2/BackgroundTask.py#L84-L93 | [
"def",
"mark_broker_action_done",
"(",
"action",
",",
"rid",
"=",
"None",
",",
"unit",
"=",
"None",
")",
":",
"rdata",
"=",
"relation_get",
"(",
"rid",
",",
"unit",
")",
"or",
"{",
"}",
"broker_rsp",
"=",
"rdata",
".",
"get",
"(",
"get_broker_rsp_key",
"(",
")",
")",
"if",
"not",
"broker_rsp",
":",
"return",
"rsp",
"=",
"CephBrokerRsp",
"(",
"broker_rsp",
")",
"unit_name",
"=",
"local_unit",
"(",
")",
".",
"partition",
"(",
"'/'",
")",
"[",
"2",
"]",
"key",
"=",
"\"unit_{}_ceph_broker_action.{}\"",
".",
"format",
"(",
"unit_name",
",",
"action",
")",
"kvstore",
"=",
"kv",
"(",
")",
"kvstore",
".",
"set",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"rsp",
".",
"request_id",
")",
"kvstore",
".",
"flush",
"(",
")"
] |
A decorator used for register custom check . | def register ( name , _callable = None ) : def wrapper ( _callable ) : registered_checks [ name ] = _callable return _callable # If function or class is given, do the registeration if _callable : return wrapper ( _callable ) return wrapper | 10,335 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/checks.py#L177-L193 | [
"def",
"Initialize",
"(",
"self",
")",
":",
"super",
"(",
"AFF4MemoryStreamBase",
",",
"self",
")",
".",
"Initialize",
"(",
")",
"contents",
"=",
"b\"\"",
"if",
"\"r\"",
"in",
"self",
".",
"mode",
":",
"contents",
"=",
"self",
".",
"Get",
"(",
"self",
".",
"Schema",
".",
"CONTENT",
")",
".",
"AsBytes",
"(",
")",
"try",
":",
"if",
"contents",
"is",
"not",
"None",
":",
"contents",
"=",
"zlib",
".",
"decompress",
"(",
"contents",
")",
"except",
"zlib",
".",
"error",
":",
"pass",
"self",
".",
"fd",
"=",
"io",
".",
"BytesIO",
"(",
"contents",
")",
"self",
".",
"size",
"=",
"len",
"(",
"contents",
")",
"self",
".",
"offset",
"=",
"0"
] |
Generates the messaging - type - related part of the message dictionary . | def serialize ( self ) : if self . response is not None : return { 'messaging_type' : 'RESPONSE' } if self . update is not None : return { 'messaging_type' : 'UPDATE' } if self . tag is not None : return { 'messaging_type' : 'MESSAGE_TAG' , 'tag' : self . tag . value , } if self . subscription is not None : return { 'messaging_type' : 'NON_PROMOTIONAL_SUBSCRIPTION' } | 10,336 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/layers.py#L102-L120 | [
"def",
"cublasGetStream",
"(",
"handle",
")",
":",
"id",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcublas",
".",
"cublasGetStream_v2",
"(",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"id",
")",
")",
"cublasCheckStatus",
"(",
"status",
")",
"return",
"id",
".",
"value"
] |
Store all options in the choices sub - register . We store both the text and the potential intent in order to match both regular quick reply clicks but also the user typing stuff on his keyboard that matches more or less the content of quick replies . | async def patch_register ( self , register : Dict , request : 'Request' ) : register [ 'choices' ] = { o . slug : { 'intent' : o . intent . key if o . intent else None , 'text' : await render ( o . text , request ) , } for o in self . options if isinstance ( o , QuickRepliesList . TextOption ) } return register | 10,337 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/layers.py#L198-L214 | [
"def",
"clear_weights",
"(",
"self",
")",
":",
"self",
".",
"weighted",
"=",
"False",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"layer",
".",
"weights",
"=",
"None"
] |
Can only be sharable if marked as such and no child element is blocking sharing due to security reasons . | def is_sharable ( self ) : return bool ( self . sharable and all ( x . is_sharable ( ) for x in self . elements ) ) | 10,338 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/layers.py#L289-L297 | [
"def",
"run_main_error_group",
"(",
")",
":",
"test",
"=",
"htf",
".",
"Test",
"(",
"htf",
".",
"PhaseGroup",
"(",
"setup",
"=",
"[",
"setup_phase",
"]",
",",
"main",
"=",
"[",
"error_main_phase",
",",
"main_phase",
"]",
",",
"teardown",
"=",
"[",
"teardown_phase",
"]",
",",
")",
")",
"test",
".",
"execute",
"(",
")"
] |
Return the EChoice object associated with this value if any . | def from_value ( cls , value ) : warnings . warn ( "{0}.{1} will be deprecated in a future release. " "Please use {0}.{2} instead" . format ( cls . __name__ , cls . from_value . __name__ , cls . get . __name__ ) , PendingDeprecationWarning ) return cls [ value ] | 10,339 | https://github.com/mbourqui/django-echoices/blob/c57405005ec368ac602bb38a71091a1e03c723bb/echoices/enums/enums.py#L165-L187 | [
"def",
"feed",
"(",
"self",
",",
"data_len",
",",
"feed_time",
"=",
"None",
")",
":",
"self",
".",
"_bytes_transferred",
"+=",
"data_len",
"self",
".",
"_collected_bytes_transferred",
"+=",
"data_len",
"time_now",
"=",
"feed_time",
"or",
"time",
".",
"time",
"(",
")",
"time_diff",
"=",
"time_now",
"-",
"self",
".",
"_last_feed_time",
"if",
"time_diff",
"<",
"self",
".",
"_sample_min_time",
":",
"return",
"self",
".",
"_last_feed_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"data_len",
"==",
"0",
"and",
"time_diff",
">=",
"self",
".",
"_stall_time",
":",
"self",
".",
"_stalled",
"=",
"True",
"return",
"self",
".",
"_samples",
".",
"append",
"(",
"(",
"time_diff",
",",
"self",
".",
"_collected_bytes_transferred",
")",
")",
"self",
".",
"_collected_bytes_transferred",
"=",
"0"
] |
Authenticates the users based on the query - string - provided token | def bernard_auth ( func ) : @ wraps ( func ) async def wrapper ( request : Request ) : def get_query_token ( ) : token_key = settings . WEBVIEW_TOKEN_KEY return request . query . get ( token_key , '' ) def get_header_token ( ) : header_key = settings . WEBVIEW_HEADER_NAME return request . headers . get ( header_key , '' ) try : token = next ( filter ( None , [ get_header_token ( ) , get_query_token ( ) , ] ) ) except StopIteration : token = '' try : body = await request . json ( ) except ValueError : body = None msg , platform = await manager . message_from_token ( token , body ) if not msg : return json_response ( { 'status' : 'unauthorized' , 'message' : 'No valid token found' , } , status = 401 ) return await func ( msg , platform ) return wrapper | 10,340 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/server/views.py#L37-L74 | [
"def",
"writearff",
"(",
"data",
",",
"filename",
",",
"relation_name",
"=",
"None",
",",
"index",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"relation_name",
"is",
"None",
":",
"relation_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"else",
":",
"fp",
"=",
"filename",
"if",
"relation_name",
"is",
"None",
":",
"relation_name",
"=",
"\"pandas\"",
"try",
":",
"data",
"=",
"_write_header",
"(",
"data",
",",
"fp",
",",
"relation_name",
",",
"index",
")",
"fp",
".",
"write",
"(",
"\"\\n\"",
")",
"_write_data",
"(",
"data",
",",
"fp",
")",
"finally",
":",
"fp",
".",
"close",
"(",
")"
] |
Provides the front - end with details about the user . This output can be completed using the api_postback_me middleware hook . | async def postback_me ( msg : BaseMessage , platform : Platform ) -> Response : async def get_basic_info ( _msg : BaseMessage , _platform : Platform ) : user = _msg . get_user ( ) return { 'friendly_name' : await user . get_friendly_name ( ) , 'locale' : await user . get_locale ( ) , 'platform' : _platform . NAME , } func = MiddlewareManager . instance ( ) . get ( 'api_postback_me' , get_basic_info ) return json_response ( await func ( msg , platform ) ) | 10,341 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/server/views.py#L78-L95 | [
"def",
"saturation",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"clean_float",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"unit_moisture_weight",
"=",
"self",
".",
"unit_moist_weight",
"-",
"self",
".",
"unit_dry_weight",
"unit_moisture_volume",
"=",
"unit_moisture_weight",
"/",
"self",
".",
"_pw",
"saturation",
"=",
"unit_moisture_volume",
"/",
"self",
".",
"_calc_unit_void_volume",
"(",
")",
"if",
"saturation",
"is",
"not",
"None",
"and",
"not",
"ct",
".",
"isclose",
"(",
"saturation",
",",
"value",
",",
"rel_tol",
"=",
"self",
".",
"_tolerance",
")",
":",
"raise",
"ModelError",
"(",
"\"New saturation (%.3f) is inconsistent \"",
"\"with calculated value (%.3f)\"",
"%",
"(",
"value",
",",
"saturation",
")",
")",
"except",
"TypeError",
":",
"pass",
"old_value",
"=",
"self",
".",
"saturation",
"self",
".",
"_saturation",
"=",
"value",
"try",
":",
"self",
".",
"recompute_all_weights_and_void",
"(",
")",
"self",
".",
"_add_to_stack",
"(",
"\"saturation\"",
",",
"value",
")",
"except",
"ModelError",
"as",
"e",
":",
"self",
".",
"_saturation",
"=",
"old_value",
"raise",
"ModelError",
"(",
"e",
")"
] |
Injects the POST body into the FSM as a Postback message . | async def postback_send ( msg : BaseMessage , platform : Platform ) -> Response : await platform . inject_message ( msg ) return json_response ( { 'status' : 'ok' , } ) | 10,342 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/server/views.py#L99-L108 | [
"def",
"distance",
"(",
"self",
",",
"other",
"=",
"None",
")",
":",
"t",
"=",
"0",
"if",
"other",
"is",
"None",
":",
"other",
"=",
"self",
".",
"__class__",
"(",
")",
"for",
"axisName",
"in",
"set",
"(",
"self",
".",
"keys",
"(",
")",
")",
"|",
"set",
"(",
"other",
".",
"keys",
"(",
")",
")",
":",
"t",
"+=",
"(",
"other",
".",
"get",
"(",
"axisName",
",",
"0",
")",
"-",
"self",
".",
"get",
"(",
"axisName",
",",
"0",
")",
")",
"**",
"2",
"return",
"math",
".",
"sqrt",
"(",
"t",
")"
] |
Makes a call to an analytics function . | async def postback_analytics ( msg : BaseMessage , platform : Platform ) -> Response : try : pb = msg . get_layers ( ) [ 0 ] assert isinstance ( pb , Postback ) user = msg . get_user ( ) user_lang = await user . get_locale ( ) user_id = user . id if pb . payload [ 'event' ] == 'page_view' : func = 'page_view' path = pb . payload [ 'path' ] title = pb . payload . get ( 'title' , '' ) args = [ path , title , user_id , user_lang ] else : return json_response ( { 'status' : 'unknown event' , 'message' : f'"{pb.payload["event"]}" is not a recognized ' f'analytics event' , } ) async for p in providers ( ) : await getattr ( p , func ) ( * args ) except ( KeyError , IndexError , AssertionError , TypeError ) : return json_response ( { 'status' : 'missing data' } , status = 400 ) else : return json_response ( { 'status' : 'ok' , } ) | 10,343 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/server/views.py#L112-L148 | [
"def",
"delete_attachments",
"(",
"self",
",",
"volumeID",
",",
"attachmentsID",
")",
":",
"log",
".",
"debug",
"(",
"\"deleting attachments from volume '{}': {}\"",
".",
"format",
"(",
"volumeID",
",",
"attachmentsID",
")",
")",
"rawVolume",
"=",
"self",
".",
"_req_raw_volume",
"(",
"volumeID",
")",
"insID",
"=",
"[",
"a",
"[",
"'id'",
"]",
"for",
"a",
"in",
"rawVolume",
"[",
"'_source'",
"]",
"[",
"'_attachments'",
"]",
"]",
"# check that all requested file are present",
"for",
"id",
"in",
"attachmentsID",
":",
"if",
"id",
"not",
"in",
"insID",
":",
"raise",
"NotFoundException",
"(",
"\"could not found attachment '{}' of the volume '{}'\"",
".",
"format",
"(",
"id",
",",
"volumeID",
")",
")",
"for",
"index",
",",
"id",
"in",
"enumerate",
"(",
"attachmentsID",
")",
":",
"rawVolume",
"[",
"'_source'",
"]",
"[",
"'_attachments'",
"]",
".",
"pop",
"(",
"insID",
".",
"index",
"(",
"id",
")",
")",
"self",
".",
"_db",
".",
"modify_book",
"(",
"volumeID",
",",
"rawVolume",
"[",
"'_source'",
"]",
",",
"version",
"=",
"rawVolume",
"[",
"'_version'",
"]",
")"
] |
Function or decorator which registers a given function as a recognized control command . | def register ( name , func = None ) : def decorator ( func ) : # Perform the registration ControlDaemon . _register ( name , func ) return func # If func was given, call the decorator, otherwise, return the # decorator if func : return decorator ( func ) else : return decorator | 10,344 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L288-L304 | [
"def",
"debug_dump",
"(",
"message",
",",
"file_prefix",
"=",
"\"dump\"",
")",
":",
"global",
"index",
"index",
"+=",
"1",
"with",
"open",
"(",
"\"%s_%s.dump\"",
"%",
"(",
"file_prefix",
",",
"index",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"message",
".",
"SerializeToString",
"(",
")",
")",
"f",
".",
"close",
"(",
")"
] |
Process the ping control message . | def ping ( daemon , channel , data = None ) : if not channel : # No place to reply to return # Get our configured node name node_name = daemon . config [ 'control' ] . get ( 'node_name' ) # Format the response reply = [ 'pong' ] if node_name or data : reply . append ( node_name or '' ) if data : reply . append ( data ) # And send it with utils . ignore_except ( ) : daemon . db . publish ( channel , ':' . join ( reply ) ) | 10,345 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L308-L340 | [
"def",
"get_chinese_new_year",
"(",
"self",
",",
"year",
")",
":",
"days",
"=",
"[",
"]",
"lunar_first_day",
"=",
"ChineseNewYearCalendar",
".",
"lunar",
"(",
"year",
",",
"1",
",",
"1",
")",
"# Chinese new year's eve",
"if",
"self",
".",
"include_chinese_new_year_eve",
":",
"days",
".",
"append",
"(",
"(",
"lunar_first_day",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"self",
".",
"chinese_new_year_eve_label",
")",
")",
"# Chinese new year (is included by default)",
"if",
"self",
".",
"include_chinese_new_year",
":",
"days",
".",
"append",
"(",
"(",
"lunar_first_day",
",",
"self",
".",
"chinese_new_year_label",
")",
")",
"if",
"self",
".",
"include_chinese_second_day",
":",
"lunar_second_day",
"=",
"lunar_first_day",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
"days",
".",
"append",
"(",
"(",
"lunar_second_day",
",",
"self",
".",
"chinese_second_day_label",
")",
")",
"if",
"self",
".",
"include_chinese_third_day",
":",
"lunar_third_day",
"=",
"lunar_first_day",
"+",
"timedelta",
"(",
"days",
"=",
"2",
")",
"days",
".",
"append",
"(",
"(",
"lunar_third_day",
",",
"self",
".",
"chinese_third_day_label",
")",
")",
"if",
"self",
".",
"shift_sunday_holidays",
":",
"if",
"lunar_first_day",
".",
"weekday",
"(",
")",
"==",
"SUN",
":",
"if",
"self",
".",
"shift_start_cny_sunday",
":",
"days",
".",
"append",
"(",
"(",
"lunar_first_day",
"-",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"\"Chinese Lunar New Year shift\"",
")",
",",
")",
"else",
":",
"if",
"self",
".",
"include_chinese_third_day",
":",
"shift_day",
"=",
"lunar_third_day",
"else",
":",
"shift_day",
"=",
"lunar_second_day",
"days",
".",
"append",
"(",
"(",
"shift_day",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"\"Chinese Lunar New Year shift\"",
")",
",",
")",
"if",
"(",
"lunar_second_day",
".",
"weekday",
"(",
")",
"==",
"SUN",
"and",
"self",
".",
"include_chinese_third_day",
")",
":",
"days",
".",
"append",
"(",
"(",
"lunar_third_day",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
",",
"\"Chinese Lunar New Year shift\"",
")",
",",
")",
"return",
"days"
] |
Process the reload control message . | def reload ( daemon , load_type = None , spread = None ) : # Figure out what type of reload this needs to be if load_type == 'immediate' : spread = None elif load_type == 'spread' : try : spread = float ( spread ) except ( TypeError , ValueError ) : # Not a valid float; use the configured spread value load_type = None else : load_type = None if load_type is None : # Use configured set-up; see if we have a spread # configured try : spread = float ( daemon . config [ 'control' ] [ 'reload_spread' ] ) except ( TypeError , ValueError , KeyError ) : # No valid configuration spread = None if spread : # Apply a randomization to spread the load around eventlet . spawn_after ( random . random ( ) * spread , daemon . reload ) else : # Spawn in immediate mode eventlet . spawn_n ( daemon . reload ) | 10,346 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L344-L396 | [
"def",
"bind",
"(",
"self",
",",
"prefix",
":",
"str",
",",
"namespace",
":",
"str",
",",
"override",
"=",
"True",
",",
"replace",
"=",
"False",
")",
":",
"namespace",
"=",
"URIRef",
"(",
"str",
"(",
"namespace",
")",
")",
"# When documenting explain that override only applies in what cases",
"if",
"prefix",
"is",
"None",
":",
"prefix",
"=",
"''",
"bound_namespace",
"=",
"self",
".",
"store",
".",
"namespace",
"(",
"prefix",
")",
"# Check if the bound_namespace contains a URI and if so convert it into a URIRef for",
"# comparison. This is to prevent duplicate namespaces with the same URI.",
"if",
"bound_namespace",
":",
"bound_namespace",
"=",
"URIRef",
"(",
"bound_namespace",
")",
"if",
"bound_namespace",
"and",
"bound_namespace",
"!=",
"namespace",
":",
"if",
"replace",
":",
"self",
".",
"store",
".",
"bind",
"(",
"prefix",
",",
"namespace",
")",
"# prefix already in use for different namespace",
"raise",
"PrefixAlreadyUsedException",
"(",
"\"Prefix (%s, %s) already used, instead of (%s, %s).\"",
",",
"prefix",
",",
"self",
".",
"store",
".",
"namespace",
"(",
"prefix",
")",
".",
"toPython",
"(",
")",
",",
"prefix",
",",
"namespace",
".",
"toPython",
"(",
")",
")",
"else",
":",
"bound_prefix",
"=",
"self",
".",
"store",
".",
"prefix",
"(",
"namespace",
")",
"if",
"bound_prefix",
"is",
"None",
":",
"self",
".",
"store",
".",
"bind",
"(",
"prefix",
",",
"namespace",
")",
"elif",
"bound_prefix",
"==",
"prefix",
":",
"pass",
"# already bound",
"else",
":",
"if",
"override",
"or",
"bound_prefix",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"self",
".",
"store",
".",
"bind",
"(",
"prefix",
",",
"namespace",
")"
] |
Set the limit data to the given list of limits . Limits are specified as the raw msgpack string representing the limit . Computes the checksum of the limits ; if the checksum is identical to the current one no action is taken . | def set_limits ( self , limits ) : # First task, build the checksum of the new limits chksum = hashlib . md5 ( ) # sufficient for our purposes for lim in limits : chksum . update ( lim ) new_sum = chksum . hexdigest ( ) # Now install it with self . limit_lock : if self . limit_sum == new_sum : # No changes return self . limit_data = [ msgpack . loads ( lim ) for lim in limits ] self . limit_sum = new_sum | 10,347 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L60-L80 | [
"def",
"finalizePrivateLessonRegistration",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"finalReg",
"=",
"kwargs",
".",
"pop",
"(",
"'registration'",
")",
"for",
"er",
"in",
"finalReg",
".",
"eventregistration_set",
".",
"filter",
"(",
"event__privatelessonevent__isnull",
"=",
"False",
")",
":",
"er",
".",
"event",
".",
"finalizeBooking",
"(",
"eventRegistration",
"=",
"er",
",",
"notifyStudent",
"=",
"False",
")"
] |
Starts the ControlDaemon by launching the listening thread and triggering the initial limits load . | def start ( self ) : # Spawn the listening thread self . listen_thread = eventlet . spawn_n ( self . listen ) # Now do the initial load self . reload ( ) | 10,348 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L136-L146 | [
"def",
"sync",
"(",
"self",
")",
":",
"if",
"self",
".",
"writeback",
"and",
"self",
".",
"cache",
":",
"super",
"(",
"_TimeoutMixin",
",",
"self",
")",
".",
"__delitem__",
"(",
"self",
".",
"_INDEX",
")",
"super",
"(",
"_TimeoutMixin",
",",
"self",
")",
".",
"sync",
"(",
")",
"self",
".",
"writeback",
"=",
"False",
"super",
"(",
"_TimeoutMixin",
",",
"self",
")",
".",
"__setitem__",
"(",
"self",
".",
"_INDEX",
",",
"self",
".",
"_index",
")",
"self",
".",
"writeback",
"=",
"True",
"if",
"hasattr",
"(",
"self",
".",
"dict",
",",
"'sync'",
")",
":",
"self",
".",
"dict",
".",
"sync",
"(",
")"
] |
Listen for incoming control messages . | def listen ( self ) : # Use a specific database handle, with override. This allows # the long-lived listen thread to be configured to use a # different database or different database options. db = self . config . get_database ( 'control' ) # Need a pub-sub object kwargs = { } if 'shard_hint' in self . config [ 'control' ] : kwargs [ 'shard_hint' ] = self . config [ 'control' ] [ 'shard_hint' ] pubsub = db . pubsub ( * * kwargs ) # Subscribe to the right channel(s)... channel = self . config [ 'control' ] . get ( 'channel' , 'control' ) pubsub . subscribe ( channel ) # Now we listen... for msg in pubsub . listen ( ) : # Only interested in messages to our reload channel if ( msg [ 'type' ] in ( 'pmessage' , 'message' ) and msg [ 'channel' ] == channel ) : # Figure out what kind of message this is command , _sep , args = msg [ 'data' ] . partition ( ':' ) # We must have some command... if not command : continue # Don't do anything with internal commands if command [ 0 ] == '_' : LOG . error ( "Cannot call internal command %r" % command ) continue # Look up the command if command in self . _commands : func = self . _commands [ command ] else : # Try an entrypoint func = utils . find_entrypoint ( 'turnstile.command' , command , compat = False ) self . _commands [ command ] = func # Don't do anything with missing commands if not func : LOG . error ( "No such command %r" % command ) continue # Execute the desired command arglist = args . split ( ':' ) if args else [ ] try : func ( self , * arglist ) except Exception : LOG . exception ( "Failed to execute command %r arguments %r" % ( command , arglist ) ) continue | 10,349 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L148-L212 | [
"def",
"same_partial_index",
"(",
"self",
",",
"other",
")",
":",
"if",
"(",
"self",
".",
"has_option",
"(",
"\"where\"",
")",
"and",
"other",
".",
"has_option",
"(",
"\"where\"",
")",
"and",
"self",
".",
"get_option",
"(",
"\"where\"",
")",
"==",
"other",
".",
"get_option",
"(",
"\"where\"",
")",
")",
":",
"return",
"True",
"if",
"not",
"self",
".",
"has_option",
"(",
"\"where\"",
")",
"and",
"not",
"other",
".",
"has_option",
"(",
"\"where\"",
")",
":",
"return",
"True",
"return",
"False"
] |
Reloads the limits configuration from the database . | def reload ( self ) : # Acquire the pending semaphore. If we fail, exit--someone # else is already doing the reload if not self . pending . acquire ( False ) : return # Do the remaining steps in a try/finally block so we make # sure to release the semaphore control_args = self . config [ 'control' ] try : # Load all the limits key = control_args . get ( 'limits_key' , 'limits' ) self . limits . set_limits ( self . db . zrange ( key , 0 , - 1 ) ) except Exception : # Log an error LOG . exception ( "Could not load limits" ) # Get our error set and publish channel error_key = control_args . get ( 'errors_key' , 'errors' ) error_channel = control_args . get ( 'errors_channel' , 'errors' ) # Get an informative message msg = "Failed to load limits: " + traceback . format_exc ( ) # Store the message into the error set. We use a set here # because it's likely that more than one node will # generate the same message if there is an error, and this # avoids an explosion in the size of the set. with utils . ignore_except ( ) : self . db . sadd ( error_key , msg ) # Publish the message to a channel with utils . ignore_except ( ) : self . db . publish ( error_channel , msg ) finally : self . pending . release ( ) | 10,350 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/control.py#L225-L271 | [
"def",
"encode",
"(",
"*",
"args",
")",
":",
"args",
"=",
"[",
"arg",
".",
"split",
"(",
")",
"for",
"arg",
"in",
"args",
"]",
"unique",
"=",
"_uniquewords",
"(",
"*",
"args",
")",
"feature_vectors",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"args",
")",
",",
"len",
"(",
"unique",
")",
")",
")",
"for",
"vec",
",",
"s",
"in",
"zip",
"(",
"feature_vectors",
",",
"args",
")",
":",
"for",
"word",
"in",
"s",
":",
"vec",
"[",
"unique",
"[",
"word",
"]",
"]",
"=",
"1",
"return",
"feature_vectors"
] |
Enforce a policy to a API . | def enforce_policy ( rule ) : def wrapper ( func ) : """Decorator used for wrap API.""" @ functools . wraps ( func ) def wrapped ( * args , * * kwargs ) : if enforcer . enforce ( rule , { } , g . cred ) : return func ( * args , * * kwargs ) return wrapped return wrapper | 10,351 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/demos/flask/server.py#L56-L67 | [
"def",
"deleteMessages",
"(",
"self",
",",
"message_ids",
")",
":",
"message_ids",
"=",
"require_list",
"(",
"message_ids",
")",
"data",
"=",
"dict",
"(",
")",
"for",
"i",
",",
"message_id",
"in",
"enumerate",
"(",
"message_ids",
")",
":",
"data",
"[",
"\"message_ids[{}]\"",
".",
"format",
"(",
"i",
")",
"]",
"=",
"message_id",
"r",
"=",
"self",
".",
"_post",
"(",
"self",
".",
"req_url",
".",
"DELETE_MESSAGES",
",",
"data",
")",
"return",
"r",
".",
"ok"
] |
Initialize a connection to the Redis database . | def initialize ( config ) : # Determine the client class to use if 'redis_client' in config : client = utils . find_entrypoint ( 'turnstile.redis_client' , config [ 'redis_client' ] , required = True ) else : client = redis . StrictRedis # Extract relevant connection information from the configuration kwargs = { } for cfg_var , type_ in REDIS_CONFIGS . items ( ) : if cfg_var in config : kwargs [ cfg_var ] = type_ ( config [ cfg_var ] ) # Make sure we have at a minimum the hostname if 'host' not in kwargs and 'unix_socket_path' not in kwargs : raise redis . ConnectionError ( "No host specified for redis database" ) # Look up the connection pool configuration cpool_class = None cpool = { } extra_kwargs = { } for key , value in config . items ( ) : if key . startswith ( 'connection_pool.' ) : _dummy , _sep , varname = key . partition ( '.' ) if varname == 'connection_class' : cpool [ varname ] = utils . find_entrypoint ( 'turnstile.connection_class' , value , required = True ) elif varname == 'max_connections' : cpool [ varname ] = int ( value ) elif varname == 'parser_class' : cpool [ varname ] = utils . find_entrypoint ( 'turnstile.parser_class' , value , required = True ) else : cpool [ varname ] = value elif key not in REDIS_CONFIGS and key not in REDIS_EXCLUDES : extra_kwargs [ key ] = value if cpool : cpool_class = redis . ConnectionPool # Use custom connection pool class if requested... if 'connection_pool' in config : cpool_class = utils . find_entrypoint ( 'turnstile.connection_pool' , config [ 'connection_pool' ] , required = True ) # If we're using a connection pool, we'll need to pass the keyword # arguments to that instead of to redis if cpool_class : cpool . update ( kwargs ) # Use a custom connection class? if 'connection_class' not in cpool : if 'unix_socket_path' in cpool : if 'host' in cpool : del cpool [ 'host' ] if 'port' in cpool : del cpool [ 'port' ] cpool [ 'path' ] = cpool [ 'unix_socket_path' ] del cpool [ 'unix_socket_path' ] cpool [ 'connection_class' ] = redis . UnixDomainSocketConnection else : cpool [ 'connection_class' ] = redis . Connection # Build the connection pool to use and set up to pass it into # the redis constructor... kwargs = dict ( connection_pool = cpool_class ( * * cpool ) ) # Build and return the database kwargs . update ( extra_kwargs ) return client ( * * kwargs ) | 10,352 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/database.py#L35-L111 | [
"def",
"_build_wheel_modern",
"(",
"ireq",
",",
"output_dir",
",",
"finder",
",",
"wheel_cache",
",",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"progress_bar\"",
":",
"\"off\"",
",",
"\"build_isolation\"",
":",
"False",
"}",
")",
"with",
"pip_shims",
".",
"RequirementTracker",
"(",
")",
"as",
"req_tracker",
":",
"if",
"req_tracker",
":",
"kwargs",
"[",
"\"req_tracker\"",
"]",
"=",
"req_tracker",
"preparer",
"=",
"pip_shims",
".",
"RequirementPreparer",
"(",
"*",
"*",
"kwargs",
")",
"builder",
"=",
"pip_shims",
".",
"WheelBuilder",
"(",
"finder",
",",
"preparer",
",",
"wheel_cache",
")",
"return",
"builder",
".",
"_build_one",
"(",
"ireq",
",",
"output_dir",
")"
] |
Helper function to hydrate a list of limits . | def limits_hydrate ( db , lims ) : return [ limits . Limit . hydrate ( db , lim ) for lim in lims ] | 10,353 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/database.py#L114-L123 | [
"async",
"def",
"open_search",
"(",
"type_",
":",
"str",
",",
"query",
":",
"dict",
",",
"options",
":",
"dict",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"not",
"hasattr",
"(",
"Wallet",
".",
"open_search",
",",
"\"cb\"",
")",
":",
"logger",
".",
"debug",
"(",
"\"vcx_wallet_open_search: Creating callback\"",
")",
"Wallet",
".",
"open_search",
".",
"cb",
"=",
"create_cb",
"(",
"CFUNCTYPE",
"(",
"None",
",",
"c_uint32",
",",
"c_uint32",
",",
"c_uint32",
")",
")",
"c_type_",
"=",
"c_char_p",
"(",
"type_",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_query",
"=",
"c_char_p",
"(",
"json",
".",
"dumps",
"(",
"query",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_options",
"=",
"c_char_p",
"(",
"json",
".",
"dumps",
"(",
"options",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"options",
"else",
"None",
"data",
"=",
"await",
"do_call",
"(",
"'vcx_wallet_open_search'",
",",
"c_type_",
",",
"c_query",
",",
"c_options",
",",
"Wallet",
".",
"open_search",
".",
"cb",
")",
"logger",
".",
"debug",
"(",
"\"vcx_wallet_open_search completed\"",
")",
"return",
"data"
] |
Safely updates the list of limits in the database . | def limit_update ( db , key , limits ) : # Start by dehydrating all the limits desired = [ msgpack . dumps ( l . dehydrate ( ) ) for l in limits ] desired_set = set ( desired ) # Now, let's update the limits with db . pipeline ( ) as pipe : while True : try : # Watch for changes to the key pipe . watch ( key ) # Look up the existing limits existing = set ( pipe . zrange ( key , 0 , - 1 ) ) # Start the transaction... pipe . multi ( ) # Remove limits we no longer have for lim in existing - desired_set : pipe . zrem ( key , lim ) # Update or add all our desired limits for idx , lim in enumerate ( desired ) : pipe . zadd ( key , ( idx + 1 ) * 10 , lim ) # Execute the transaction pipe . execute ( ) except redis . WatchError : # Try again... continue else : # We're all done! break | 10,354 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/database.py#L126-L172 | [
"def",
"dir",
"(",
"self",
",",
"path",
"=",
"'/'",
",",
"slash",
"=",
"True",
",",
"bus",
"=",
"False",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"slash",
":",
"msg",
"=",
"MSG_DIRALLSLASH",
"else",
":",
"msg",
"=",
"MSG_DIRALL",
"if",
"bus",
":",
"flags",
"=",
"self",
".",
"flags",
"|",
"FLG_BUS_RET",
"else",
":",
"flags",
"=",
"self",
".",
"flags",
"&",
"~",
"FLG_BUS_RET",
"ret",
",",
"data",
"=",
"self",
".",
"sendmess",
"(",
"msg",
",",
"str2bytez",
"(",
"path",
")",
",",
"flags",
",",
"timeout",
"=",
"timeout",
")",
"if",
"ret",
"<",
"0",
":",
"raise",
"OwnetError",
"(",
"-",
"ret",
",",
"self",
".",
"errmess",
"[",
"-",
"ret",
"]",
",",
"path",
")",
"if",
"data",
":",
"return",
"bytes2str",
"(",
"data",
")",
".",
"split",
"(",
"','",
")",
"else",
":",
"return",
"[",
"]"
] |
Utility function to issue a command to all Turnstile instances . | def command ( db , channel , command , * args ) : # Build the command we're sending cmd = [ command ] cmd . extend ( str ( a ) for a in args ) # Send it out db . publish ( channel , ':' . join ( cmd ) ) | 10,355 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/database.py#L175-L196 | [
"def",
"build_synchronize_decorator",
"(",
")",
":",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"lock_decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"lock_decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"lock",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"lock_decorated",
"return",
"lock_decorator"
] |
Internal method to tokenize latex | def _tokenize_latex ( self , exp ) : tokens = [ ] prevexp = "" while exp : t , exp = self . _get_next_token ( exp ) if t . strip ( ) != "" : tokens . append ( t ) if prevexp == exp : break prevexp = exp return tokens | 10,356 | https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/indices.py#L95-L108 | [
"def",
"_get_broadcast_shape",
"(",
"shape1",
",",
"shape2",
")",
":",
"if",
"shape1",
"==",
"shape2",
":",
"return",
"shape1",
"length1",
"=",
"len",
"(",
"shape1",
")",
"length2",
"=",
"len",
"(",
"shape2",
")",
"if",
"length1",
">",
"length2",
":",
"shape",
"=",
"list",
"(",
"shape1",
")",
"else",
":",
"shape",
"=",
"list",
"(",
"shape2",
")",
"i",
"=",
"max",
"(",
"length1",
",",
"length2",
")",
"-",
"1",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"shape1",
"[",
":",
":",
"-",
"1",
"]",
",",
"shape2",
"[",
":",
":",
"-",
"1",
"]",
")",
":",
"if",
"a",
"!=",
"1",
"and",
"b",
"!=",
"1",
"and",
"a",
"!=",
"b",
":",
"raise",
"ValueError",
"(",
"'shape1=%s is not broadcastable to shape2=%s'",
"%",
"(",
"shape1",
",",
"shape2",
")",
")",
"shape",
"[",
"i",
"]",
"=",
"max",
"(",
"a",
",",
"b",
")",
"i",
"-=",
"1",
"return",
"tuple",
"(",
"shape",
")"
] |
Convert query into an indexable string . | def _convert_query ( self , query ) : query = self . dictionary . doc2bow ( self . _tokenize_latex ( query ) ) sims = self . index [ query ] neighbors = sorted ( sims , key = lambda item : - item [ 1 ] ) neighbors = { "neighbors" : [ { self . columns [ 0 ] : { "data" : self . docs [ n [ 0 ] ] , "fmt" : "math" } , self . columns [ 1 ] : { "data" : float ( n [ 1 ] ) } } for n in neighbors ] } if neighbors else { "neighbors" : [ ] } return neighbors | 10,357 | https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/indices.py#L110-L118 | [
"def",
"should_use_custom_repo",
"(",
"args",
",",
"cd_conf",
",",
"repo_url",
")",
":",
"if",
"repo_url",
":",
"# repo_url signals a CLI override, return False immediately",
"return",
"False",
"if",
"cd_conf",
":",
"if",
"cd_conf",
".",
"has_repos",
":",
"has_valid_release",
"=",
"args",
".",
"release",
"in",
"cd_conf",
".",
"get_repos",
"(",
")",
"has_default_repo",
"=",
"cd_conf",
".",
"get_default_repo",
"(",
")",
"if",
"has_valid_release",
"or",
"has_default_repo",
":",
"return",
"True",
"return",
"False"
] |
nicely join two path elements together | def join ( path1 , path2 ) : if path1 . endswith ( '/' ) and path2 . startswith ( '/' ) : return '' . join ( [ path1 , path2 [ 1 : ] ] ) elif path1 . endswith ( '/' ) or path2 . startswith ( '/' ) : return '' . join ( [ path1 , path2 ] ) else : return '' . join ( [ path1 , '/' , path2 ] ) | 10,358 | https://github.com/jasonrbriggs/proton/blob/e734734750797ef0caaa1680379e07b86d7a53e3/python/proton/utils.py#L24-L33 | [
"def",
"_CheckPacketSize",
"(",
"cursor",
")",
":",
"cur_packet_size",
"=",
"int",
"(",
"_ReadVariable",
"(",
"\"max_allowed_packet\"",
",",
"cursor",
")",
")",
"if",
"cur_packet_size",
"<",
"MAX_PACKET_SIZE",
":",
"raise",
"Error",
"(",
"\"MySQL max_allowed_packet of {0} is required, got {1}. \"",
"\"Please set max_allowed_packet={0} in your MySQL config.\"",
".",
"format",
"(",
"MAX_PACKET_SIZE",
",",
"cur_packet_size",
")",
")"
] |
Converts LaTeX math expressions into an html layout . Creates a html file in the directory where print_math is called by default . Displays math to jupyter notebook if notebook argument is specified . | def print_math ( math_expression_lst , name = "math.html" , out = 'html' , formatter = lambda x : x ) : try : shutil . rmtree ( 'viz' ) except : pass pth = get_cur_path ( ) + print_math_template_path shutil . copytree ( pth , 'viz' ) # clean_str = formatter(math_expression_lst) html_loc = None if out == "html" : html_loc = pth + "standalone_index.html" if out == "notebook" : from IPython . display import display , HTML html_loc = pth + "notebook_index.html" html = open ( html_loc ) . read ( ) html = html . replace ( "__MATH_LIST__" , json . dumps ( math_expression_lst ) ) if out == "notebook" : display ( HTML ( html ) ) elif out == "html" : with open ( name , "w+" ) as out_f : out_f . write ( html ) | 10,359 | https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/print_math.py#L17-L53 | [
"def",
"Reset",
"(",
"self",
",",
"Channel",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"__m_dllBasic",
".",
"CAN_Reset",
"(",
"Channel",
")",
"return",
"TPCANStatus",
"(",
"res",
")",
"except",
":",
"logger",
".",
"error",
"(",
"\"Exception on PCANBasic.Reset\"",
")",
"raise"
] |
Log an error or print in stdout if no logger . | def log_error ( self , msg , * args ) : if self . _logger is not None : self . _logger . error ( msg , * args ) else : print ( msg % args ) | 10,360 | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L55-L60 | [
"def",
"full_analysis",
"(",
"self",
",",
"ncpus",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"molecular_weight",
"(",
")",
"self",
".",
"calculate_centre_of_mass",
"(",
")",
"self",
".",
"calculate_maximum_diameter",
"(",
")",
"self",
".",
"calculate_average_diameter",
"(",
")",
"self",
".",
"calculate_pore_diameter",
"(",
")",
"self",
".",
"calculate_pore_volume",
"(",
")",
"self",
".",
"calculate_pore_diameter_opt",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"calculate_pore_volume_opt",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"calculate_windows",
"(",
"ncpus",
"=",
"ncpus",
",",
"*",
"*",
"kwargs",
")",
"# self._circumcircle(**kwargs)",
"return",
"self",
".",
"properties"
] |
Return sensor attribute with precission or None if not present . | def _get_value_opc_attr ( self , attr_name , prec_decimals = 2 ) : try : value = getattr ( self , attr_name ) if value is not None : return round ( value , prec_decimals ) except I2cVariableNotImplemented : pass return None | 10,361 | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L91-L99 | [
"def",
"connect_controller",
"(",
"self",
",",
"vid",
",",
"pid",
",",
"serial",
")",
":",
"self",
".",
"lib",
".",
"tdConnectTellStickController",
"(",
"vid",
",",
"pid",
",",
"serial",
")"
] |
Return string representation of the current state of the sensor . | def current_state_str ( self ) : if self . sample_ok : msg = '' temperature = self . _get_value_opc_attr ( 'temperature' ) if temperature is not None : msg += 'Temp: %s ºC, ' emperature humidity = self . _get_value_opc_attr ( 'humidity' ) if humidity is not None : msg += 'Humid: %s %%, ' % humidity pressure = self . _get_value_opc_attr ( 'pressure' ) if pressure is not None : msg += 'Press: %s mb, ' % pressure light_level = self . _get_value_opc_attr ( 'light_level' ) if light_level is not None : msg += 'Light: %s lux, ' % light_level return msg [ : - 2 ] else : return "Bad sample" | 10,362 | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L102-L120 | [
"def",
"get_modifications",
"(",
"self",
")",
":",
"# Get all the specific mod types",
"mod_event_types",
"=",
"list",
"(",
"ont_to_mod_type",
".",
"keys",
"(",
")",
")",
"# Add ONT::PTMs as a special case",
"mod_event_types",
"+=",
"[",
"'ONT::PTM'",
"]",
"mod_events",
"=",
"[",
"]",
"for",
"mod_event_type",
"in",
"mod_event_types",
":",
"events",
"=",
"self",
".",
"tree",
".",
"findall",
"(",
"\"EVENT/[type='%s']\"",
"%",
"mod_event_type",
")",
"mod_extracted",
"=",
"self",
".",
"extracted_events",
".",
"get",
"(",
"mod_event_type",
",",
"[",
"]",
")",
"for",
"event",
"in",
"events",
":",
"event_id",
"=",
"event",
".",
"attrib",
".",
"get",
"(",
"'id'",
")",
"if",
"event_id",
"not",
"in",
"mod_extracted",
":",
"mod_events",
".",
"append",
"(",
"event",
")",
"# Iterate over all modification events",
"for",
"event",
"in",
"mod_events",
":",
"stmts",
"=",
"self",
".",
"_get_modification_event",
"(",
"event",
")",
"if",
"stmts",
":",
"for",
"stmt",
"in",
"stmts",
":",
"self",
".",
"statements",
".",
"append",
"(",
"stmt",
")"
] |
Apply func to each channel of audio data in samples | def _applyMultichan ( samples , func ) : # type: (np.ndarray, Callable[[np.ndarray], np.ndarray]) -> np.ndarray if len ( samples . shape ) == 1 or samples . shape [ 1 ] == 1 : newsamples = func ( samples ) else : y = np . array ( [ ] ) for i in range ( samples . shape [ 1 ] ) : y = np . concatenate ( ( y , func ( samples [ : , i ] ) ) ) newsamples = y . reshape ( samples . shape [ 1 ] , - 1 ) . T return newsamples | 10,363 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L17-L29 | [
"def",
"_retry",
"(",
"function",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"last_exception",
"=",
"None",
"#for host in self.router.get_hosts(**kwargs):",
"for",
"host",
"in",
"self",
".",
"host",
":",
"try",
":",
"return",
"function",
"(",
"self",
",",
"host",
",",
"*",
"*",
"kwargs",
")",
"except",
"SolrError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"e",
")",
"raise",
"except",
"ConnectionError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"\"Tried connecting to Solr, but couldn't because of the following exception.\"",
")",
"if",
"'401'",
"in",
"e",
".",
"__str__",
"(",
")",
":",
"raise",
"last_exception",
"=",
"e",
"# raise the last exception after contacting all hosts instead of returning None",
"if",
"last_exception",
"is",
"not",
"None",
":",
"raise",
"last_exception",
"return",
"inner"
] |
Resample using Fourier method . The same as resample_scipy but with low - pass filtering for upsampling | def _resample_obspy ( samples , sr , newsr , window = 'hanning' , lowpass = True ) : # type: (np.ndarray, int, int, str, bool) -> np.ndarray from scipy . signal import resample from math import ceil factor = sr / float ( newsr ) if newsr < sr and lowpass : # be sure filter still behaves good if factor > 16 : logger . info ( "Automatic filter design is unstable for resampling " "factors (current sampling rate/new sampling rate) " "above 16. Manual resampling is necessary." ) freq = min ( sr , newsr ) * 0.5 / float ( factor ) logger . debug ( f"resample_obspy: lowpass {freq}" ) samples = lowpass_cheby2 ( samples , freq = freq , sr = sr , maxorder = 12 ) num = int ( ceil ( len ( samples ) / factor ) ) return _applyMultichan ( samples , lambda S : resample ( S , num , window = window ) ) | 10,364 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L191-L213 | [
"def",
"_set",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"AttachmentsField",
",",
"self",
")",
".",
"_set",
"(",
"value",
")",
"self",
".",
"_cursor",
"=",
"None"
] |
Resample samples with given samplerate sr to new samplerate newsr | def resample ( samples , oldsr , newsr ) : # type: (np.ndarray, int, int) -> np.ndarray backends = [ _resample_samplerate , # turns the samples into float32, which is ok for audio _resample_scikits , _resample_nnresample , # very good results, follows libsamplerate closely _resample_obspy , # these last two introduce some error at the first samples _resample_scipy ] # type: List[Callable[[np.ndarray, int, int], Opt[np.ndarray]]] for backend in backends : newsamples = backend ( samples , oldsr , newsr ) if newsamples is not None : return newsamples | 10,365 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L216-L238 | [
"async",
"def",
"complete",
"(",
"self",
",",
"code",
":",
"str",
",",
"opts",
":",
"dict",
"=",
"None",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"opts",
"=",
"{",
"}",
"if",
"opts",
"is",
"None",
"else",
"opts",
"params",
"=",
"{",
"}",
"if",
"self",
".",
"owner_access_key",
":",
"params",
"[",
"'owner_access_key'",
"]",
"=",
"self",
".",
"owner_access_key",
"rqst",
"=",
"Request",
"(",
"self",
".",
"session",
",",
"'POST'",
",",
"'/kernel/{}/complete'",
".",
"format",
"(",
"self",
".",
"kernel_id",
")",
",",
"params",
"=",
"params",
")",
"rqst",
".",
"set_json",
"(",
"{",
"'code'",
":",
"code",
",",
"'options'",
":",
"{",
"'row'",
":",
"int",
"(",
"opts",
".",
"get",
"(",
"'row'",
",",
"0",
")",
")",
",",
"'col'",
":",
"int",
"(",
"opts",
".",
"get",
"(",
"'col'",
",",
"0",
")",
")",
",",
"'line'",
":",
"opts",
".",
"get",
"(",
"'line'",
",",
"''",
")",
",",
"'post'",
":",
"opts",
".",
"get",
"(",
"'post'",
",",
"''",
")",
",",
"}",
",",
"}",
")",
"async",
"with",
"rqst",
".",
"fetch",
"(",
")",
"as",
"resp",
":",
"return",
"await",
"resp",
".",
"json",
"(",
")"
] |
return package version without importing it | def get_package_version ( ) : base = os . path . abspath ( os . path . dirname ( __file__ ) ) with open ( os . path . join ( base , 'policy' , '__init__.py' ) , mode = 'rt' , encoding = 'utf-8' ) as initf : for line in initf : m = version . match ( line . strip ( ) ) if not m : continue return m . groups ( ) [ 0 ] | 10,366 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/setup.py#L24-L34 | [
"def",
"main",
"(",
")",
":",
"try",
":",
"# Retrieve the first USB device",
"device",
"=",
"AlarmDecoder",
"(",
"SerialDevice",
"(",
"interface",
"=",
"SERIAL_DEVICE",
")",
")",
"# Set up an event handler and open the device",
"device",
".",
"on_rfx_message",
"+=",
"handle_rfx",
"with",
"device",
".",
"open",
"(",
"baudrate",
"=",
"BAUDRATE",
")",
":",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"except",
"Exception",
"as",
"ex",
":",
"print",
"(",
"'Exception:'",
",",
"ex",
")"
] |
return package s long description | def get_long_description ( ) : base = os . path . abspath ( os . path . dirname ( __file__ ) ) readme_file = os . path . join ( base , 'README.md' ) with open ( readme_file , mode = 'rt' , encoding = 'utf-8' ) as readme : return readme . read ( ) | 10,367 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/setup.py#L37-L42 | [
"def",
"_get_default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"name",
"in",
"obj",
".",
"_property_values",
":",
"# this shouldn't happen because we should have checked before _get_default()",
"raise",
"RuntimeError",
"(",
"\"Bokeh internal error, does not handle the case of self.name already in _property_values\"",
")",
"is_themed",
"=",
"obj",
".",
"themed_values",
"(",
")",
"is",
"not",
"None",
"and",
"self",
".",
"name",
"in",
"obj",
".",
"themed_values",
"(",
")",
"default",
"=",
"self",
".",
"instance_default",
"(",
"obj",
")",
"if",
"is_themed",
":",
"unstable_dict",
"=",
"obj",
".",
"_unstable_themed_values",
"else",
":",
"unstable_dict",
"=",
"obj",
".",
"_unstable_default_values",
"if",
"self",
".",
"name",
"in",
"unstable_dict",
":",
"return",
"unstable_dict",
"[",
"self",
".",
"name",
"]",
"if",
"self",
".",
"property",
".",
"_may_have_unstable_default",
"(",
")",
":",
"if",
"isinstance",
"(",
"default",
",",
"PropertyValueContainer",
")",
":",
"default",
".",
"_register_owner",
"(",
"obj",
",",
"self",
")",
"unstable_dict",
"[",
"self",
".",
"name",
"]",
"=",
"default",
"return",
"default"
] |
return package s install requires | def get_install_requires ( ) : base = os . path . abspath ( os . path . dirname ( __file__ ) ) requirements_file = os . path . join ( base , 'requirements.txt' ) if not os . path . exists ( requirements_file ) : return [ ] with open ( requirements_file , mode = 'rt' , encoding = 'utf-8' ) as f : return f . read ( ) . splitlines ( ) | 10,368 | https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/setup.py#L61-L68 | [
"def",
"parse_tophat_log",
"(",
"self",
",",
"raw_data",
")",
":",
"if",
"'Aligned pairs'",
"in",
"raw_data",
":",
"# Paired end data",
"regexes",
"=",
"{",
"'overall_aligned_percent'",
":",
"r\"([\\d\\.]+)% overall read mapping rate.\"",
",",
"'concordant_aligned_percent'",
":",
"r\"([\\d\\.]+)% concordant pair alignment rate.\"",
",",
"'aligned_total'",
":",
"r\"Aligned pairs:\\s+(\\d+)\"",
",",
"'aligned_multimap'",
":",
"r\"Aligned pairs:\\s+\\d+\\n\\s+of these:\\s+(\\d+)\"",
",",
"'aligned_discordant'",
":",
"r\"(\\d+) \\([\\s\\d\\.]+%\\) are discordant alignments\"",
",",
"'total_reads'",
":",
"r\"[Rr]eads:\\n\\s+Input\\s*:\\s+(\\d+)\"",
",",
"}",
"else",
":",
"# Single end data",
"regexes",
"=",
"{",
"'total_reads'",
":",
"r\"[Rr]eads:\\n\\s+Input\\s*:\\s+(\\d+)\"",
",",
"'aligned_total'",
":",
"r\"Mapped\\s*:\\s+(\\d+)\"",
",",
"'aligned_multimap'",
":",
"r\"of these\\s*:\\s+(\\d+)\"",
",",
"'overall_aligned_percent'",
":",
"r\"([\\d\\.]+)% overall read mapping rate.\"",
",",
"}",
"parsed_data",
"=",
"{",
"}",
"for",
"k",
",",
"r",
"in",
"regexes",
".",
"items",
"(",
")",
":",
"r_search",
"=",
"re",
".",
"search",
"(",
"r",
",",
"raw_data",
",",
"re",
".",
"MULTILINE",
")",
"if",
"r_search",
":",
"parsed_data",
"[",
"k",
"]",
"=",
"float",
"(",
"r_search",
".",
"group",
"(",
"1",
")",
")",
"if",
"len",
"(",
"parsed_data",
")",
"==",
"0",
":",
"return",
"None",
"parsed_data",
"[",
"'concordant_aligned_percent'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'concordant_aligned_percent'",
",",
"0",
")",
"parsed_data",
"[",
"'aligned_total'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'aligned_total'",
",",
"0",
")",
"parsed_data",
"[",
"'aligned_multimap'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'aligned_multimap'",
",",
"0",
")",
"parsed_data",
"[",
"'aligned_discordant'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'aligned_discordant'",
",",
"0",
")",
"parsed_data",
"[",
"'unaligned_total'",
"]",
"=",
"parsed_data",
"[",
"'total_reads'",
"]",
"-",
"parsed_data",
"[",
"'aligned_total'",
"]",
"parsed_data",
"[",
"'aligned_not_multimapped_discordant'",
"]",
"=",
"parsed_data",
"[",
"'aligned_total'",
"]",
"-",
"parsed_data",
"[",
"'aligned_multimap'",
"]",
"-",
"parsed_data",
"[",
"'aligned_discordant'",
"]",
"return",
"parsed_data"
] |
Download all sheets as configured . | def main ( flags ) : dl = SheetDownloader ( flags ) dl . init ( ) for file_info in settings . GOOGLE_SHEET_SYNC [ 'files' ] : print ( 'Downloading {}' . format ( file_info [ 'path' ] ) ) dl . download_sheet ( file_info [ 'path' ] , file_info [ 'sheet' ] , file_info [ 'range' ] , ) | 10,369 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/sheet_sync/_base.py#L122-L136 | [
"def",
"public_broadcaster",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PUBLIC_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"WebSocketHandler",
".",
"broadcast",
"(",
"line",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PUBLIC_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Download the cell range from the sheet and store it as CSV in the file_path file . | def download_sheet ( self , file_path , sheet_id , cell_range ) : result = self . service . spreadsheets ( ) . values ( ) . get ( spreadsheetId = sheet_id , range = cell_range , ) . execute ( ) values = result . get ( 'values' , [ ] ) with open ( file_path , newline = '' , encoding = 'utf-8' , mode = 'w' ) as f : writer = csv . writer ( f , lineterminator = '\n' ) for row in values : writer . writerow ( row ) | 10,370 | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/sheet_sync/_base.py#L102-L119 | [
"def",
"_count_devices",
"(",
"self",
")",
":",
"number_of_devices",
"=",
"ctypes",
".",
"c_uint",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetRawInputDeviceList",
"(",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_int",
")",
"(",
")",
",",
"ctypes",
".",
"byref",
"(",
"number_of_devices",
")",
",",
"ctypes",
".",
"sizeof",
"(",
"RawInputDeviceList",
")",
")",
"==",
"-",
"1",
":",
"warn",
"(",
"\"Call to GetRawInputDeviceList was unsuccessful.\"",
"\"We have no idea if a mouse or keyboard is attached.\"",
",",
"RuntimeWarning",
")",
"return",
"devices_found",
"=",
"(",
"RawInputDeviceList",
"*",
"number_of_devices",
".",
"value",
")",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetRawInputDeviceList",
"(",
"devices_found",
",",
"ctypes",
".",
"byref",
"(",
"number_of_devices",
")",
",",
"ctypes",
".",
"sizeof",
"(",
"RawInputDeviceList",
")",
")",
"==",
"-",
"1",
":",
"warn",
"(",
"\"Call to GetRawInputDeviceList was unsuccessful.\"",
"\"We have no idea if a mouse or keyboard is attached.\"",
",",
"RuntimeWarning",
")",
"return",
"for",
"device",
"in",
"devices_found",
":",
"if",
"device",
".",
"dwType",
"==",
"0",
":",
"self",
".",
"_raw_device_counts",
"[",
"'mice'",
"]",
"+=",
"1",
"elif",
"device",
".",
"dwType",
"==",
"1",
":",
"self",
".",
"_raw_device_counts",
"[",
"'keyboards'",
"]",
"+=",
"1",
"elif",
"device",
".",
"dwType",
"==",
"2",
":",
"self",
".",
"_raw_device_counts",
"[",
"'otherhid'",
"]",
"+=",
"1",
"else",
":",
"self",
".",
"_raw_device_counts",
"[",
"'unknown'",
"]",
"+=",
"1"
] |
Returns the version printed in a friendly way . | def getFriendlyString ( self ) : if self . _friendlyString is not None : return self . _friendlyString resultComponents = [ self . getIntMajor ( ) , self . getIntMinor ( ) , self . getIntBuild ( ) , self . getIntRevision ( ) ] for i in range ( len ( resultComponents ) - 1 , - 1 , - 1 ) : if resultComponents [ i ] == 0 : del resultComponents [ i ] else : break result = "." . join ( map ( str , resultComponents ) ) self . _friendlyString = result return result | 10,371 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/versioning.py#L117-L143 | [
"def",
"swo_disable",
"(",
"self",
",",
"port_mask",
")",
":",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_SWO_DisableTarget",
"(",
"port_mask",
")",
"if",
"res",
"!=",
"0",
":",
"raise",
"errors",
".",
"JLinkException",
"(",
"res",
")",
"return",
"None"
] |
Returns the versions of the suitable entries available in the directory - an empty list if no such entry is available | def getVersions ( self ) : if not os . path . exists ( self . _path ) : return [ ] result = [ ] for entryName in os . listdir ( self . _path ) : try : entryVersion = Version ( entryName ) result . append ( entryVersion ) except InvalidVersionException : continue return result | 10,372 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/versioning.py#L167-L185 | [
"def",
"_getOrCreate",
"(",
"cls",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
".",
"_taskContext",
",",
"BarrierTaskContext",
")",
":",
"cls",
".",
"_taskContext",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"return",
"cls",
".",
"_taskContext"
] |
Adds the active users for this branch to a users field . | def setUsers ( self , * args , * * kwargs ) : try : usrs = [ us for us in self . mambuusersclass ( branchId = self [ 'id' ] , * args , * * kwargs ) if us [ 'userState' ] == "ACTIVE" ] except AttributeError as ae : from . mambuuser import MambuUsers self . mambuusersclass = MambuUsers usrs = [ us for us in self . mambuusersclass ( branchId = self [ 'id' ] , * args , * * kwargs ) if us [ 'userState' ] == "ACTIVE" ] self [ 'users' ] = usrs return 1 | 10,373 | https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambubranch.py#L39-L57 | [
"def",
"_get_partition_info",
"(",
"storage_system",
",",
"device_path",
")",
":",
"try",
":",
"partition_infos",
"=",
"storage_system",
".",
"RetrieveDiskPartitionInfo",
"(",
"devicePath",
"=",
"[",
"device_path",
"]",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"log",
".",
"trace",
"(",
"'partition_info = %s'",
",",
"partition_infos",
"[",
"0",
"]",
")",
"return",
"partition_infos",
"[",
"0",
"]"
] |
Un - indents text at cursor position . | def unindent ( self ) : _logger ( ) . debug ( 'unindent' ) cursor = self . editor . textCursor ( ) _logger ( ) . debug ( 'cursor has selection %r' , cursor . hasSelection ( ) ) if cursor . hasSelection ( ) : cursor . beginEditBlock ( ) self . unindent_selection ( cursor ) cursor . endEditBlock ( ) self . editor . setTextCursor ( cursor ) else : tab_len = self . editor . tab_length indentation = cursor . positionInBlock ( ) indentation -= self . min_column if indentation == 0 : return max_spaces = indentation % tab_len if max_spaces == 0 : max_spaces = tab_len spaces = self . count_deletable_spaces ( cursor , max_spaces ) _logger ( ) . info ( 'deleting %d space before cursor' % spaces ) cursor . beginEditBlock ( ) for _ in range ( spaces ) : cursor . deletePreviousChar ( ) cursor . endEditBlock ( ) self . editor . setTextCursor ( cursor ) _logger ( ) . debug ( cursor . block ( ) . text ( ) ) | 10,374 | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/modes/indenter.py#L149-L178 | [
"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",
")"
] |
Instantiate a WorkflowEngine given a name or UUID . | def with_name ( cls , name , id_user = 0 , * * extra_data ) : return cls ( name = name , id_user = 0 , * * extra_data ) | 10,375 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L65-L77 | [
"def",
"_get_tab_zpe",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
":",
"# Compute the COBS ZPE table for decoding",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
"[",
"'\\xe0'",
"]",
"=",
"(",
"224",
",",
"''",
")",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
".",
"update",
"(",
"dict",
"(",
"(",
"chr",
"(",
"l",
")",
",",
"(",
"l",
",",
"'\\0'",
")",
")",
"for",
"l",
"in",
"range",
"(",
"1",
",",
"224",
")",
")",
")",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
".",
"update",
"(",
"dict",
"(",
"(",
"chr",
"(",
"l",
")",
",",
"(",
"l",
"-",
"224",
",",
"'\\0\\0'",
")",
")",
"for",
"l",
"in",
"range",
"(",
"225",
",",
"256",
")",
")",
")",
"# Compute the COBS ZPE table for encoding",
"cls",
".",
"_tabs",
"[",
"'enc_cobs_zpe'",
"]",
"=",
"[",
"(",
"224",
",",
"'\\xe0'",
")",
",",
"dict",
"(",
"(",
"l",
",",
"chr",
"(",
"l",
")",
")",
"for",
"l",
"in",
"range",
"(",
"1",
",",
"224",
")",
")",
",",
"dict",
"(",
"(",
"l",
"-",
"224",
",",
"chr",
"(",
"l",
")",
")",
"for",
"l",
"in",
"range",
"(",
"225",
",",
"256",
")",
")",
"]",
"return",
"cls",
".",
"_tabs",
"[",
"'dec_cobs_zpe'",
"]",
",",
"cls",
".",
"_tabs",
"[",
"'enc_cobs_zpe'",
"]"
] |
Load an existing workflow from the database given a UUID . | def from_uuid ( cls , uuid , * * extra_data ) : model = Workflow . query . get ( uuid ) if model is None : raise LookupError ( "No workflow with UUID {} was found" . format ( uuid ) ) instance = cls ( model = model , * * extra_data ) instance . objects = WorkflowObjectModel . query . filter ( WorkflowObjectModel . id_workflow == uuid , WorkflowObjectModel . id_parent == None , # noqa ) . all ( ) return instance | 10,376 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L80-L96 | [
"def",
"_compute_standard_dev",
"(",
"self",
",",
"rup",
",",
"imt",
",",
"C",
")",
":",
"sigma_mean",
"=",
"0.",
"if",
"imt",
".",
"name",
"in",
"\"SA PGA\"",
":",
"psi",
"=",
"-",
"6.898E-3",
"else",
":",
"psi",
"=",
"-",
"3.054E-5",
"if",
"rup",
".",
"mag",
"<=",
"6.5",
":",
"sigma_mean",
"=",
"(",
"C",
"[",
"'c12'",
"]",
"*",
"rup",
".",
"mag",
")",
"+",
"C",
"[",
"'c13'",
"]",
"elif",
"rup",
".",
"mag",
">",
"6.5",
":",
"sigma_mean",
"=",
"(",
"psi",
"*",
"rup",
".",
"mag",
")",
"+",
"C",
"[",
"'c14'",
"]",
"return",
"sigma_mean"
] |
Continue workflow for one given object from restart_point . | def continue_object ( self , workflow_object , restart_point = 'restart_task' , task_offset = 1 , stop_on_halt = False ) : translate = { 'restart_task' : 'current' , 'continue_next' : 'next' , 'restart_prev' : 'prev' , } self . state . callback_pos = workflow_object . callback_pos or [ 0 ] self . restart ( task = translate [ restart_point ] , obj = 'first' , objects = [ workflow_object ] , stop_on_halt = stop_on_halt ) | 10,377 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L193-L215 | [
"def",
"createComboContract",
"(",
"self",
",",
"symbol",
",",
"legs",
",",
"currency",
"=",
"\"USD\"",
",",
"exchange",
"=",
"None",
")",
":",
"exchange",
"=",
"legs",
"[",
"0",
"]",
".",
"m_exchange",
"if",
"exchange",
"is",
"None",
"else",
"exchange",
"contract_tuple",
"=",
"(",
"symbol",
",",
"\"BAG\"",
",",
"exchange",
",",
"currency",
",",
"\"\"",
",",
"0.0",
",",
"\"\"",
")",
"contract",
"=",
"self",
".",
"createContract",
"(",
"contract_tuple",
",",
"comboLegs",
"=",
"legs",
")",
"return",
"contract"
] |
Return True if workflow is fully completed . | def has_completed ( self ) : objects_in_db = WorkflowObjectModel . query . filter ( WorkflowObjectModel . id_workflow == self . uuid , WorkflowObjectModel . id_parent == None , # noqa ) . filter ( WorkflowObjectModel . status . in_ ( [ workflow_object_class . known_statuses . COMPLETED ] ) ) . count ( ) return objects_in_db == len ( list ( self . objects ) ) | 10,378 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L222-L230 | [
"def",
"_add_record",
"(",
"table",
",",
"data",
",",
"buffer_size",
")",
":",
"fields",
"=",
"table",
".",
"fields",
"# remove any keys that aren't relation fields",
"for",
"invalid_key",
"in",
"set",
"(",
"data",
")",
".",
"difference",
"(",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"fields",
"]",
")",
":",
"del",
"data",
"[",
"invalid_key",
"]",
"table",
".",
"append",
"(",
"Record",
".",
"from_dict",
"(",
"fields",
",",
"data",
")",
")",
"# write if requested and possible",
"if",
"buffer_size",
"is",
"not",
"None",
"and",
"table",
".",
"is_attached",
"(",
")",
":",
"# for now there isn't a public method to get the number of new",
"# records, so use private members",
"if",
"(",
"len",
"(",
"table",
")",
"-",
"1",
")",
"-",
"table",
".",
"_last_synced_index",
">",
"buffer_size",
":",
"table",
".",
"commit",
"(",
")"
] |
Configure the workflow to run by the name of this one . | def set_workflow_by_name ( self , workflow_name ) : from . proxies import workflows if workflow_name not in workflows : # No workflow with that name exists raise WorkflowDefinitionError ( "Workflow '%s' does not exist" % ( workflow_name , ) , workflow_name = workflow_name ) self . workflow_definition = workflows [ workflow_name ] self . callbacks . replace ( self . workflow_definition . workflow ) | 10,379 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L232-L249 | [
"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"
] |
Take action after every WF callback . | def after_each_callback ( eng , callback_func , obj ) : obj . callback_pos = eng . state . callback_pos obj . extra_data [ "_last_task_name" ] = callback_func . __name__ task_history = get_task_history ( callback_func ) if "_task_history" not in obj . extra_data : obj . extra_data [ "_task_history" ] = [ task_history ] else : obj . extra_data [ "_task_history" ] . append ( task_history ) | 10,380 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L275-L283 | [
"def",
"create",
"(",
"url",
",",
"filename",
",",
"properties",
")",
":",
"# Ensure that the file has valid suffix",
"if",
"not",
"has_tar_suffix",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"'invalid file suffix: '",
"+",
"filename",
")",
"# Upload file to create subject. If response is not 201 the uploaded",
"# file is not a valid FreeSurfer archive",
"files",
"=",
"{",
"'file'",
":",
"open",
"(",
"filename",
",",
"'rb'",
")",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"files",
"=",
"files",
")",
"if",
"response",
".",
"status_code",
"!=",
"201",
":",
"raise",
"ValueError",
"(",
"'invalid file: '",
"+",
"filename",
")",
"# Get image group HATEOAS references from successful response",
"links",
"=",
"references_to_dict",
"(",
"response",
".",
"json",
"(",
")",
"[",
"'links'",
"]",
")",
"resource_url",
"=",
"links",
"[",
"REF_SELF",
"]",
"# Update subject properties if given",
"if",
"not",
"properties",
"is",
"None",
":",
"obj_props",
"=",
"[",
"]",
"# Catch TypeErrors if properties is not a list.",
"try",
":",
"for",
"key",
"in",
"properties",
":",
"obj_props",
".",
"append",
"(",
"{",
"'key'",
":",
"key",
",",
"'value'",
":",
"properties",
"[",
"key",
"]",
"}",
")",
"except",
"TypeError",
"as",
"ex",
":",
"raise",
"ValueError",
"(",
"'invalid property set'",
")",
"try",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"links",
"[",
"REF_UPSERT_PROPERTIES",
"]",
")",
"req",
".",
"add_header",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
",",
"json",
".",
"dumps",
"(",
"{",
"'properties'",
":",
"obj_props",
"}",
")",
")",
"except",
"urllib2",
".",
"URLError",
"as",
"ex",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"ex",
")",
")",
"return",
"resource_url"
] |
Take action before the processing of an object begins . | def before_object ( eng , objects , obj ) : super ( InvenioProcessingFactory , InvenioProcessingFactory ) . before_object ( eng , objects , obj ) if "_error_msg" in obj . extra_data : del obj . extra_data [ "_error_msg" ] db . session . commit ( ) | 10,381 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L300-L308 | [
"def",
"update_sandbox_product",
"(",
"self",
",",
"product_id",
",",
"surge_multiplier",
"=",
"None",
",",
"drivers_available",
"=",
"None",
",",
")",
":",
"args",
"=",
"{",
"'surge_multiplier'",
":",
"surge_multiplier",
",",
"'drivers_available'",
":",
"drivers_available",
",",
"}",
"endpoint",
"=",
"'v1.2/sandbox/products/{}'",
".",
"format",
"(",
"product_id",
")",
"return",
"self",
".",
"_api_call",
"(",
"'PUT'",
",",
"endpoint",
",",
"args",
"=",
"args",
")"
] |
Take action once the proccessing of an object completes . | def after_object ( eng , objects , obj ) : # We save each object once it is fully run through super ( InvenioProcessingFactory , InvenioProcessingFactory ) . after_object ( eng , objects , obj ) obj . save ( status = obj . known_statuses . COMPLETED , id_workflow = eng . model . uuid ) db . session . commit ( ) | 10,382 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L311-L320 | [
"def",
"native_libraries_verify",
"(",
")",
":",
"with",
"open",
"(",
"BINARY_EXT_TEMPLATE",
",",
"\"r\"",
")",
"as",
"file_obj",
":",
"template",
"=",
"file_obj",
".",
"read",
"(",
")",
"expected",
"=",
"template",
".",
"format",
"(",
"revision",
"=",
"REVISION",
")",
"with",
"open",
"(",
"BINARY_EXT_FILE",
",",
"\"r\"",
")",
"as",
"file_obj",
":",
"contents",
"=",
"file_obj",
".",
"read",
"(",
")",
"if",
"contents",
"!=",
"expected",
":",
"err_msg",
"=",
"\"\\n\"",
"+",
"get_diff",
"(",
"contents",
",",
"expected",
",",
"\"docs/python/binary-extension.rst.actual\"",
",",
"\"docs/python/binary-extension.rst.expected\"",
",",
")",
"raise",
"ValueError",
"(",
"err_msg",
")",
"else",
":",
"print",
"(",
"\"docs/python/binary-extension.rst contents are as expected.\"",
")"
] |
Execute before processing the workflow . | def before_processing ( eng , objects ) : super ( InvenioProcessingFactory , InvenioProcessingFactory ) . before_processing ( eng , objects ) eng . save ( WorkflowStatus . RUNNING ) db . session . commit ( ) | 10,383 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L323-L328 | [
"def",
"winsorise_uint32",
"(",
"df",
",",
"invalid_data_behavior",
",",
"column",
",",
"*",
"columns",
")",
":",
"columns",
"=",
"list",
"(",
"(",
"column",
",",
")",
"+",
"columns",
")",
"mask",
"=",
"df",
"[",
"columns",
"]",
">",
"UINT32_MAX",
"if",
"invalid_data_behavior",
"!=",
"'ignore'",
":",
"mask",
"|=",
"df",
"[",
"columns",
"]",
".",
"isnull",
"(",
")",
"else",
":",
"# we are not going to generate a warning or error for this so just use",
"# nan_to_num",
"df",
"[",
"columns",
"]",
"=",
"np",
".",
"nan_to_num",
"(",
"df",
"[",
"columns",
"]",
")",
"mv",
"=",
"mask",
".",
"values",
"if",
"mv",
".",
"any",
"(",
")",
":",
"if",
"invalid_data_behavior",
"==",
"'raise'",
":",
"raise",
"ValueError",
"(",
"'%d values out of bounds for uint32: %r'",
"%",
"(",
"mv",
".",
"sum",
"(",
")",
",",
"df",
"[",
"mask",
".",
"any",
"(",
"axis",
"=",
"1",
")",
"]",
",",
")",
",",
")",
"if",
"invalid_data_behavior",
"==",
"'warn'",
":",
"warnings",
".",
"warn",
"(",
"'Ignoring %d values because they are out of bounds for'",
"' uint32: %r'",
"%",
"(",
"mv",
".",
"sum",
"(",
")",
",",
"df",
"[",
"mask",
".",
"any",
"(",
"axis",
"=",
"1",
")",
"]",
",",
")",
",",
"stacklevel",
"=",
"3",
",",
"# one extra frame for `expect_element`",
")",
"df",
"[",
"mask",
"]",
"=",
"0",
"return",
"df"
] |
Process to update status . | def after_processing ( eng , objects ) : super ( InvenioProcessingFactory , InvenioProcessingFactory ) . after_processing ( eng , objects ) if eng . has_completed : eng . save ( WorkflowStatus . COMPLETED ) else : eng . save ( WorkflowStatus . HALTED ) db . session . commit ( ) | 10,384 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L331-L339 | [
"def",
"on_response",
"(",
"self",
",",
"ch",
",",
"method_frame",
",",
"props",
",",
"body",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"rabbitmq.Requester.on_response\"",
")",
"if",
"self",
".",
"corr_id",
"==",
"props",
".",
"correlation_id",
":",
"self",
".",
"response",
"=",
"{",
"'props'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
"else",
":",
"LOGGER",
".",
"warn",
"(",
"\"rabbitmq.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"props",
".",
"correlation_id",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"natsd.Requester.on_response - discarded response : \"",
"+",
"str",
"(",
"{",
"'properties'",
":",
"props",
",",
"'body'",
":",
"body",
"}",
")",
")"
] |
Handle general exceptions in workflow saving states . | def Exception ( obj , eng , callbacks , exc_info ) : exception_repr = '' . join ( traceback . format_exception ( * exc_info ) ) msg = "Error:\n%s" % ( exception_repr ) eng . log . error ( msg ) if obj : # Sets an error message as a tuple (title, details) obj . extra_data [ '_error_msg' ] = exception_repr obj . save ( status = obj . known_statuses . ERROR , callback_pos = eng . state . callback_pos , id_workflow = eng . uuid ) eng . save ( WorkflowStatus . ERROR ) db . session . commit ( ) # Call super which will reraise super ( InvenioTransitionAction , InvenioTransitionAction ) . Exception ( obj , eng , callbacks , exc_info ) | 10,385 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L346-L365 | [
"def",
"parseReaderConfig",
"(",
"self",
",",
"confdict",
")",
":",
"logger",
".",
"debug",
"(",
"'parseReaderConfig input: %s'",
",",
"confdict",
")",
"conf",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"confdict",
".",
"items",
"(",
")",
":",
"if",
"not",
"k",
".",
"startswith",
"(",
"'Parameter'",
")",
":",
"continue",
"ty",
"=",
"v",
"[",
"'Type'",
"]",
"data",
"=",
"v",
"[",
"'Data'",
"]",
"vendor",
"=",
"None",
"subtype",
"=",
"None",
"try",
":",
"vendor",
",",
"subtype",
"=",
"v",
"[",
"'Vendor'",
"]",
",",
"v",
"[",
"'Subtype'",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"ty",
"==",
"1023",
":",
"if",
"vendor",
"==",
"25882",
"and",
"subtype",
"==",
"37",
":",
"tempc",
"=",
"struct",
".",
"unpack",
"(",
"'!H'",
",",
"data",
")",
"[",
"0",
"]",
"conf",
".",
"update",
"(",
"temperature",
"=",
"tempc",
")",
"else",
":",
"conf",
"[",
"ty",
"]",
"=",
"data",
"return",
"conf"
] |
Take actions when WaitProcessing is raised . | def WaitProcessing ( obj , eng , callbacks , exc_info ) : e = exc_info [ 1 ] obj . set_action ( e . action , e . message ) obj . save ( status = eng . object_status . WAITING , callback_pos = eng . state . callback_pos , id_workflow = eng . uuid ) eng . save ( WorkflowStatus . HALTED ) eng . log . warning ( "Workflow '%s' waiting at task %s with message: %s" , eng . name , eng . current_taskname or "Unknown" , e . message ) db . session . commit ( ) # Call super which will reraise TransitionActions . HaltProcessing ( obj , eng , callbacks , exc_info ) | 10,386 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L368-L391 | [
"def",
"get",
"(",
"self",
",",
"path_info",
")",
":",
"assert",
"path_info",
"[",
"\"scheme\"",
"]",
"==",
"\"local\"",
"path",
"=",
"path_info",
"[",
"\"path\"",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"None",
"actual_mtime",
",",
"actual_size",
"=",
"get_mtime_and_size",
"(",
"path",
")",
"actual_inode",
"=",
"get_inode",
"(",
"path",
")",
"existing_record",
"=",
"self",
".",
"get_state_record_for_inode",
"(",
"actual_inode",
")",
"if",
"not",
"existing_record",
":",
"return",
"None",
"mtime",
",",
"size",
",",
"checksum",
",",
"_",
"=",
"existing_record",
"if",
"self",
".",
"_file_metadata_changed",
"(",
"actual_mtime",
",",
"mtime",
",",
"actual_size",
",",
"size",
")",
":",
"return",
"None",
"self",
".",
"_update_state_record_timestamp_for_inode",
"(",
"actual_inode",
")",
"return",
"checksum"
] |
Stop the engne and mark the workflow as completed . | def StopProcessing ( obj , eng , callbacks , exc_info ) : e = exc_info [ 1 ] obj . save ( status = eng . object_status . COMPLETED , id_workflow = eng . uuid ) eng . save ( WorkflowStatus . COMPLETED ) obj . log . warning ( "Workflow '%s' stopped at task %s with message: %s" , eng . name , eng . current_taskname or "Unknown" , e . message ) db . session . commit ( ) super ( InvenioTransitionAction , InvenioTransitionAction ) . StopProcessing ( obj , eng , callbacks , exc_info ) | 10,387 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L419-L433 | [
"def",
"handle_error",
"(",
"_",
",",
"client_addr",
")",
":",
"exc_type",
",",
"exc_value",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"exc_type",
"is",
"socket",
".",
"error",
"and",
"exc_value",
"[",
"0",
"]",
"==",
"32",
":",
"pass",
"elif",
"exc_type",
"is",
"cPickle",
".",
"UnpicklingError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Invalid connection from {0}\\n'",
".",
"format",
"(",
"client_addr",
"[",
"0",
"]",
")",
")",
"else",
":",
"raise"
] |
Take action when SkipToken is raised . | def SkipToken ( obj , eng , callbacks , exc_info ) : msg = "Skipped running this object: {0}" . format ( obj . id ) eng . log . debug ( msg ) raise Continue | 10,388 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L436-L440 | [
"def",
"merge_entities",
"(",
"self",
",",
"from_entity_ids",
",",
"to_entity_id",
",",
"force",
"=",
"False",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'from_entity_ids'",
":",
"from_entity_ids",
",",
"'to_entity_id'",
":",
"to_entity_id",
",",
"'force'",
":",
"force",
",",
"}",
"api_path",
"=",
"'/v1/{mount_point}/entity/merge'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
")",
"return",
"self",
".",
"_adapter",
".",
"post",
"(",
"url",
"=",
"api_path",
",",
"json",
"=",
"params",
",",
")"
] |
Take action when AbortProcessing is raised . | def AbortProcessing ( obj , eng , callbacks , exc_info ) : msg = "Processing was aborted for object: {0}" . format ( obj . id ) eng . log . debug ( msg ) raise Break | 10,389 | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L443-L447 | [
"def",
"connect",
"(",
"self",
",",
"port",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"self",
".",
"_driver",
".",
"connect",
"(",
"port",
"=",
"port",
")",
"self",
".",
"fw_version",
"=",
"self",
".",
"_driver",
".",
"get_fw_version",
"(",
")",
"# the below call to `cache_instrument_models` is relied upon by",
"# `Session._simulate()`, which calls `robot.connect()` after exec'ing a",
"# protocol. That protocol could very well have different pipettes than",
"# what are physically attached to the robot",
"self",
".",
"cache_instrument_models",
"(",
")"
] |
All edits that are one edit away from word . | def edits1 ( word ) : letters = 'qwertyuiopasdfghjklzxcvbnm' splits = [ ( word [ : i ] , word [ i : ] ) for i in range ( len ( word ) + 1 ) ] print ( 'splits = ' , splits ) deletes = [ L + R [ 1 : ] for L , R in splits if R ] print ( 'deletes = ' , deletes ) transposes = [ L + R [ 1 ] + R [ 0 ] + R [ 2 : ] for L , R in splits if len ( R ) > 1 ] print ( 'transposes = ' , transposes ) replaces = [ L + c + R [ 1 : ] for L , R in splits if R for c in letters ] print ( 'replaces = ' , replaces ) inserts = [ L + c + R for L , R in splits for c in letters ] print ( 'inserts = ' , inserts ) print ( deletes + transposes + replaces + inserts ) print ( len ( set ( deletes + transposes + replaces + inserts ) ) ) return deletes + transposes + replaces + inserts | 10,390 | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/tezt.py#L1-L16 | [
"async",
"def",
"processClaims",
"(",
"self",
",",
"allClaims",
":",
"Dict",
"[",
"ID",
",",
"Claims",
"]",
")",
":",
"res",
"=",
"[",
"]",
"for",
"schemaId",
",",
"(",
"claim_signature",
",",
"claim_attributes",
")",
"in",
"allClaims",
".",
"items",
"(",
")",
":",
"res",
".",
"append",
"(",
"await",
"self",
".",
"processClaim",
"(",
"schemaId",
",",
"claim_attributes",
",",
"claim_signature",
")",
")",
"return",
"res"
] |
Return a Locus object for a Variant instance . | def to_locus ( variant_or_locus ) : if isinstance ( variant_or_locus , Locus ) : return variant_or_locus try : return variant_or_locus . locus except AttributeError : # IMPORTANT: if varcode someday changes from inclusive to interbase # coordinates, this will need to be updated. return Locus . from_inclusive_coordinates ( variant_or_locus . contig , variant_or_locus . start , variant_or_locus . end ) | 10,391 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L605-L634 | [
"def",
"create_calcs",
"(",
"self",
")",
":",
"specs",
"=",
"self",
".",
"_combine_core_aux_specs",
"(",
")",
"for",
"spec",
"in",
"specs",
":",
"spec",
"[",
"'dtype_out_time'",
"]",
"=",
"_prune_invalid_time_reductions",
"(",
"spec",
")",
"return",
"[",
"Calc",
"(",
"*",
"*",
"sp",
")",
"for",
"sp",
"in",
"specs",
"]"
] |
Given a 1 - base locus return the Pileup at that locus . | def pileup ( self , locus ) : locus = to_locus ( locus ) if len ( locus . positions ) != 1 : raise ValueError ( "Not a single-base locus: %s" % locus ) return self . pileups [ locus ] | 10,392 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L54-L64 | [
"def",
"cycle_file",
"(",
"source_plaintext_filename",
")",
":",
"# Create a static random master key provider",
"key_id",
"=",
"os",
".",
"urandom",
"(",
"8",
")",
"master_key_provider",
"=",
"StaticRandomMasterKeyProvider",
"(",
")",
"master_key_provider",
".",
"add_master_key",
"(",
"key_id",
")",
"ciphertext_filename",
"=",
"source_plaintext_filename",
"+",
"\".encrypted\"",
"cycled_plaintext_filename",
"=",
"source_plaintext_filename",
"+",
"\".decrypted\"",
"# Encrypt the plaintext source data",
"with",
"open",
"(",
"source_plaintext_filename",
",",
"\"rb\"",
")",
"as",
"plaintext",
",",
"open",
"(",
"ciphertext_filename",
",",
"\"wb\"",
")",
"as",
"ciphertext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"mode",
"=",
"\"e\"",
",",
"source",
"=",
"plaintext",
",",
"key_provider",
"=",
"master_key_provider",
")",
"as",
"encryptor",
":",
"for",
"chunk",
"in",
"encryptor",
":",
"ciphertext",
".",
"write",
"(",
"chunk",
")",
"# Decrypt the ciphertext",
"with",
"open",
"(",
"ciphertext_filename",
",",
"\"rb\"",
")",
"as",
"ciphertext",
",",
"open",
"(",
"cycled_plaintext_filename",
",",
"\"wb\"",
")",
"as",
"plaintext",
":",
"with",
"aws_encryption_sdk",
".",
"stream",
"(",
"mode",
"=",
"\"d\"",
",",
"source",
"=",
"ciphertext",
",",
"key_provider",
"=",
"master_key_provider",
")",
"as",
"decryptor",
":",
"for",
"chunk",
"in",
"decryptor",
":",
"plaintext",
".",
"write",
"(",
"chunk",
")",
"# Verify that the \"cycled\" (encrypted, then decrypted) plaintext is identical to the source",
"# plaintext",
"assert",
"filecmp",
".",
"cmp",
"(",
"source_plaintext_filename",
",",
"cycled_plaintext_filename",
")",
"# Verify that the encryption context used in the decrypt operation includes all key pairs from",
"# the encrypt operation",
"#",
"# In production, always use a meaningful encryption context. In this sample, we omit the",
"# encryption context (no key pairs).",
"assert",
"all",
"(",
"pair",
"in",
"decryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
"for",
"pair",
"in",
"encryptor",
".",
"header",
".",
"encryption_context",
".",
"items",
"(",
")",
")",
"return",
"ciphertext_filename",
",",
"cycled_plaintext_filename"
] |
Return a new PileupCollection instance including only pileups for the specified loci . | def at ( self , * loci ) : loci = [ to_locus ( obj ) for obj in loci ] single_position_loci = [ ] for locus in loci : for position in locus . positions : single_position_loci . append ( Locus . from_interbase_coordinates ( locus . contig , position ) ) pileups = dict ( ( locus , self . pileups [ locus ] ) for locus in single_position_loci ) return PileupCollection ( pileups , self ) | 10,393 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L66-L79 | [
"def",
"_login",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"data",
"=",
"{",
"'username'",
":",
"username",
",",
"'password'",
":",
"password",
",",
"'grant_type'",
":",
"'password'",
"}",
"r",
"=",
"self",
".",
"spark_api",
".",
"oauth",
".",
"token",
".",
"POST",
"(",
"auth",
"=",
"(",
"'spark'",
",",
"'spark'",
")",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"self",
".",
"_check_error",
"(",
"r",
")",
"return",
"r",
".",
"json",
"(",
")",
"[",
"'access_token'",
"]"
] |
The reads in this PileupCollection . All reads will have an alignment that overlaps at least one of the included loci . | def reads ( self ) : # TODO: Optimize this. def alignment_precedence ( pysam_alignment_record ) : return pysam_alignment_record . mapping_quality result = { } for pileup in self . pileups . values ( ) : for e in pileup . elements : key = read_key ( e . alignment ) if key not in result or ( alignment_precedence ( e . alignment ) > alignment_precedence ( result [ key ] ) ) : result [ key ] = e . alignment return list ( result . values ( ) ) | 10,394 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L87-L117 | [
"def",
"refresh_datasources",
"(",
"self",
",",
"datasource_name",
"=",
"None",
",",
"merge_flag",
"=",
"True",
",",
"refreshAll",
"=",
"True",
")",
":",
"ds_list",
"=",
"self",
".",
"get_datasources",
"(",
")",
"blacklist",
"=",
"conf",
".",
"get",
"(",
"'DRUID_DATA_SOURCE_BLACKLIST'",
",",
"[",
"]",
")",
"ds_refresh",
"=",
"[",
"]",
"if",
"not",
"datasource_name",
":",
"ds_refresh",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"ds",
":",
"ds",
"not",
"in",
"blacklist",
",",
"ds_list",
")",
")",
"elif",
"datasource_name",
"not",
"in",
"blacklist",
"and",
"datasource_name",
"in",
"ds_list",
":",
"ds_refresh",
".",
"append",
"(",
"datasource_name",
")",
"else",
":",
"return",
"self",
".",
"refresh",
"(",
"ds_refresh",
",",
"merge_flag",
",",
"refreshAll",
")"
] |
Collect read attributes across reads in this PileupCollection into a pandas . DataFrame . | def read_attributes ( self , attributes = None ) : def include ( attribute ) : return attributes is None or attribute in attributes reads = self . reads ( ) possible_column_names = list ( PileupCollection . _READ_ATTRIBUTE_NAMES ) result = OrderedDict ( ( name , [ getattr ( read , name ) for read in reads ] ) for name in PileupCollection . _READ_ATTRIBUTE_NAMES if include ( name ) ) # Add tag columns. if reads : tag_dicts = [ dict ( x . get_tags ( ) ) for x in reads ] tag_keys = set . union ( * [ set ( item . keys ( ) ) for item in tag_dicts ] ) for tag_key in sorted ( tag_keys ) : column_name = "TAG_%s" % tag_key possible_column_names . append ( column_name ) if include ( column_name ) : result [ column_name ] = [ d . get ( tag_key ) for d in tag_dicts ] # Lastly, we include the underlying pysam alignment record. possible_column_names . append ( "pysam_alignment_record" ) if include ( "pysam_alignment_record" ) : result [ "pysam_alignment_record" ] = reads # If particular attributes were requested, check that they're here. if attributes is not None : for attribute in attributes : if attribute not in result : raise ValueError ( "No such attribute: %s. Valid attributes are: %s" % ( attribute , " " . join ( possible_column_names ) ) ) assert set ( attributes ) == set ( result ) return pandas . DataFrame ( result ) | 10,395 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L143-L240 | [
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",
".",
"delete",
"(",
"0",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volume %s.\"",
",",
"vol_name",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volumes.\"",
")"
] |
Split the PileupCollection by the alleles suggested by the reads at the specified locus . | def group_by_allele ( self , locus ) : locus = to_locus ( locus ) read_to_allele = None loci = [ ] if locus . positions : # Our locus includes at least one reference base. for position in locus . positions : base_position = Locus . from_interbase_coordinates ( locus . contig , position ) loci . append ( base_position ) new_read_to_allele = { } for element in self . pileups [ base_position ] : allele_prefix = "" key = alignment_key ( element . alignment ) if read_to_allele is not None : try : allele_prefix = read_to_allele [ key ] except KeyError : continue allele = allele_prefix + element . bases new_read_to_allele [ key ] = allele read_to_allele = new_read_to_allele else : # Our locus is between reference bases. position_before = Locus . from_interbase_coordinates ( locus . contig , locus . start ) loci . append ( position_before ) read_to_allele = { } for element in self . pileups [ position_before ] : allele = element . bases [ 1 : ] read_to_allele [ alignment_key ( element . alignment ) ] = allele split = defaultdict ( lambda : PileupCollection ( pileups = { } , parent = self ) ) for locus in loci : pileup = self . pileups [ locus ] for e in pileup . elements : key = read_to_allele . get ( alignment_key ( e . alignment ) ) if key is not None : if locus in split [ key ] . pileups : split [ key ] . pileups [ locus ] . append ( e ) else : split [ key ] . pileups [ locus ] = Pileup ( locus , [ e ] ) # Sort by number of reads (descending). Break ties with the # lexicographic ordering of the allele string. def sorter ( pair ) : ( allele , pileup_collection ) = pair return ( - 1 * pileup_collection . num_reads ( ) , allele ) return OrderedDict ( sorted ( split . items ( ) , key = sorter ) ) | 10,396 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L249-L336 | [
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Convenience method to summarize the evidence for each of the alleles present at a locus . Applies a score function to the PileupCollection associated with each allele . | def allele_summary ( self , locus , score = lambda x : x . num_reads ( ) ) : locus = to_locus ( locus ) return [ ( allele , score ( x ) ) for ( allele , x ) in self . group_by_allele ( locus ) . items ( ) ] | 10,397 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L338-L363 | [
"def",
"_abort_all_transfers",
"(",
"self",
",",
"exception",
")",
":",
"pending_reads",
"=",
"len",
"(",
"self",
".",
"_commands_to_read",
")",
"# invalidate _transfer_list",
"for",
"transfer",
"in",
"self",
".",
"_transfer_list",
":",
"transfer",
".",
"add_error",
"(",
"exception",
")",
"# clear all deferred buffers",
"self",
".",
"_init_deferred_buffers",
"(",
")",
"# finish all pending reads and ignore the data",
"# Only do this if the error is a tranfer error.",
"# Otherwise this could cause another exception",
"if",
"isinstance",
"(",
"exception",
",",
"DAPAccessIntf",
".",
"TransferError",
")",
":",
"for",
"_",
"in",
"range",
"(",
"pending_reads",
")",
":",
"self",
".",
"_interface",
".",
"read",
"(",
")"
] |
Given a variant split the PileupCollection based on whether it the data supports the reference allele the alternate allele or neither . | def group_by_match ( self , variant ) : locus = to_locus ( variant ) if len ( variant . ref ) != len ( locus . positions ) : logging . warning ( "Ref is length %d but locus has %d bases in variant: %s" % ( len ( variant . ref ) , len ( locus . positions ) , str ( variant ) ) ) alleles_dict = self . group_by_allele ( locus ) single_base_loci = [ Locus . from_interbase_coordinates ( locus . contig , position ) for position in locus . positions ] empty_pileups = dict ( ( locus , Pileup ( locus = locus , elements = [ ] ) ) for locus in single_base_loci ) empty_collection = PileupCollection ( pileups = empty_pileups , parent = self ) ref = { variant . ref : alleles_dict . pop ( variant . ref , empty_collection ) } alt = { variant . alt : alleles_dict . pop ( variant . alt , empty_collection ) } other = alleles_dict # TODO: consider end of read issues for insertions return MatchingEvidence ( ref , alt , other ) | 10,398 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L365-L402 | [
"def",
"startAll",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Starting all threads...\"",
")",
"for",
"thread",
"in",
"self",
".",
"getThreads",
"(",
")",
":",
"thr",
"=",
"self",
".",
"getThread",
"(",
"thread",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Starting {0}\"",
".",
"format",
"(",
"thr",
".",
"name",
")",
")",
"thr",
".",
"start",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Started all threads\"",
")"
] |
Convenience method to summarize the evidence for and against a variant using a user - specified score function . | def match_summary ( self , variant , score = lambda x : x . num_reads ( ) ) : split = self . group_by_match ( variant ) def name ( allele_to_pileup_collection ) : return "," . join ( allele_to_pileup_collection ) def aggregate_and_score ( pileup_collections ) : merged = PileupCollection . merge ( * pileup_collections ) return score ( merged ) result = [ ( name ( split . ref ) , aggregate_and_score ( split . ref . values ( ) ) ) , ( name ( split . alt ) , aggregate_and_score ( split . alt . values ( ) ) ) , ] result . extend ( ( allele , score ( collection ) ) for ( allele , collection ) in split . other . items ( ) ) return result | 10,399 | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L404-L443 | [
"def",
"m2o_to_m2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")",
":",
"return",
"m2o_to_x2m",
"(",
"cr",
",",
"model",
",",
"table",
",",
"field",
",",
"source_field",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.