query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
listlengths 20
553
|
|---|---|---|---|---|
Change to the privilege mode .
|
def enable ( self , enable_password ) : if self . device . prompt [ - 1 ] == '#' : self . log ( "Device is already in privileged mode" ) return events = [ self . password_re , self . device . prompt_re , pexpect . TIMEOUT , pexpect . EOF ] transitions = [ ( self . password_re , [ 0 ] , 1 , partial ( a_send_password , enable_password ) , 10 ) , ( self . password_re , [ 1 ] , - 1 , ConnectionAuthenticationError ( "Incorrect enable password" , self . device . hostname ) , 0 ) , ( self . device . prompt_re , [ 0 , 1 , 2 , 3 ] , - 1 , a_expected_prompt , 0 ) , ( pexpect . TIMEOUT , [ 0 , 1 , 2 ] , - 1 , ConnectionAuthenticationError ( "Unable to get privileged mode" , self . device . hostname ) , 0 ) , ( pexpect . EOF , [ 0 , 1 , 2 ] , - 1 , ConnectionError ( "Device disconnected" ) , 0 ) ] self . device . ctrl . send_command ( self . enable_cmd ) fsm = FSM ( "IOS-ENABLE" , self . device , events , transitions , timeout = 10 , max_transitions = 5 ) fsm . run ( ) if self . device . prompt [ - 1 ] != '#' : raise ConnectionAuthenticationError ( "Privileged mode not set" , self . device . hostname )
| 3,000
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/IOS.py#L48-L68
|
[
"def",
"replace_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"video_key",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_video_path",
")",
"# Setup API client",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
"\"Updating Video\"",
")",
"try",
":",
"response",
"=",
"jwplatform_client",
".",
"videos",
".",
"update",
"(",
"video_key",
"=",
"video_key",
",",
"upload_method",
"=",
"'s3'",
",",
"update_file",
"=",
"'True'",
",",
"*",
"*",
"kwargs",
")",
"except",
"jwplatform",
".",
"errors",
".",
"JWPlatformError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Encountered an error updating the video\\n{}\"",
".",
"format",
"(",
"e",
")",
")",
"sys",
".",
"exit",
"(",
"e",
".",
"message",
")",
"logging",
".",
"info",
"(",
"response",
")",
"# Construct base url for upload",
"upload_url",
"=",
"'{}://{}{}'",
".",
"format",
"(",
"response",
"[",
"'link'",
"]",
"[",
"'protocol'",
"]",
",",
"response",
"[",
"'link'",
"]",
"[",
"'address'",
"]",
",",
"response",
"[",
"'link'",
"]",
"[",
"'path'",
"]",
")",
"# Query parameters for the upload",
"query_parameters",
"=",
"response",
"[",
"'link'",
"]",
"[",
"'query'",
"]",
"# HTTP PUT upload using requests",
"headers",
"=",
"{",
"'Content-Disposition'",
":",
"'attachment; filename=\"{}\"'",
".",
"format",
"(",
"filename",
")",
"}",
"with",
"open",
"(",
"local_video_path",
",",
"'rb'",
")",
"as",
"f",
":",
"r",
"=",
"requests",
".",
"put",
"(",
"upload_url",
",",
"params",
"=",
"query_parameters",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"f",
")",
"logging",
".",
"info",
"(",
"'uploading file {} to url {}'",
".",
"format",
"(",
"local_video_path",
",",
"r",
".",
"url",
")",
")",
"logging",
".",
"info",
"(",
"'upload response: {}'",
".",
"format",
"(",
"r",
".",
"text",
")",
")",
"logging",
".",
"info",
"(",
"r",
")"
] |
Gets a list of descriptions given the tag .
|
def description ( tag ) : tag_object = Tag ( tag ) results = [ ] results . extend ( tag_object . descriptions ) subtags = tag_object . subtags for subtag in subtags : results += subtag . description return results
| 3,001
|
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/tags.py#L117-L131
|
[
"def",
"log10",
"(",
"self",
",",
"floor",
"=",
"None",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
",",
"floor",
")",
":",
"arr",
"=",
"dataset",
"[",
"s",
"]",
"arr",
"=",
"np",
".",
"log10",
"(",
"arr",
")",
"if",
"floor",
"is",
"not",
"None",
":",
"arr",
"[",
"arr",
"<",
"floor",
"]",
"=",
"floor",
"dataset",
"[",
"s",
"]",
"=",
"arr",
"self",
".",
"chunkwise",
"(",
"f",
",",
"floor",
"=",
"floor",
")"
] |
Draw N samples from the prior .
|
def prior_draw ( self , N = 1 ) : p = np . random . ranf ( size = ( N , self . ndim ) ) p = ( self . _upper_right - self . _lower_left ) * p + self . _lower_left return p
| 3,002
|
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/examples/twoD.py#L49-L55
|
[
"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"
] |
Use a uniform bounded prior .
|
def lnprior ( self , X ) : if np . any ( X < self . _lower_left ) or np . any ( X > self . _upper_right ) : return - np . inf else : return 0.0
| 3,003
|
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/examples/twoD.py#L57-L64
|
[
"def",
"parse_from_file",
"(",
"filename",
",",
"nodata",
"=",
"False",
")",
":",
"header",
"=",
"None",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"file",
":",
"header",
"=",
"read_machine_header",
"(",
"file",
")",
"meta_raw",
"=",
"file",
".",
"read",
"(",
"header",
"[",
"'meta_len'",
"]",
")",
"meta",
"=",
"__parse_meta",
"(",
"meta_raw",
",",
"header",
")",
"data",
"=",
"b''",
"if",
"not",
"nodata",
":",
"data",
"=",
"__decompress",
"(",
"meta",
",",
"file",
".",
"read",
"(",
"header",
"[",
"'data_len'",
"]",
")",
")",
"return",
"header",
",",
"meta",
",",
"data"
] |
Use a softened version of the interpolant as a likelihood .
|
def lnlike ( self , X ) : return - 3.5 * np . log ( self . _interpolant ( X [ 0 ] , X [ 1 ] , grid = False ) )
| 3,004
|
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/examples/twoD.py#L66-L70
|
[
"def",
"_SeparateTypes",
"(",
"self",
",",
"metadata_value_pairs",
")",
":",
"registry_pairs",
"=",
"[",
"]",
"file_pairs",
"=",
"[",
"]",
"match_pairs",
"=",
"[",
"]",
"for",
"metadata",
",",
"result",
"in",
"metadata_value_pairs",
":",
"if",
"(",
"result",
".",
"stat_entry",
".",
"pathspec",
".",
"pathtype",
"==",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"REGISTRY",
")",
":",
"registry_pairs",
".",
"append",
"(",
"(",
"metadata",
",",
"result",
".",
"stat_entry",
")",
")",
"else",
":",
"file_pairs",
".",
"append",
"(",
"(",
"metadata",
",",
"result",
")",
")",
"match_pairs",
".",
"extend",
"(",
"[",
"(",
"metadata",
",",
"match",
")",
"for",
"match",
"in",
"result",
".",
"matches",
"]",
")",
"return",
"registry_pairs",
",",
"file_pairs",
",",
"match_pairs"
] |
Print detected information .
|
def echo_info ( conn ) : click . echo ( "General information:" ) click . echo ( " Hostname: {}" . format ( conn . hostname ) ) click . echo ( " HW Family: {}" . format ( conn . family ) ) click . echo ( " HW Platform: {}" . format ( conn . platform ) ) click . echo ( " SW Type: {}" . format ( conn . os_type ) ) click . echo ( " SW Version: {}" . format ( conn . os_version ) ) click . echo ( " Prompt: {}" . format ( conn . prompt ) ) click . echo ( " Console connection: {}" . format ( conn . is_console ) ) click . echo ( "\nUDI:" ) click . echo ( " PID: {}" . format ( conn . pid ) ) click . echo ( " Description: {}" . format ( conn . description ) ) click . echo ( " Name: {}" . format ( conn . name ) ) click . echo ( " SN: {}" . format ( conn . sn ) ) click . echo ( " VID: {}" . format ( conn . vid ) )
| 3,005
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/__main__.py#L16-L32
|
[
"def",
"validate_arguments",
"(",
"log",
",",
"whitelisted_args",
",",
"args",
")",
":",
"valid_patterns",
"=",
"{",
"re",
".",
"compile",
"(",
"p",
")",
":",
"v",
"for",
"p",
",",
"v",
"in",
"whitelisted_args",
".",
"items",
"(",
")",
"}",
"def",
"validate",
"(",
"idx",
")",
":",
"arg",
"=",
"args",
"[",
"idx",
"]",
"for",
"pattern",
",",
"has_argument",
"in",
"valid_patterns",
".",
"items",
"(",
")",
":",
"if",
"pattern",
".",
"match",
"(",
"arg",
")",
":",
"return",
"2",
"if",
"has_argument",
"else",
"1",
"log",
".",
"warn",
"(",
"\"Zinc argument '{}' is not supported, and is subject to change/removal!\"",
".",
"format",
"(",
"arg",
")",
")",
"return",
"1",
"arg_index",
"=",
"0",
"while",
"arg_index",
"<",
"len",
"(",
"args",
")",
":",
"arg_index",
"+=",
"validate",
"(",
"arg_index",
")"
] |
Run the main function .
|
def run ( url , cmd , log_path , log_level , log_session , force_discovery , print_info ) : log_level = log_levels [ log_level ] conn = condoor . Connection ( "host" , list ( url ) , log_session = log_session , log_level = log_level , log_dir = log_path ) try : conn . connect ( force_discovery = force_discovery ) if print_info : echo_info ( conn ) for command in cmd : result = conn . send ( command ) print ( "\nCommand: {}" . format ( command ) ) print ( "Result: \n{}" . format ( result ) ) except ( condoor . ConnectionError , condoor . ConnectionAuthenticationError , condoor . ConnectionTimeoutError , condoor . InvalidHopInfoError , condoor . CommandSyntaxError , condoor . CommandTimeoutError , condoor . CommandError , condoor . ConnectionError ) as excpt : click . echo ( excpt ) finally : conn . disconnect ( ) return
| 3,006
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/__main__.py#L77-L96
|
[
"def",
"set_temperature",
"(",
"self",
",",
"zone",
",",
"temperature",
",",
"until",
"=",
"None",
")",
":",
"if",
"until",
"is",
"None",
":",
"data",
"=",
"{",
"\"Value\"",
":",
"temperature",
",",
"\"Status\"",
":",
"\"Hold\"",
",",
"\"NextTime\"",
":",
"None",
"}",
"else",
":",
"data",
"=",
"{",
"\"Value\"",
":",
"temperature",
",",
"\"Status\"",
":",
"\"Temporary\"",
",",
"\"NextTime\"",
":",
"until",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
"}",
"self",
".",
"_set_heat_setpoint",
"(",
"zone",
",",
"data",
")"
] |
Convert to URL scheme .
|
def convert ( self , value , param , ctx ) : if not isinstance ( value , tuple ) : parsed = urlparse . urlparse ( value ) if parsed . scheme not in ( 'telnet' , 'ssh' ) : self . fail ( 'invalid URL scheme (%s). Only telnet and ssh URLs are ' 'allowed' % parsed , param , ctx ) return value
| 3,007
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/__main__.py#L40-L47
|
[
"def",
"write_result_stream",
"(",
"result_stream",
",",
"filename_prefix",
"=",
"None",
",",
"results_per_file",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"result_stream",
",",
"types",
".",
"GeneratorType",
")",
":",
"stream",
"=",
"result_stream",
"else",
":",
"stream",
"=",
"result_stream",
".",
"stream",
"(",
")",
"file_time_formatter",
"=",
"\"%Y-%m-%dT%H_%M_%S\"",
"if",
"filename_prefix",
"is",
"None",
":",
"filename_prefix",
"=",
"\"twitter_search_results\"",
"if",
"results_per_file",
":",
"logger",
".",
"info",
"(",
"\"chunking result stream to files with {} tweets per file\"",
".",
"format",
"(",
"results_per_file",
")",
")",
"chunked_stream",
"=",
"partition",
"(",
"stream",
",",
"results_per_file",
",",
"pad_none",
"=",
"True",
")",
"for",
"chunk",
"in",
"chunked_stream",
":",
"chunk",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"chunk",
")",
"curr_datetime",
"=",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"file_time_formatter",
")",
")",
"_filename",
"=",
"\"{}_{}.json\"",
".",
"format",
"(",
"filename_prefix",
",",
"curr_datetime",
")",
"yield",
"from",
"write_ndjson",
"(",
"_filename",
",",
"chunk",
")",
"else",
":",
"curr_datetime",
"=",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"file_time_formatter",
")",
")",
"_filename",
"=",
"\"{}.json\"",
".",
"format",
"(",
"filename_prefix",
")",
"yield",
"from",
"write_ndjson",
"(",
"_filename",
",",
"stream",
")"
] |
Send text line to the controller followed by os . linesep .
|
def a_send_line ( text , ctx ) : if hasattr ( text , '__iter__' ) : try : ctx . ctrl . sendline ( text . next ( ) ) except StopIteration : ctx . finished = True else : ctx . ctrl . sendline ( text ) return True
| 3,008
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L9-L18
|
[
"def",
"validate_submission",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_prepare_temp_dir",
"(",
")",
"# Convert filename to be absolute path, relative path might cause problems",
"# with mounting directory in Docker",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"# extract submission",
"if",
"not",
"self",
".",
"_extract_submission",
"(",
"filename",
")",
":",
"return",
"None",
"# verify submission size",
"if",
"not",
"self",
".",
"_verify_submission_size",
"(",
")",
":",
"return",
"None",
"# Load metadata",
"metadata",
"=",
"self",
".",
"_load_and_verify_metadata",
"(",
")",
"if",
"not",
"metadata",
":",
"return",
"None",
"submission_type",
"=",
"metadata",
"[",
"'type'",
"]",
"# verify docker container size",
"if",
"not",
"self",
".",
"_verify_docker_image_size",
"(",
"metadata",
"[",
"'container_gpu'",
"]",
")",
":",
"return",
"None",
"# Try to run submission on sample data",
"self",
".",
"_prepare_sample_data",
"(",
"submission_type",
")",
"if",
"not",
"self",
".",
"_run_submission",
"(",
"metadata",
")",
":",
"logging",
".",
"error",
"(",
"'Failure while running submission'",
")",
"return",
"None",
"if",
"not",
"self",
".",
"_verify_output",
"(",
"submission_type",
")",
":",
"logging",
".",
"warning",
"(",
"'Some of the outputs of your submission are invalid or '",
"'missing. You submission still will be evaluation '",
"'but you might get lower score.'",
")",
"return",
"metadata"
] |
Sent the username text .
|
def a_send_username ( username , ctx ) : if username : ctx . ctrl . sendline ( username ) return True else : ctx . ctrl . disconnect ( ) raise ConnectionAuthenticationError ( "Username not provided" , ctx . ctrl . hostname )
| 3,009
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L29-L36
|
[
"def",
"_init_regs_random",
"(",
"self",
")",
":",
"# Generate random values and make sure they are all different.",
"values",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"self",
".",
"_arch_regs_parent",
")",
":",
"values",
".",
"add",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"self",
".",
"_arch_info",
".",
"operand_size",
"-",
"1",
")",
")",
"values",
"=",
"list",
"(",
"values",
")",
"# Assign random values to registers.",
"regs",
"=",
"{",
"}",
"for",
"idx",
",",
"reg",
"in",
"enumerate",
"(",
"self",
".",
"_arch_regs_parent",
")",
":",
"regs",
"[",
"reg",
"]",
"=",
"values",
"[",
"idx",
"]",
"&",
"(",
"2",
"**",
"self",
".",
"_arch_regs_size",
"[",
"reg",
"]",
"-",
"1",
")",
"return",
"regs"
] |
Send the password text .
|
def a_send_password ( password , ctx ) : if password : ctx . ctrl . send_command ( password , password = True ) return True else : ctx . ctrl . disconnect ( ) raise ConnectionAuthenticationError ( "Password not provided" , ctx . ctrl . hostname )
| 3,010
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L40-L51
|
[
"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",
")"
] |
Raise ConnectionError exception when connected to standby console .
|
def a_standby_console ( ctx ) : ctx . device . is_console = True ctx . ctrl . disconnect ( ) raise ConnectionError ( "Standby console" , ctx . ctrl . hostname )
| 3,011
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L82-L86
|
[
"def",
"populateFromDirectory",
"(",
"self",
",",
"vcfDirectory",
")",
":",
"pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vcfDirectory",
",",
"\"*.vcf.gz\"",
")",
"dataFiles",
"=",
"[",
"]",
"indexFiles",
"=",
"[",
"]",
"for",
"vcfFile",
"in",
"glob",
".",
"glob",
"(",
"pattern",
")",
":",
"dataFiles",
".",
"append",
"(",
"vcfFile",
")",
"indexFiles",
".",
"append",
"(",
"vcfFile",
"+",
"\".tbi\"",
")",
"self",
".",
"populateFromFile",
"(",
"dataFiles",
",",
"indexFiles",
")"
] |
Provide the message that current software is not committed and reload is not possible .
|
def a_not_committed ( ctx ) : ctx . ctrl . sendline ( 'n' ) ctx . msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx . device . chain . connection . emit_message ( ctx . msg , log_level = logging . ERROR ) ctx . failed = True return False
| 3,012
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L107-L113
|
[
"def",
"correspondence",
"(",
"soup",
")",
":",
"correspondence",
"=",
"[",
"]",
"author_notes_nodes",
"=",
"raw_parser",
".",
"author_notes",
"(",
"soup",
")",
"if",
"author_notes_nodes",
":",
"corresp_nodes",
"=",
"raw_parser",
".",
"corresp",
"(",
"author_notes_nodes",
")",
"for",
"tag",
"in",
"corresp_nodes",
":",
"correspondence",
".",
"append",
"(",
"tag",
".",
"text",
")",
"return",
"correspondence"
] |
Stay connected .
|
def a_stays_connected ( ctx ) : ctx . ctrl . connected = True ctx . device . connected = False return True
| 3,013
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L126-L130
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Provide message when received humphost prompt .
|
def a_unexpected_prompt ( ctx ) : prompt = ctx . ctrl . match . group ( 0 ) ctx . msg = "Received the jump host prompt: '{}'" . format ( prompt ) ctx . device . connected = False ctx . finished = True raise ConnectionError ( "Unable to connect to the device." , ctx . ctrl . hostname )
| 3,014
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L134-L140
|
[
"def",
"delete",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"delete\"",
",",
"\"()V\"",
")",
"else",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"delete\"",
",",
"\"(I)V\"",
",",
"index",
")"
] |
Check the prompt and update the drivers .
|
def a_connection_timeout ( ctx ) : prompt = ctx . ctrl . after ctx . msg = "Received the jump host prompt: '{}'" . format ( prompt ) ctx . device . connected = False ctx . finished = True raise ConnectionTimeoutError ( "Unable to connect to the device." , ctx . ctrl . hostname )
| 3,015
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L144-L150
|
[
"def",
"delete_external_event",
"(",
"self",
",",
"calendar_id",
",",
"event_uid",
")",
":",
"self",
".",
"request_handler",
".",
"delete",
"(",
"endpoint",
"=",
"'calendars/%s/events'",
"%",
"calendar_id",
",",
"data",
"=",
"{",
"'event_uid'",
":",
"event_uid",
"}",
")"
] |
Update driver config mode and hostname when received an expected prompt .
|
def a_expected_prompt ( ctx ) : prompt = ctx . ctrl . match . group ( 0 ) ctx . device . update_driver ( prompt ) ctx . device . update_config_mode ( ) ctx . device . update_hostname ( ) ctx . finished = True return True
| 3,016
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L154-L161
|
[
"def",
"decrease_frequency",
"(",
"self",
",",
"frequency",
"=",
"None",
")",
":",
"if",
"frequency",
"is",
"None",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"decreaseFrequency\"",
",",
"\"()V\"",
")",
"else",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"decreaseFrequency\"",
",",
"\"(I)V\"",
",",
"frequency",
")"
] |
Send new line and reconnect .
|
def a_return_and_reconnect ( ctx ) : ctx . ctrl . send ( "\r" ) ctx . device . connect ( ctx . ctrl ) return True
| 3,017
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L186-L190
|
[
"def",
"createMSBWTFromBam",
"(",
"bamFNs",
",",
"outputDir",
",",
"numProcs",
",",
"areUniform",
",",
"logger",
")",
":",
"#generate the files we will reference and clear out the in memory array before making the BWT",
"logger",
".",
"info",
"(",
"'Saving sorted sequences...'",
")",
"seqFN",
"=",
"outputDir",
"+",
"'/seqs.npy'",
"offsetFN",
"=",
"outputDir",
"+",
"'/offsets.npy'",
"abtFN",
"=",
"outputDir",
"+",
"'/about.npy'",
"bwtFN",
"=",
"outputDir",
"+",
"'/msbwt.npy'",
"MSBWTGen",
".",
"clearAuxiliaryData",
"(",
"outputDir",
")",
"preprocessBams",
"(",
"bamFNs",
",",
"seqFN",
",",
"offsetFN",
",",
"abtFN",
",",
"areUniform",
",",
"logger",
")",
"MSBWTGen",
".",
"createFromSeqs",
"(",
"seqFN",
",",
"offsetFN",
",",
"bwtFN",
",",
"numProcs",
",",
"areUniform",
",",
"logger",
")"
] |
Store the command result for complex state machines .
|
def a_store_cmd_result ( ctx ) : result = ctx . ctrl . before # check if multi line index = result . find ( '\n' ) if index > 0 : # remove first line result = result [ index + 1 : ] ctx . device . last_command_result = result . replace ( '\r' , '' ) return True
| 3,018
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L194-L206
|
[
"def",
"_add_open_file",
"(",
"self",
",",
"file_obj",
")",
":",
"if",
"self",
".",
"_free_fd_heap",
":",
"open_fd",
"=",
"heapq",
".",
"heappop",
"(",
"self",
".",
"_free_fd_heap",
")",
"self",
".",
"open_files",
"[",
"open_fd",
"]",
"=",
"[",
"file_obj",
"]",
"return",
"open_fd",
"self",
".",
"open_files",
".",
"append",
"(",
"[",
"file_obj",
"]",
")",
"return",
"len",
"(",
"self",
".",
"open_files",
")",
"-",
"1"
] |
Message the captured pattern .
|
def a_message_callback ( ctx ) : message = ctx . ctrl . after . strip ( ) . splitlines ( ) [ - 1 ] ctx . device . chain . connection . emit_message ( message , log_level = logging . INFO ) return True
| 3,019
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L210-L214
|
[
"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",
")"
] |
Capture the show configuration failed result .
|
def a_capture_show_configuration_failed ( ctx ) : result = ctx . device . send ( "show configuration failed" ) ctx . device . last_command_result = result index = result . find ( "SEMANTIC ERRORS" ) ctx . device . chain . connection . emit_message ( result , log_level = logging . ERROR ) if index > 0 : raise ConfigurationSemanticErrors ( result ) else : raise ConfigurationErrors ( result )
| 3,020
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L218-L227
|
[
"def",
"get_ddlib_feats",
"(",
"span",
",",
"context",
",",
"idxs",
")",
":",
"if",
"span",
".",
"stable_id",
"not",
"in",
"unary_ddlib_feats",
":",
"unary_ddlib_feats",
"[",
"span",
".",
"stable_id",
"]",
"=",
"set",
"(",
")",
"for",
"seq_feat",
"in",
"_get_seq_features",
"(",
"context",
",",
"idxs",
")",
":",
"unary_ddlib_feats",
"[",
"span",
".",
"stable_id",
"]",
".",
"add",
"(",
"seq_feat",
")",
"for",
"window_feat",
"in",
"_get_window_features",
"(",
"context",
",",
"idxs",
")",
":",
"unary_ddlib_feats",
"[",
"span",
".",
"stable_id",
"]",
".",
"add",
"(",
"window_feat",
")",
"for",
"f",
"in",
"unary_ddlib_feats",
"[",
"span",
".",
"stable_id",
"]",
":",
"yield",
"f"
] |
Raise the configuration inconsistency error .
|
def a_configuration_inconsistency ( ctx ) : ctx . msg = "This SDR's running configuration is inconsistent with persistent configuration. " "No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' " "command is performed." ctx . device . chain . connection . emit_message ( "Configuration inconsistency." , log_level = logging . ERROR ) ctx . finished = True raise ConfigurationErrors ( "Configuration inconsistency." )
| 3,021
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/actions.py#L231-L239
|
[
"def",
"_get_aug_flow",
"(",
"left",
",",
"left_type",
",",
"aug_opnode",
",",
"right",
",",
"right_type",
",",
"context",
",",
"reverse_context",
")",
":",
"bin_op",
"=",
"aug_opnode",
".",
"op",
".",
"strip",
"(",
"\"=\"",
")",
"aug_op",
"=",
"aug_opnode",
".",
"op",
"if",
"_same_type",
"(",
"left_type",
",",
"right_type",
")",
":",
"methods",
"=",
"[",
"_aug_op",
"(",
"left",
",",
"aug_opnode",
",",
"aug_op",
",",
"right",
",",
"context",
")",
",",
"_bin_op",
"(",
"left",
",",
"aug_opnode",
",",
"bin_op",
",",
"right",
",",
"context",
")",
",",
"]",
"elif",
"helpers",
".",
"is_subtype",
"(",
"left_type",
",",
"right_type",
")",
":",
"methods",
"=",
"[",
"_aug_op",
"(",
"left",
",",
"aug_opnode",
",",
"aug_op",
",",
"right",
",",
"context",
")",
",",
"_bin_op",
"(",
"left",
",",
"aug_opnode",
",",
"bin_op",
",",
"right",
",",
"context",
")",
",",
"]",
"elif",
"helpers",
".",
"is_supertype",
"(",
"left_type",
",",
"right_type",
")",
":",
"methods",
"=",
"[",
"_aug_op",
"(",
"left",
",",
"aug_opnode",
",",
"aug_op",
",",
"right",
",",
"context",
")",
",",
"_bin_op",
"(",
"right",
",",
"aug_opnode",
",",
"bin_op",
",",
"left",
",",
"reverse_context",
",",
"reverse",
"=",
"True",
")",
",",
"_bin_op",
"(",
"left",
",",
"aug_opnode",
",",
"bin_op",
",",
"right",
",",
"context",
")",
",",
"]",
"else",
":",
"methods",
"=",
"[",
"_aug_op",
"(",
"left",
",",
"aug_opnode",
",",
"aug_op",
",",
"right",
",",
"context",
")",
",",
"_bin_op",
"(",
"left",
",",
"aug_opnode",
",",
"bin_op",
",",
"right",
",",
"context",
")",
",",
"_bin_op",
"(",
"right",
",",
"aug_opnode",
",",
"bin_op",
",",
"left",
",",
"reverse_context",
",",
"reverse",
"=",
"True",
")",
",",
"]",
"return",
"methods"
] |
Returns the string used to identify the client when initiating a SMTP session .
|
def fqdn ( self ) : if self . _fqdn is None : # Let's try to retrieve it: self . _fqdn = socket . getfqdn ( ) if "." not in self . _fqdn : try : info = socket . getaddrinfo ( host = "localhost" , port = None , proto = socket . IPPROTO_TCP ) except socket . gaierror : addr = "127.0.0.1" else : # We only consider the first returned result and we're # only interested in getting the IP(v4 or v6) address: addr = info [ 0 ] [ 4 ] [ 0 ] self . _fqdn = "[{}]" . format ( addr ) return self . _fqdn
| 3,022
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L132-L166
|
[
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Resets some attributes to their default values .
|
def reset_state ( self ) : self . last_helo_response = ( None , None ) self . last_ehlo_response = ( None , None ) self . supports_esmtp = False self . esmtp_extensions = { } self . auth_mechanisms = [ ] self . ssl_context = False self . reader = None self . writer = None self . transport = None
| 3,023
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L168-L189
|
[
"def",
"add_parens",
"(",
"line",
",",
"maxline",
",",
"indent",
",",
"statements",
"=",
"statements",
",",
"count",
"=",
"count",
")",
":",
"if",
"line",
"[",
"0",
"]",
"in",
"statements",
":",
"index",
"=",
"1",
"if",
"not",
"line",
"[",
"0",
"]",
".",
"endswith",
"(",
"' '",
")",
":",
"index",
"=",
"2",
"assert",
"line",
"[",
"1",
"]",
"==",
"' '",
"line",
".",
"insert",
"(",
"index",
",",
"'('",
")",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"':'",
":",
"line",
".",
"insert",
"(",
"-",
"1",
",",
"')'",
")",
"else",
":",
"line",
".",
"append",
"(",
"')'",
")",
"# That was the easy stuff. Now for assignments.",
"groups",
"=",
"list",
"(",
"get_assign_groups",
"(",
"line",
")",
")",
"if",
"len",
"(",
"groups",
")",
"==",
"1",
":",
"# So sad, too bad",
"return",
"line",
"counts",
"=",
"list",
"(",
"count",
"(",
"x",
")",
"for",
"x",
"in",
"groups",
")",
"didwrap",
"=",
"False",
"# If the LHS is large, wrap it first",
"if",
"sum",
"(",
"counts",
"[",
":",
"-",
"1",
"]",
")",
">=",
"maxline",
"-",
"indent",
"-",
"4",
":",
"for",
"group",
"in",
"groups",
"[",
":",
"-",
"1",
"]",
":",
"didwrap",
"=",
"False",
"# Only want to know about last group",
"if",
"len",
"(",
"group",
")",
">",
"1",
":",
"group",
".",
"insert",
"(",
"0",
",",
"'('",
")",
"group",
".",
"insert",
"(",
"-",
"1",
",",
"')'",
")",
"didwrap",
"=",
"True",
"# Might not need to wrap the RHS if wrapped the LHS",
"if",
"not",
"didwrap",
"or",
"counts",
"[",
"-",
"1",
"]",
">",
"maxline",
"-",
"indent",
"-",
"10",
":",
"groups",
"[",
"-",
"1",
"]",
".",
"insert",
"(",
"0",
",",
"'('",
")",
"groups",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"')'",
")",
"return",
"[",
"item",
"for",
"group",
"in",
"groups",
"for",
"item",
"in",
"group",
"]"
] |
Sends a SMTP HELO command . - Identifies the client and starts the session .
|
async def helo ( self , from_host = None ) : if from_host is None : from_host = self . fqdn code , message = await self . do_cmd ( "HELO" , from_host ) self . last_helo_response = ( code , message ) return code , message
| 3,024
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L308-L338
|
[
"def",
"_get_purecn_dx_files",
"(",
"paired",
",",
"out",
")",
":",
"out_base",
"=",
"\"%s-dx\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"out",
"[",
"\"rds\"",
"]",
")",
"[",
"0",
"]",
"all_files",
"=",
"[",
"]",
"for",
"key",
",",
"ext",
"in",
"[",
"[",
"(",
"\"mutation_burden\"",
",",
")",
",",
"\"_mutation_burden.csv\"",
"]",
",",
"[",
"(",
"\"plot\"",
",",
"\"signatures\"",
")",
",",
"\"_signatures.pdf\"",
"]",
",",
"[",
"(",
"\"signatures\"",
",",
")",
",",
"\"_signatures.csv\"",
"]",
"]",
":",
"cur_file",
"=",
"\"%s%s\"",
"%",
"(",
"out_base",
",",
"ext",
")",
"out",
"=",
"tz",
".",
"update_in",
"(",
"out",
",",
"key",
",",
"lambda",
"x",
":",
"cur_file",
")",
"all_files",
".",
"append",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"cur_file",
")",
")",
"return",
"out_base",
",",
"out",
",",
"all_files"
] |
Sends a SMTP EHLO command . - Identifies the client and starts the session .
|
async def ehlo ( self , from_host = None ) : if from_host is None : from_host = self . fqdn code , message = await self . do_cmd ( "EHLO" , from_host ) self . last_ehlo_response = ( code , message ) extns , auths = SMTP . parse_esmtp_extensions ( message ) self . esmtp_extensions = extns self . auth_mechanisms = auths self . supports_esmtp = True return code , message
| 3,025
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L340-L375
|
[
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"match_path",
"=",
"path",
"return",
"dict",
"(",
"[",
"i",
"for",
"i",
"in",
"_recurmatch",
"(",
"match_path",
",",
"aug",
")",
"]",
")"
] |
Sends a SMTP HELP command .
|
async def help ( self , command_name = None ) : if command_name is None : command_name = "" code , message = await self . do_cmd ( "HELP" , command_name ) return message
| 3,026
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L377-L403
|
[
"def",
"GetBaseFiles",
"(",
"self",
",",
"diff",
")",
":",
"files",
"=",
"{",
"}",
"for",
"line",
"in",
"diff",
".",
"splitlines",
"(",
"True",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'Index:'",
")",
"or",
"line",
".",
"startswith",
"(",
"'Property changes on:'",
")",
":",
"unused",
",",
"filename",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"# On Windows if a file has property changes its filename uses '\\'",
"# instead of '/'.",
"filename",
"=",
"to_slash",
"(",
"filename",
".",
"strip",
"(",
")",
")",
"files",
"[",
"filename",
"]",
"=",
"self",
".",
"GetBaseFile",
"(",
"filename",
")",
"return",
"files"
] |
Sends a SMTP MAIL command . - Starts the mail transfer session .
|
async def mail ( self , sender , options = None ) : if options is None : options = [ ] from_addr = "FROM:{}" . format ( quoteaddr ( sender ) ) code , message = await self . do_cmd ( "MAIL" , from_addr , * options ) return code , message
| 3,027
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L487-L517
|
[
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"match_path",
"=",
"path",
"return",
"dict",
"(",
"[",
"i",
"for",
"i",
"in",
"_recurmatch",
"(",
"match_path",
",",
"aug",
")",
"]",
")"
] |
Sends a SMTP RCPT command . - Indicates a recipient for the e - mail .
|
async def rcpt ( self , recipient , options = None ) : if options is None : options = [ ] to_addr = "TO:{}" . format ( quoteaddr ( recipient ) ) code , message = await self . do_cmd ( "RCPT" , to_addr , * options ) return code , message
| 3,028
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L519-L549
|
[
"def",
"BitVecFuncVal",
"(",
"value",
":",
"int",
",",
"func_name",
":",
"str",
",",
"size",
":",
"int",
",",
"annotations",
":",
"Annotations",
"=",
"None",
",",
"input_",
":",
"Union",
"[",
"int",
",",
"\"BitVec\"",
"]",
"=",
"None",
",",
")",
"->",
"BitVecFunc",
":",
"raw",
"=",
"z3",
".",
"BitVecVal",
"(",
"value",
",",
"size",
")",
"return",
"BitVecFunc",
"(",
"raw",
",",
"func_name",
",",
"input_",
",",
"annotations",
")"
] |
Sends a SMTP QUIT command . - Ends the session .
|
async def quit ( self ) : code = - 1 message = None try : code , message = await self . do_cmd ( "QUIT" ) except ConnectionError : # We voluntarily ignore this kind of exceptions since... the # connection seems already closed. pass except SMTPCommandFailedError : pass await self . close ( ) return code , message
| 3,029
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L551-L578
|
[
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"match_path",
"=",
"path",
"return",
"dict",
"(",
"[",
"i",
"for",
"i",
"in",
"_recurmatch",
"(",
"match_path",
",",
"aug",
")",
"]",
")"
] |
Sends a SMTP DATA command . - Transmits the message to the server .
|
async def data ( self , email_message ) : code , message = await self . do_cmd ( "DATA" , success = ( 354 , ) ) email_message = SMTP . prepare_message ( email_message ) self . writer . write ( email_message ) # write is non-blocking. await self . writer . drain ( ) # don't forget to drain. code , message = await self . reader . read_reply ( ) return code , message
| 3,030
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L580-L616
|
[
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"match_path",
"=",
"path",
"return",
"dict",
"(",
"[",
"i",
"for",
"i",
"in",
"_recurmatch",
"(",
"match_path",
",",
"aug",
")",
"]",
")"
] |
Tries to authenticate user against the SMTP server .
|
async def auth ( self , username , password ) : # EHLO/HELO is required: await self . ehlo_or_helo_if_needed ( ) errors = [ ] # To store SMTPAuthenticationErrors code = message = None # Try to authenticate using all mechanisms supported by both # server and client (and only these): for auth , meth in self . __class__ . _supported_auth_mechanisms . items ( ) : if auth in self . auth_mechanisms : auth_func = getattr ( self , meth ) try : code , message = await auth_func ( username , password ) except SMTPAuthenticationError as e : errors . append ( e ) else : break else : if not errors : err = "Could not find any suitable authentication mechanism." errors . append ( SMTPAuthenticationError ( - 1 , err ) ) raise SMTPLoginError ( errors ) return code , message
| 3,031
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L618-L664
|
[
"def",
"readDir",
"(",
"dirPath",
",",
"numLabels",
",",
"modify",
"=",
"False",
")",
":",
"samplesDict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"_",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dirPath",
")",
":",
"for",
"f",
"in",
"files",
":",
"basename",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"if",
"\".\"",
"in",
"basename",
"and",
"extension",
"==",
"\".csv\"",
":",
"category",
"=",
"basename",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"if",
"modify",
":",
"category",
"=",
"category",
".",
"replace",
"(",
"\"0\"",
",",
"\"/\"",
")",
"category",
"=",
"category",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")",
"samplesDict",
"[",
"category",
"]",
"=",
"readCSV",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirPath",
",",
"f",
")",
",",
"numLabels",
"=",
"numLabels",
")",
"return",
"samplesDict"
] |
Upgrades the connection to the SMTP server into TLS mode .
|
async def starttls ( self , context = None ) : if not self . use_aioopenssl : raise BadImplementationError ( "This connection does not use aioopenssl" ) import aioopenssl import OpenSSL await self . ehlo_or_helo_if_needed ( ) if "starttls" not in self . esmtp_extensions : raise SMTPCommandNotSupportedError ( "STARTTLS" ) code , message = await self . do_cmd ( "STARTTLS" , success = ( 220 , ) ) # Don't check for code, do_cmd did it if context is None : context = OpenSSL . SSL . Context ( OpenSSL . SSL . TLSv1_2_METHOD ) await self . transport . starttls ( ssl_context = context ) # RFC 3207: # The client MUST discard any knowledge obtained from # the server, such as the list of SMTP service extensions, # which was not obtained from the TLS negotiation itself. # FIXME: wouldn't it be better to use reset_state here ? # And reset self.reader, self.writer and self.transport just after # Maybe also self.ssl_context ? self . last_ehlo_response = ( None , None ) self . last_helo_response = ( None , None ) self . supports_esmtp = False self . esmtp_extensions = { } self . auth_mechanisms = [ ] return ( code , message )
| 3,032
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L666-L721
|
[
"def",
"tree",
"(",
"path",
",",
"load_path",
"=",
"None",
")",
":",
"load_path",
"=",
"_check_load_paths",
"(",
"load_path",
")",
"aug",
"=",
"_Augeas",
"(",
"loadpath",
"=",
"load_path",
")",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"match_path",
"=",
"path",
"return",
"dict",
"(",
"[",
"i",
"for",
"i",
"in",
"_recurmatch",
"(",
"match_path",
",",
"aug",
")",
"]",
")"
] |
Performs an entire e - mail transaction .
|
async def sendmail ( self , sender , recipients , message , mail_options = None , rcpt_options = None ) : # Make sure `recipients` is a list: if isinstance ( recipients , str ) : recipients = [ recipients ] # Set some defaults values: if mail_options is None : mail_options = [ ] if rcpt_options is None : rcpt_options = [ ] # EHLO or HELO is required: await self . ehlo_or_helo_if_needed ( ) if self . supports_esmtp : if "size" in self . esmtp_extensions : mail_options . append ( "size={}" . format ( len ( message ) ) ) await self . mail ( sender , mail_options ) errors = [ ] for recipient in recipients : try : await self . rcpt ( recipient , rcpt_options ) except SMTPCommandFailedError as e : errors . append ( e ) if len ( recipients ) == len ( errors ) : # The server refused all our recipients: raise SMTPNoRecipientError ( errors ) await self . data ( message ) # If we got here then somebody got our mail: return errors
| 3,033
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L723-L810
|
[
"def",
"GetEntries",
"(",
"self",
",",
"parser_mediator",
",",
"match",
"=",
"None",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"device_cache",
"=",
"match",
".",
"get",
"(",
"'DeviceCache'",
",",
"{",
"}",
")",
"for",
"device",
",",
"value",
"in",
"iter",
"(",
"device_cache",
".",
"items",
"(",
")",
")",
":",
"name",
"=",
"value",
".",
"get",
"(",
"'Name'",
",",
"''",
")",
"if",
"name",
":",
"name",
"=",
"''",
".",
"join",
"(",
"(",
"'Name:'",
",",
"name",
")",
")",
"event_data",
"=",
"plist_event",
".",
"PlistTimeEventData",
"(",
")",
"event_data",
".",
"root",
"=",
"'/DeviceCache'",
"datetime_value",
"=",
"value",
".",
"get",
"(",
"'LastInquiryUpdate'",
",",
"None",
")",
"if",
"datetime_value",
":",
"event_data",
".",
"desc",
"=",
"' '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"(",
"'Bluetooth Discovery'",
",",
"name",
")",
")",
")",
"event_data",
".",
"key",
"=",
"'{0:s}/LastInquiryUpdate'",
".",
"format",
"(",
"device",
")",
"event",
"=",
"time_events",
".",
"PythonDatetimeEvent",
"(",
"datetime_value",
",",
"definitions",
".",
"TIME_DESCRIPTION_WRITTEN",
")",
"parser_mediator",
".",
"ProduceEventWithEventData",
"(",
"event",
",",
"event_data",
")",
"if",
"device",
"in",
"match",
".",
"get",
"(",
"'PairedDevices'",
",",
"[",
"]",
")",
":",
"event_data",
".",
"desc",
"=",
"'Paired:True {0:s}'",
".",
"format",
"(",
"name",
")",
"event_data",
".",
"key",
"=",
"device",
"event",
"=",
"time_events",
".",
"PythonDatetimeEvent",
"(",
"datetime_value",
",",
"definitions",
".",
"TIME_DESCRIPTION_WRITTEN",
")",
"parser_mediator",
".",
"ProduceEventWithEventData",
"(",
"event",
",",
"event_data",
")",
"datetime_value",
"=",
"value",
".",
"get",
"(",
"'LastNameUpdate'",
",",
"None",
")",
"if",
"datetime_value",
":",
"event_data",
".",
"desc",
"=",
"' '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"(",
"'Device Name Set'",
",",
"name",
")",
")",
")",
"event_data",
".",
"key",
"=",
"'{0:s}/LastNameUpdate'",
".",
"format",
"(",
"device",
")",
"event",
"=",
"time_events",
".",
"PythonDatetimeEvent",
"(",
"datetime_value",
",",
"definitions",
".",
"TIME_DESCRIPTION_WRITTEN",
")",
"parser_mediator",
".",
"ProduceEventWithEventData",
"(",
"event",
",",
"event_data",
")",
"datetime_value",
"=",
"value",
".",
"get",
"(",
"'LastServicesUpdate'",
",",
"None",
")",
"if",
"datetime_value",
":",
"event_data",
".",
"desc",
"=",
"' '",
".",
"join",
"(",
"filter",
"(",
"None",
",",
"(",
"'Services Updated'",
",",
"name",
")",
")",
")",
"event_data",
".",
"key",
"=",
"'{0:s}/LastServicesUpdate'",
".",
"format",
"(",
"device",
")",
"event",
"=",
"time_events",
".",
"PythonDatetimeEvent",
"(",
"datetime_value",
",",
"definitions",
".",
"TIME_DESCRIPTION_WRITTEN",
")",
"parser_mediator",
".",
"ProduceEventWithEventData",
"(",
"event",
",",
"event_data",
")"
] |
Performs an authentication attemps using the CRAM - MD5 mechanism .
|
async def _auth_cram_md5 ( self , username , password ) : mechanism = "CRAM-MD5" code , message = await self . do_cmd ( "AUTH" , mechanism , success = ( 334 , ) ) decoded_challenge = base64 . b64decode ( message ) challenge_hash = hmac . new ( key = password . encode ( "utf-8" ) , msg = decoded_challenge , digestmod = "md5" ) hex_hash = challenge_hash . hexdigest ( ) response = "{} {}" . format ( username , hex_hash ) encoded_response = SMTP . b64enc ( response ) try : code , message = await self . do_cmd ( encoded_response , success = ( 235 , 503 ) ) except SMTPCommandFailedError as e : raise SMTPAuthenticationError ( e . code , e . message , mechanism ) return code , message
| 3,034
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L861-L913
|
[
"def",
"_normalize_numpy_indices",
"(",
"i",
")",
":",
"if",
"isinstance",
"(",
"i",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"i",
".",
"dtype",
"==",
"bool",
":",
"i",
"=",
"tuple",
"(",
"j",
".",
"tolist",
"(",
")",
"for",
"j",
"in",
"i",
".",
"nonzero",
"(",
")",
")",
"elif",
"i",
".",
"dtype",
"==",
"int",
":",
"i",
"=",
"i",
".",
"tolist",
"(",
")",
"return",
"i"
] |
Performs an authentication attempt using the LOGIN mechanism .
|
async def _auth_login ( self , username , password ) : mechanism = "LOGIN" code , message = await self . do_cmd ( "AUTH" , mechanism , SMTP . b64enc ( username ) , success = ( 334 , ) ) try : code , message = await self . do_cmd ( SMTP . b64enc ( password ) , success = ( 235 , 503 ) ) except SMTPCommandFailedError as e : raise SMTPAuthenticationError ( e . code , e . message , mechanism ) return code , message
| 3,035
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L915-L954
|
[
"def",
"readDir",
"(",
"dirPath",
",",
"numLabels",
",",
"modify",
"=",
"False",
")",
":",
"samplesDict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"_",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dirPath",
")",
":",
"for",
"f",
"in",
"files",
":",
"basename",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"if",
"\".\"",
"in",
"basename",
"and",
"extension",
"==",
"\".csv\"",
":",
"category",
"=",
"basename",
".",
"split",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"if",
"modify",
":",
"category",
"=",
"category",
".",
"replace",
"(",
"\"0\"",
",",
"\"/\"",
")",
"category",
"=",
"category",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")",
"samplesDict",
"[",
"category",
"]",
"=",
"readCSV",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirPath",
",",
"f",
")",
",",
"numLabels",
"=",
"numLabels",
")",
"return",
"samplesDict"
] |
Performs an authentication attempt using the PLAIN mechanism .
|
async def _auth_plain ( self , username , password ) : mechanism = "PLAIN" credentials = "\0{}\0{}" . format ( username , password ) encoded_credentials = SMTP . b64enc ( credentials ) try : code , message = await self . do_cmd ( "AUTH" , mechanism , encoded_credentials , success = ( 235 , 503 ) ) except SMTPCommandFailedError as e : raise SMTPAuthenticationError ( e . code , e . message , mechanism ) return code , message
| 3,036
|
https://github.com/hwmrocker/smtplibaio/blob/84ce8e45b7e706476739d0efcb416c18ecabbbb6/smtplibaio/smtp.py#L956-L995
|
[
"def",
"batchseeds",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"pdf",
"import",
"cat",
"xargs",
"=",
"args",
"[",
"1",
":",
"]",
"p",
"=",
"OptionParser",
"(",
"batchseeds",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"add_seeds_options",
"(",
"p",
",",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
"p",
".",
"print_help",
"(",
")",
")",
"folder",
",",
"=",
"args",
"folder",
"=",
"folder",
".",
"rstrip",
"(",
"'/'",
")",
"outdir",
"=",
"folder",
"+",
"\"-debug\"",
"outfile",
"=",
"folder",
"+",
"\"-output.tsv\"",
"assert",
"op",
".",
"isdir",
"(",
"folder",
")",
"images",
"=",
"[",
"]",
"jsonfile",
"=",
"opts",
".",
"calibrate",
"or",
"op",
".",
"join",
"(",
"folder",
",",
"\"calibrate.json\"",
")",
"if",
"not",
"op",
".",
"exists",
"(",
"jsonfile",
")",
":",
"jsonfile",
"=",
"None",
"for",
"im",
"in",
"iglob",
"(",
"folder",
",",
"\"*.jpg,*.JPG,*.png\"",
")",
":",
"if",
"im",
".",
"endswith",
"(",
"(",
"\".resize.jpg\"",
",",
"\".main.jpg\"",
",",
"\".label.jpg\"",
")",
")",
":",
"continue",
"if",
"op",
".",
"basename",
"(",
"im",
")",
".",
"startswith",
"(",
"\"calibrate\"",
")",
":",
"continue",
"images",
".",
"append",
"(",
"im",
")",
"fw",
"=",
"must_open",
"(",
"outfile",
",",
"'w'",
")",
"print",
"(",
"Seed",
".",
"header",
"(",
"calibrate",
"=",
"jsonfile",
")",
",",
"file",
"=",
"fw",
")",
"nseeds",
"=",
"0",
"for",
"im",
"in",
"images",
":",
"imargs",
"=",
"[",
"im",
",",
"\"--noheader\"",
",",
"\"--outdir={0}\"",
".",
"format",
"(",
"outdir",
")",
"]",
"+",
"xargs",
"if",
"jsonfile",
":",
"imargs",
"+=",
"[",
"\"--calibrate={0}\"",
".",
"format",
"(",
"jsonfile",
")",
"]",
"objects",
"=",
"seeds",
"(",
"imargs",
")",
"for",
"o",
"in",
"objects",
":",
"print",
"(",
"o",
",",
"file",
"=",
"fw",
")",
"nseeds",
"+=",
"len",
"(",
"objects",
")",
"fw",
".",
"close",
"(",
")",
"logging",
".",
"debug",
"(",
"\"Processed {0} images.\"",
".",
"format",
"(",
"len",
"(",
"images",
")",
")",
")",
"logging",
".",
"debug",
"(",
"\"A total of {0} objects written to `{1}`.\"",
".",
"format",
"(",
"nseeds",
",",
"outfile",
")",
")",
"pdfs",
"=",
"iglob",
"(",
"outdir",
",",
"\"*.pdf\"",
")",
"outpdf",
"=",
"folder",
"+",
"\"-output.pdf\"",
"cat",
"(",
"pdfs",
"+",
"[",
"\"--outfile={0}\"",
".",
"format",
"(",
"outpdf",
")",
"]",
")",
"logging",
".",
"debug",
"(",
"\"Debugging information written to `{0}`.\"",
".",
"format",
"(",
"outpdf",
")",
")",
"return",
"outfile"
] |
Get format according to algorithm defined in RFC 5646 section 2 . 1 . 1 .
|
def format ( self ) : tag = self . data [ 'tag' ] subtags = tag . split ( '-' ) if len ( subtags ) == 1 : return subtags [ 0 ] formatted_tag = subtags [ 0 ] private_tag = False for i , subtag in enumerate ( subtags [ 1 : ] ) : if len ( subtags [ i ] ) == 1 or private_tag : formatted_tag += '-' + subtag private_tag = True elif len ( subtag ) == 2 : formatted_tag += '-' + subtag . upper ( ) elif len ( subtag ) == 4 : formatted_tag += '-' + subtag . capitalize ( ) else : formatted_tag += '-' + subtag return formatted_tag
| 3,037
|
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Tag.py#L118-L146
|
[
"def",
"axis_updated",
"(",
"self",
",",
"event",
":",
"InputEvent",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"not",
"None",
":",
"axis",
"=",
"self",
".",
"axes_by_code",
".",
"get",
"(",
"prefix",
"+",
"str",
"(",
"event",
".",
"code",
")",
")",
"else",
":",
"axis",
"=",
"self",
".",
"axes_by_code",
".",
"get",
"(",
"event",
".",
"code",
")",
"if",
"axis",
"is",
"not",
"None",
":",
"axis",
".",
"receive_device_value",
"(",
"event",
".",
"value",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Unknown axis code {} ({}), value {}'",
".",
"format",
"(",
"event",
".",
"code",
",",
"prefix",
",",
"event",
".",
"value",
")",
")"
] |
Object Enumeration .
|
def ObjectEnum ( ctx ) : return Enum ( ctx , villager_male = 83 , villager_female = 293 , scout_cavalry = 448 , eagle_warrior = 751 , king = 434 , flare = 332 , relic = 285 , turkey = 833 , sheep = 594 , deer = 65 , boar = 48 , iron_boar = 810 , ostrich = 1026 , javelina = 822 , crocodile = 1031 , rhinoceros = 1139 , wolf = 126 , jaguar = 812 , hawk = 96 , macaw = 816 , shore_fish = 69 , fish_1 = 455 , fish_2 = 456 , fish_4 = 458 , fish_3 = 457 , marlin_1 = 450 , marlin_2 = 451 , dolphin = 452 , cactus = 709 , berry_bush = 59 , stone_pile = 102 , gold_pile = 66 , forest_tree = 350 , forest_tree_2 = 411 , snow_pine_tree = 413 , straggler_tree = 349 , tc_1 = 109 , tc_2 = 618 , tc_3 = 619 , tc_4 = 620 , castle = 70 , palisade_wall = 72 , stone_wall = 117 , stone_gate_1 = 64 , stone_gate_2 = 81 , stone_gate_3 = 88 , stone_gate_4 = 95 , palisade_gate_1 = 662 , palisade_gate_2 = 666 , palisade_gate_3 = 670 , palisade_gate_4 = 674 , fortified_wall = 155 , cliff_1 = 264 , cliff_2 = 265 , cliff_3 = 266 , cliff_4 = 267 , cliff_5 = 268 , cliff_6 = 269 , cliff_7 = 270 , cliff_8 = 271 , cliff_9 = 272 , cliff_10 = 273 , outpost = 598 , shipwreck = 722 , map_revealer = 837 , default = Pass )
| 3,038
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L8-L81
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Game Type Enumeration .
|
def GameTypeEnum ( ctx ) : return Enum ( ctx , RM = 0 , Regicide = 1 , DM = 2 , Scenario = 3 , Campaign = 4 , KingOfTheHill = 5 , WonderRace = 6 , DefendTheWonder = 7 , TurboRandom = 8 )
| 3,039
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L92-L105
|
[
"def",
"_lsm_load_pages",
"(",
"self",
")",
":",
"# cache all pages to preserve corrected values",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"cache",
"=",
"True",
"pages",
".",
"useframes",
"=",
"True",
"# use first and second page as keyframes",
"pages",
".",
"keyframe",
"=",
"1",
"pages",
".",
"keyframe",
"=",
"0",
"# load remaining pages as frames",
"pages",
".",
"_load",
"(",
"keyframe",
"=",
"None",
")",
"# fix offsets and bytecounts first",
"self",
".",
"_lsm_fix_strip_offsets",
"(",
")",
"self",
".",
"_lsm_fix_strip_bytecounts",
"(",
")",
"# assign keyframes for data and thumbnail series",
"keyframe",
"=",
"pages",
"[",
"0",
"]",
"for",
"page",
"in",
"pages",
"[",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe",
"keyframe",
"=",
"pages",
"[",
"1",
"]",
"for",
"page",
"in",
"pages",
"[",
"1",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe"
] |
Object Type Enumeration .
|
def ObjectTypeEnum ( ctx ) : return Enum ( ctx , static = 10 , animated = 20 , doppelganger = 25 , moving = 30 , action = 40 , base = 50 , missile = 60 , combat = 70 , building = 80 , tree = 90 , default = Pass )
| 3,040
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L107-L122
|
[
"def",
"_lsm_load_pages",
"(",
"self",
")",
":",
"# cache all pages to preserve corrected values",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"cache",
"=",
"True",
"pages",
".",
"useframes",
"=",
"True",
"# use first and second page as keyframes",
"pages",
".",
"keyframe",
"=",
"1",
"pages",
".",
"keyframe",
"=",
"0",
"# load remaining pages as frames",
"pages",
".",
"_load",
"(",
"keyframe",
"=",
"None",
")",
"# fix offsets and bytecounts first",
"self",
".",
"_lsm_fix_strip_offsets",
"(",
")",
"self",
".",
"_lsm_fix_strip_bytecounts",
"(",
")",
"# assign keyframes for data and thumbnail series",
"keyframe",
"=",
"pages",
"[",
"0",
"]",
"for",
"page",
"in",
"pages",
"[",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe",
"keyframe",
"=",
"pages",
"[",
"1",
"]",
"for",
"page",
"in",
"pages",
"[",
"1",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe"
] |
Player Type Enumeration .
|
def PlayerTypeEnum ( ctx ) : return Enum ( ctx , absent = 0 , closed = 1 , human = 2 , eliminated = 3 , computer = 4 , cyborg = 5 , spectator = 6 )
| 3,041
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L124-L135
|
[
"def",
"_lsm_load_pages",
"(",
"self",
")",
":",
"# cache all pages to preserve corrected values",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"cache",
"=",
"True",
"pages",
".",
"useframes",
"=",
"True",
"# use first and second page as keyframes",
"pages",
".",
"keyframe",
"=",
"1",
"pages",
".",
"keyframe",
"=",
"0",
"# load remaining pages as frames",
"pages",
".",
"_load",
"(",
"keyframe",
"=",
"None",
")",
"# fix offsets and bytecounts first",
"self",
".",
"_lsm_fix_strip_offsets",
"(",
")",
"self",
".",
"_lsm_fix_strip_bytecounts",
"(",
")",
"# assign keyframes for data and thumbnail series",
"keyframe",
"=",
"pages",
"[",
"0",
"]",
"for",
"page",
"in",
"pages",
"[",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe",
"keyframe",
"=",
"pages",
"[",
"1",
"]",
"for",
"page",
"in",
"pages",
"[",
"1",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe"
] |
Resource Type Enumeration .
|
def ResourceEnum ( ctx ) : return Enum ( ctx , food = 0 , wood = 1 , stone = 2 , gold = 3 , decay = 12 , fish = 17 , default = Pass # lots of resource types exist )
| 3,042
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L167-L178
|
[
"def",
"_lsm_load_pages",
"(",
"self",
")",
":",
"# cache all pages to preserve corrected values",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"cache",
"=",
"True",
"pages",
".",
"useframes",
"=",
"True",
"# use first and second page as keyframes",
"pages",
".",
"keyframe",
"=",
"1",
"pages",
".",
"keyframe",
"=",
"0",
"# load remaining pages as frames",
"pages",
".",
"_load",
"(",
"keyframe",
"=",
"None",
")",
"# fix offsets and bytecounts first",
"self",
".",
"_lsm_fix_strip_offsets",
"(",
")",
"self",
".",
"_lsm_fix_strip_bytecounts",
"(",
")",
"# assign keyframes for data and thumbnail series",
"keyframe",
"=",
"pages",
"[",
"0",
"]",
"for",
"page",
"in",
"pages",
"[",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe",
"keyframe",
"=",
"pages",
"[",
"1",
"]",
"for",
"page",
"in",
"pages",
"[",
"1",
":",
":",
"2",
"]",
":",
"page",
".",
"keyframe",
"=",
"keyframe"
] |
Victory Type Enumeration .
|
def VictoryEnum ( ctx ) : return Enum ( ctx , standard = 0 , conquest = 1 , exploration = 2 , ruins = 3 , artifacts = 4 , discoveries = 5 , gold = 6 , time_limit = 7 , score = 8 , standard2 = 9 , regicide = 10 , last_man = 11 )
| 3,043
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L180-L196
|
[
"def",
"_consumers",
"(",
"self",
")",
":",
"consumers",
"=",
"{",
"}",
"for",
"env",
"in",
"os",
".",
"environ",
":",
"if",
"env",
".",
"startswith",
"(",
"'CONSUMER_KEY_SECRET_'",
")",
":",
"key",
"=",
"env",
"[",
"20",
":",
"]",
"# Strip off the CONSUMER_KEY_SECRET_ prefix",
"# TODO: remove below after live test",
"# consumers[key] = {\"secret\": os.environ[env], \"cert\": 'NA'}",
"consumers",
"[",
"key",
"]",
"=",
"{",
"\"secret\"",
":",
"os",
".",
"environ",
"[",
"env",
"]",
",",
"\"cert\"",
":",
"None",
"}",
"if",
"not",
"consumers",
":",
"raise",
"LTIException",
"(",
"\"No consumers found. Chalice stores \"",
"\"consumers in Lambda environment variables. \"",
"\"Have you created the environment variables?\"",
")",
"return",
"consumers"
] |
Starting Age Enumeration .
|
def StartingAgeEnum ( ctx ) : return Enum ( ctx , what = - 2 , unset = - 1 , dark = 0 , feudal = 1 , castle = 2 , imperial = 3 , postimperial = 4 , dmpostimperial = 6 )
| 3,044
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L219-L231
|
[
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"logging",
".",
"debug",
"(",
"'Saving epoch %d data to \"%s\"'",
",",
"epoch_id",
",",
"self",
".",
"_file_path",
")",
"if",
"not",
"self",
".",
"_header_written",
":",
"self",
".",
"_write_header",
"(",
"epoch_data",
"=",
"epoch_data",
")",
"self",
".",
"_write_row",
"(",
"epoch_id",
"=",
"epoch_id",
",",
"epoch_data",
"=",
"epoch_data",
")"
] |
Game Action Modes .
|
def GameActionModeEnum ( ctx ) : return Enum ( ctx , diplomacy = 0 , speed = 1 , instant_build = 2 , quick_build = 4 , allied_victory = 5 , cheat = 6 , unk0 = 9 , spy = 10 , unk1 = 11 , farm_queue = 13 , farm_unqueue = 14 , default = Pass )
| 3,045
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L250-L266
|
[
"def",
"vn_release",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_reserve function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"vn_id",
"=",
"kwargs",
".",
"get",
"(",
"'vn_id'",
",",
"None",
")",
"vn_name",
"=",
"kwargs",
".",
"get",
"(",
"'vn_name'",
",",
"None",
")",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'path'",
",",
"None",
")",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'data'",
",",
"None",
")",
"if",
"vn_id",
":",
"if",
"vn_name",
":",
"log",
".",
"warning",
"(",
"'Both the \\'vn_id\\' and \\'vn_name\\' arguments were provided. '",
"'\\'vn_id\\' will take precedence.'",
")",
"elif",
"vn_name",
":",
"vn_id",
"=",
"get_vn_id",
"(",
"kwargs",
"=",
"{",
"'name'",
":",
"vn_name",
"}",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_release function requires a \\'vn_id\\' or a \\'vn_name\\' to '",
"'be provided.'",
")",
"if",
"data",
":",
"if",
"path",
":",
"log",
".",
"warning",
"(",
"'Both the \\'data\\' and \\'path\\' arguments were provided. '",
"'\\'data\\' will take precedence.'",
")",
"elif",
"path",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"mode",
"=",
"'r'",
")",
"as",
"rfh",
":",
"data",
"=",
"rfh",
".",
"read",
"(",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_release function requires either \\'data\\' or a \\'path\\' to '",
"'be provided.'",
")",
"server",
",",
"user",
",",
"password",
"=",
"_get_xml_rpc",
"(",
")",
"auth",
"=",
"':'",
".",
"join",
"(",
"[",
"user",
",",
"password",
"]",
")",
"response",
"=",
"server",
".",
"one",
".",
"vn",
".",
"release",
"(",
"auth",
",",
"int",
"(",
"vn_id",
")",
",",
"data",
")",
"ret",
"=",
"{",
"'action'",
":",
"'vn.release'",
",",
"'released'",
":",
"response",
"[",
"0",
"]",
",",
"'resource_id'",
":",
"response",
"[",
"1",
"]",
",",
"'error_code'",
":",
"response",
"[",
"2",
"]",
",",
"}",
"return",
"ret"
] |
Types of Releases .
|
def ReleaseTypeEnum ( ctx ) : return Enum ( ctx , all = 0 , selected = 3 , sametype = 4 , notselected = 5 , inversetype = 6 , default = Pass )
| 3,046
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L278-L288
|
[
"def",
"_check_timeindex",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"timeseries",
".",
"generation_fluctuating",
"self",
".",
"timeseries",
".",
"generation_dispatchable",
"self",
".",
"timeseries",
".",
"load",
"self",
".",
"timeseries",
".",
"generation_reactive_power",
"self",
".",
"timeseries",
".",
"load_reactive_power",
"except",
":",
"message",
"=",
"'Time index of feed-in and load time series does '",
"'not match.'",
"logging",
".",
"error",
"(",
"message",
")",
"raise",
"KeyError",
"(",
"message",
")"
] |
Player s Diplomacy Enumeration .
|
def MyDiplomacyEnum ( ctx ) : return Enum ( ctx , gaia = 0 , self = 1 , ally = 2 , neutral = 3 , enemy = 4 , invalid_player = - 1 )
| 3,047
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L310-L320
|
[
"def",
"apply_crop_list",
"(",
"crop_list",
",",
"input_doc",
",",
"page_nums_to_crop",
",",
"already_cropped_by_this_program",
")",
":",
"if",
"args",
".",
"restore",
"and",
"not",
"already_cropped_by_this_program",
":",
"print",
"(",
"\"\\nWarning from pdfCropMargins: The Producer string indicates that\"",
"\"\\neither this document was not previously cropped by pdfCropMargins\"",
"\"\\nor else it was modified by another program after that. Trying the\"",
"\"\\nundo anyway...\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"args",
".",
"restore",
"and",
"args",
".",
"verbose",
":",
"print",
"(",
"\"\\nRestoring the document to margins saved for each page in the ArtBox.\"",
")",
"if",
"args",
".",
"verbose",
"and",
"not",
"args",
".",
"restore",
":",
"print",
"(",
"\"\\nNew full page sizes after cropping, in PDF format (lbrt):\"",
")",
"# Copy over each page, after modifying the appropriate PDF boxes.",
"for",
"page_num",
"in",
"range",
"(",
"input_doc",
".",
"getNumPages",
"(",
")",
")",
":",
"curr_page",
"=",
"input_doc",
".",
"getPage",
"(",
"page_num",
")",
"# Restore any rotation which was originally on the page.",
"curr_page",
".",
"rotateClockwise",
"(",
"curr_page",
".",
"rotationAngle",
")",
"# Only do the restore from ArtBox if '--restore' option was selected.",
"if",
"args",
".",
"restore",
":",
"if",
"not",
"curr_page",
".",
"artBox",
":",
"print",
"(",
"\"\\nWarning from pdfCropMargins: Attempting to restore pages from\"",
"\"\\nthe ArtBox in each page, but page\"",
",",
"page_num",
",",
"\"has no readable\"",
"\"\\nArtBox. Leaving that page unchanged.\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"continue",
"curr_page",
".",
"mediaBox",
"=",
"curr_page",
".",
"artBox",
"curr_page",
".",
"cropBox",
"=",
"curr_page",
".",
"artBox",
"continue",
"# Do the save to ArtBox if that option is chosen and Producer is set.",
"if",
"not",
"args",
".",
"noundosave",
"and",
"not",
"already_cropped_by_this_program",
":",
"curr_page",
".",
"artBox",
"=",
"intersect_boxes",
"(",
"curr_page",
".",
"mediaBox",
",",
"curr_page",
".",
"cropBox",
")",
"# Reset the CropBox and MediaBox to their saved original values",
"# (which were set in getFullPageBox, in the curr_page object's namespace).",
"curr_page",
".",
"mediaBox",
"=",
"curr_page",
".",
"originalMediaBox",
"curr_page",
".",
"cropBox",
"=",
"curr_page",
".",
"originalCropBox",
"# Copy the original page without further mods if it wasn't in the range",
"# selected for cropping.",
"if",
"page_num",
"not",
"in",
"page_nums_to_crop",
":",
"continue",
"# Convert the computed \"box to crop to\" into a RectangleObject (for pyPdf).",
"new_cropped_box",
"=",
"RectangleObject",
"(",
"crop_list",
"[",
"page_num",
"]",
")",
"if",
"args",
".",
"verbose",
":",
"print",
"(",
"\"\\t\"",
"+",
"str",
"(",
"page_num",
"+",
"1",
")",
"+",
"\"\\t\"",
",",
"new_cropped_box",
")",
"# page numbering from 1",
"if",
"not",
"args",
".",
"boxesToSet",
":",
"args",
".",
"boxesToSet",
"=",
"[",
"\"m\"",
",",
"\"c\"",
"]",
"# Now set any boxes which were selected to be set via the --boxesToSet option.",
"if",
"\"m\"",
"in",
"args",
".",
"boxesToSet",
":",
"curr_page",
".",
"mediaBox",
"=",
"new_cropped_box",
"if",
"\"c\"",
"in",
"args",
".",
"boxesToSet",
":",
"curr_page",
".",
"cropBox",
"=",
"new_cropped_box",
"if",
"\"t\"",
"in",
"args",
".",
"boxesToSet",
":",
"curr_page",
".",
"trimBox",
"=",
"new_cropped_box",
"if",
"\"a\"",
"in",
"args",
".",
"boxesToSet",
":",
"curr_page",
".",
"artBox",
"=",
"new_cropped_box",
"if",
"\"b\"",
"in",
"args",
".",
"boxesToSet",
":",
"curr_page",
".",
"bleedBox",
"=",
"new_cropped_box",
"return"
] |
Action Enumeration .
|
def ActionEnum ( ctx ) : return Enum ( ctx , interact = 0 , stop = 1 , ai_interact = 2 , move = 3 , add_attribute = 5 , give_attribute = 6 , ai_move = 10 , resign = 11 , spec = 15 , waypoint = 16 , stance = 18 , guard = 19 , follow = 20 , patrol = 21 , formation = 23 , save = 27 , ai_waypoint = 31 , chapter = 32 , ai_command = 53 , ai_queue = 100 , research = 101 , build = 102 , game = 103 , wall = 105 , delete = 106 , attackground = 107 , tribute = 108 , repair = 110 , release = 111 , multiqueue = 112 , togglegate = 114 , flare = 115 , order = 117 , queue = 119 , gatherpoint = 120 , sell = 122 , buy = 123 , droprelic = 126 , townbell = 127 , backtowork = 128 , postgame = 255 , default = Pass )
| 3,048
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L322-L368
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
generate a new kernel
|
def newKernel ( self , nb ) : manager , kernel = utils . start_new_kernel ( kernel_name = nb . metadata . kernelspec . name ) return kernel
| 3,049
|
https://github.com/bollwyvl/nosebook/blob/6a79104b9be4b5acf1ff06cbf745f220a54a4613/nosebook.py#L65-L72
|
[
"def",
"GetAttachmentIdFromMediaId",
"(",
"media_id",
")",
":",
"altchars",
"=",
"'+-'",
"if",
"not",
"six",
".",
"PY2",
":",
"altchars",
"=",
"altchars",
".",
"encode",
"(",
"'utf-8'",
")",
"# altchars for '+' and '/'. We keep '+' but replace '/' with '-'",
"buffer",
"=",
"base64",
".",
"b64decode",
"(",
"str",
"(",
"media_id",
")",
",",
"altchars",
")",
"resoure_id_length",
"=",
"20",
"attachment_id",
"=",
"''",
"if",
"len",
"(",
"buffer",
")",
">",
"resoure_id_length",
":",
"# We are cutting off the storage index.",
"attachment_id",
"=",
"base64",
".",
"b64encode",
"(",
"buffer",
"[",
"0",
":",
"resoure_id_length",
"]",
",",
"altchars",
")",
"if",
"not",
"six",
".",
"PY2",
":",
"attachment_id",
"=",
"attachment_id",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"attachment_id",
"=",
"media_id",
"return",
"attachment_id"
] |
apply configured options
|
def configure ( self , options , conf ) : super ( Nosebook , self ) . configure ( options , conf ) self . testMatch = re . compile ( options . nosebookTestMatch ) . match self . testMatchCell = re . compile ( options . nosebookTestMatchCell ) . match scrubs = [ ] if options . nosebookScrub : try : scrubs = json . loads ( options . nosebookScrub ) except Exception : scrubs = [ options . nosebookScrub ] if isstr ( scrubs ) : scrubs = { scrubs : "<...>" } elif not isinstance ( scrubs , dict ) : scrubs = dict ( [ ( scrub , "<...%s>" % i ) for i , scrub in enumerate ( scrubs ) ] ) self . scrubMatch = { re . compile ( scrub ) : sub for scrub , sub in scrubs . items ( ) }
| 3,050
|
https://github.com/bollwyvl/nosebook/blob/6a79104b9be4b5acf1ff06cbf745f220a54a4613/nosebook.py#L136-L165
|
[
"def",
"_openResources",
"(",
"self",
")",
":",
"try",
":",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"ex",
")",
"logger",
".",
"warning",
"(",
"\"Unable to read wav with memmory mapping. Trying without now.\"",
")",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"False",
")",
"self",
".",
"_array",
"=",
"data",
"self",
".",
"attributes",
"[",
"'rate'",
"]",
"=",
"rate"
] |
filter files to those that match nosebook - match
|
def wantFile ( self , filename ) : log . info ( "considering %s" , filename ) if self . testMatch ( filename ) is None : return False nb = self . readnb ( filename ) for cell in self . codeCells ( nb ) : return True log . info ( "no `code` cells in %s" , filename ) return False
| 3,051
|
https://github.com/bollwyvl/nosebook/blob/6a79104b9be4b5acf1ff06cbf745f220a54a4613/nosebook.py#L193-L210
|
[
"def",
"download_with_progress",
"(",
"url",
",",
"chunk_size",
",",
"*",
"*",
"progress_kwargs",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"total_size",
"=",
"int",
"(",
"resp",
".",
"headers",
"[",
"'content-length'",
"]",
")",
"data",
"=",
"BytesIO",
"(",
")",
"with",
"progressbar",
"(",
"length",
"=",
"total_size",
",",
"*",
"*",
"progress_kwargs",
")",
"as",
"pbar",
":",
"for",
"chunk",
"in",
"resp",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
":",
"data",
".",
"write",
"(",
"chunk",
")",
"pbar",
".",
"update",
"(",
"len",
"(",
"chunk",
")",
")",
"data",
".",
"seek",
"(",
"0",
")",
"return",
"data"
] |
Create a SlipSocket connection .
|
def create_connection ( cls , address , timeout = None , source_address = None ) : sock = socket . create_connection ( address , timeout , source_address ) return cls ( sock )
| 3,052
|
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipsocket.py#L94-L110
|
[
"def",
"store",
"(",
"self",
",",
"extractions",
":",
"List",
"[",
"Extraction",
"]",
",",
"attribute",
":",
"str",
",",
"group_by_tags",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_value",
",",
"dict",
")",
":",
"raise",
"StoreExtractionError",
"(",
"\"segment is type: \"",
"+",
"str",
"(",
"type",
"(",
"self",
".",
"_value",
")",
")",
")",
"if",
"not",
"len",
"(",
"extractions",
")",
":",
"return",
"if",
"group_by_tags",
":",
"try",
":",
"next",
"(",
"x",
"for",
"x",
"in",
"extractions",
"if",
"x",
".",
"tag",
")",
"# if there is at least one extraction with a tag",
"if",
"attribute",
"not",
"in",
"self",
".",
"_extractions",
":",
"self",
".",
"_extractions",
"[",
"attribute",
"]",
"=",
"set",
"(",
"[",
"]",
")",
"self",
".",
"_value",
"[",
"attribute",
"]",
"=",
"{",
"}",
"extraction_provenances",
"=",
"{",
"}",
"for",
"e",
"in",
"extractions",
":",
"tag",
"=",
"e",
".",
"tag",
"if",
"e",
".",
"tag",
"else",
"'NO_TAGS'",
"if",
"tag",
"not",
"in",
"self",
".",
"value",
"[",
"attribute",
"]",
":",
"self",
".",
"value",
"[",
"attribute",
"]",
"[",
"tag",
"]",
"=",
"[",
"e",
".",
"value",
"]",
"else",
":",
"if",
"e",
".",
"value",
"not",
"in",
"self",
".",
"value",
"[",
"attribute",
"]",
"[",
"tag",
"]",
":",
"self",
".",
"value",
"[",
"attribute",
"]",
"[",
"tag",
"]",
".",
"append",
"(",
"e",
".",
"value",
")",
"# TODO: handle provenance of non literals",
"if",
"isinstance",
"(",
"e",
".",
"value",
",",
"Number",
")",
"or",
"isinstance",
"(",
"e",
".",
"value",
",",
"str",
")",
":",
"extraction_provenances",
"[",
"e",
".",
"value",
"]",
"=",
"e",
".",
"prov_id",
"self",
".",
"_extractions",
"[",
"attribute",
"]",
"=",
"self",
".",
"_extractions",
"[",
"attribute",
"]",
".",
"union",
"(",
"extractions",
")",
"new_id",
"=",
"self",
".",
"_document",
".",
"provenance_id_index",
"# for the purpose of provenance hierarrchy tracking",
"storage_provenance_record",
":",
"StorageProvenanceRecord",
"=",
"StorageProvenanceRecord",
"(",
"new_id",
",",
"self",
".",
"json_path",
",",
"attribute",
",",
"extraction_provenances",
",",
"self",
".",
"document",
")",
"self",
".",
"_document",
".",
"provenance_id_index_incrementer",
"(",
")",
"self",
".",
"_document",
".",
"provenances",
"[",
"new_id",
"]",
"=",
"storage_provenance_record",
"self",
".",
"create_storage_provenance",
"(",
"storage_provenance_record",
")",
"return",
"except",
"StopIteration",
":",
"pass",
"if",
"attribute",
"not",
"in",
"self",
".",
"_extractions",
":",
"self",
".",
"_extractions",
"[",
"attribute",
"]",
"=",
"set",
"(",
"[",
"]",
")",
"self",
".",
"_value",
"[",
"attribute",
"]",
"=",
"list",
"(",
")",
"self",
".",
"_extractions",
"[",
"attribute",
"]",
"=",
"self",
".",
"_extractions",
"[",
"attribute",
"]",
".",
"union",
"(",
"extractions",
")",
"extraction_provenances",
"=",
"dict",
"(",
")",
"for",
"a_extraction",
"in",
"extractions",
":",
"# TODO: handle provenance of non literals",
"if",
"isinstance",
"(",
"a_extraction",
".",
"value",
",",
"Number",
")",
"or",
"isinstance",
"(",
"a_extraction",
".",
"value",
",",
"str",
")",
":",
"extraction_provenances",
"[",
"a_extraction",
".",
"value",
"]",
"=",
"a_extraction",
".",
"prov_id",
"if",
"a_extraction",
".",
"value",
"not",
"in",
"self",
".",
"_value",
"[",
"attribute",
"]",
":",
"self",
".",
"_value",
"[",
"attribute",
"]",
".",
"append",
"(",
"a_extraction",
".",
"value",
")",
"new_id",
"=",
"self",
".",
"_document",
".",
"provenance_id_index",
"# for the purpose of provenance hierarchy tracking",
"storage_provenance_record",
":",
"StorageProvenanceRecord",
"=",
"StorageProvenanceRecord",
"(",
"new_id",
",",
"self",
".",
"json_path",
",",
"attribute",
",",
"extraction_provenances",
",",
"self",
".",
"document",
")",
"self",
".",
"_document",
".",
"provenance_id_index_incrementer",
"(",
")",
"self",
".",
"_document",
".",
"provenances",
"[",
"new_id",
"]",
"=",
"storage_provenance_record",
"self",
".",
"create_storage_provenance",
"(",
"storage_provenance_record",
")"
] |
Send a SLIP - encoded message over the stream .
|
def send_msg ( self , message ) : packet = self . driver . send ( message ) self . send_bytes ( packet )
| 3,053
|
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipwrapper.py#L65-L71
|
[
"def",
"disk_xml",
"(",
"identifier",
",",
"pool_xml",
",",
"base_volume_xml",
",",
"cow",
")",
":",
"pool",
"=",
"etree",
".",
"fromstring",
"(",
"pool_xml",
")",
"base_volume",
"=",
"etree",
".",
"fromstring",
"(",
"base_volume_xml",
")",
"pool_path",
"=",
"pool",
".",
"find",
"(",
"'.//path'",
")",
".",
"text",
"base_path",
"=",
"base_volume",
".",
"find",
"(",
"'.//target/path'",
")",
".",
"text",
"target_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pool_path",
",",
"'%s.qcow2'",
"%",
"identifier",
")",
"volume_xml",
"=",
"VOLUME_DEFAULT_CONFIG",
".",
"format",
"(",
"identifier",
",",
"target_path",
")",
"volume",
"=",
"etree",
".",
"fromstring",
"(",
"volume_xml",
")",
"base_volume_capacity",
"=",
"base_volume",
".",
"find",
"(",
"\".//capacity\"",
")",
"volume",
".",
"append",
"(",
"base_volume_capacity",
")",
"if",
"cow",
":",
"backing_xml",
"=",
"BACKING_STORE_DEFAULT_CONFIG",
".",
"format",
"(",
"base_path",
")",
"backing_store",
"=",
"etree",
".",
"fromstring",
"(",
"backing_xml",
")",
"volume",
".",
"append",
"(",
"backing_store",
")",
"return",
"etree",
".",
"tostring",
"(",
"volume",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] |
Receive a single message from the stream .
|
def recv_msg ( self ) : # First check if there are any pending messages if self . _messages : return self . _messages . popleft ( ) # No pending messages left. If a ProtocolError has occurred # it must be re-raised here: if self . _protocol_error : self . _handle_pending_protocol_error ( ) while not self . _messages and not self . _stream_closed : # As long as no messages are available, # flush the internal packet buffer, # and try to read data try : if self . _flush_needed : self . _flush_needed = False self . _messages . extend ( self . driver . flush ( ) ) else : data = self . recv_bytes ( ) if data == b'' : self . _stream_closed = True self . _messages . extend ( self . driver . receive ( data ) ) except ProtocolError as pe : self . _messages . extend ( self . driver . messages ) self . _protocol_error = pe self . _traceback = sys . exc_info ( ) [ 2 ] break if self . _messages : return self . _messages . popleft ( ) if self . _protocol_error : self . _handle_pending_protocol_error ( ) else : return b''
| 3,054
|
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slipwrapper.py#L73-L117
|
[
"def",
"set_name_with_model",
"(",
"self",
",",
"model",
")",
":",
"table_name",
"=",
"model",
".",
"_meta",
".",
"db_table",
"column_names",
"=",
"[",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
".",
"column",
"for",
"field_name",
",",
"order",
"in",
"self",
".",
"fields_orders",
"]",
"column_names_with_order",
"=",
"[",
"(",
"(",
"'-%s'",
"if",
"order",
"else",
"'%s'",
")",
"%",
"column_name",
")",
"for",
"column_name",
",",
"(",
"field_name",
",",
"order",
")",
"in",
"zip",
"(",
"column_names",
",",
"self",
".",
"fields_orders",
")",
"]",
"# The length of the parts of the name is based on the default max",
"# length of 30 characters.",
"hash_data",
"=",
"[",
"table_name",
"]",
"+",
"column_names_with_order",
"+",
"[",
"self",
".",
"suffix",
"]",
"+",
"self",
".",
"name_hash_extra_data",
"(",
")",
"self",
".",
"name",
"=",
"'%s_%s_%s'",
"%",
"(",
"table_name",
"[",
":",
"11",
"]",
",",
"column_names",
"[",
"0",
"]",
"[",
":",
"7",
"]",
",",
"'%s_%s'",
"%",
"(",
"self",
".",
"_hash_generator",
"(",
"*",
"hash_data",
")",
",",
"self",
".",
"suffix",
")",
",",
")",
"assert",
"len",
"(",
"self",
".",
"name",
")",
"<=",
"self",
".",
"max_name_length",
",",
"(",
"'Index too long for multiple database support. Is self.suffix '",
"'longer than 3 characters?'",
")",
"self",
".",
"check_name",
"(",
")"
] |
Clean up the object .
|
def finalize ( self ) : self . pause_session_logging ( ) self . _disable_logging ( ) self . _msg_callback = None self . _error_msg_callback = None self . _warning_msg_callback = None self . _info_msg_callback = None
| 3,055
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L100-L111
|
[
"def",
"pvd_factory",
"(",
"sys_ident",
",",
"vol_ident",
",",
"set_size",
",",
"seqnum",
",",
"log_block_size",
",",
"vol_set_ident",
",",
"pub_ident_str",
",",
"preparer_ident_str",
",",
"app_ident_str",
",",
"copyright_file",
",",
"abstract_file",
",",
"bibli_file",
",",
"vol_expire_date",
",",
"app_use",
",",
"xa",
")",
":",
"# type: (bytes, bytes, int, int, int, bytes, bytes, bytes, bytes, bytes, bytes, bytes, float, bytes, bool) -> PrimaryOrSupplementaryVD",
"pvd",
"=",
"PrimaryOrSupplementaryVD",
"(",
"VOLUME_DESCRIPTOR_TYPE_PRIMARY",
")",
"pvd",
".",
"new",
"(",
"0",
",",
"sys_ident",
",",
"vol_ident",
",",
"set_size",
",",
"seqnum",
",",
"log_block_size",
",",
"vol_set_ident",
",",
"pub_ident_str",
",",
"preparer_ident_str",
",",
"app_ident_str",
",",
"copyright_file",
",",
"abstract_file",
",",
"bibli_file",
",",
"vol_expire_date",
",",
"app_use",
",",
"xa",
",",
"1",
",",
"b''",
")",
"return",
"pvd"
] |
Get the deque of chain indices starting with last successful index .
|
def _chain_indices ( self ) : chain_indices = deque ( range ( len ( self . connection_chains ) ) ) chain_indices . rotate ( self . _last_chain_index ) return chain_indices
| 3,056
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L226-L230
|
[
"def",
"BuildChecks",
"(",
"self",
",",
"request",
")",
":",
"result",
"=",
"[",
"]",
"if",
"request",
".",
"HasField",
"(",
"\"start_time\"",
")",
"or",
"request",
".",
"HasField",
"(",
"\"end_time\"",
")",
":",
"def",
"FilterTimestamp",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"HasField",
"(",
"\"st_mtime\"",
")",
"and",
"(",
"file_stat",
".",
"st_mtime",
"<",
"request",
".",
"start_time",
"or",
"file_stat",
".",
"st_mtime",
">",
"request",
".",
"end_time",
")",
"result",
".",
"append",
"(",
"FilterTimestamp",
")",
"if",
"request",
".",
"HasField",
"(",
"\"min_file_size\"",
")",
"or",
"request",
".",
"HasField",
"(",
"\"max_file_size\"",
")",
":",
"def",
"FilterSize",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"HasField",
"(",
"\"st_size\"",
")",
"and",
"(",
"file_stat",
".",
"st_size",
"<",
"request",
".",
"min_file_size",
"or",
"file_stat",
".",
"st_size",
">",
"request",
".",
"max_file_size",
")",
"result",
".",
"append",
"(",
"FilterSize",
")",
"if",
"request",
".",
"HasField",
"(",
"\"perm_mode\"",
")",
":",
"def",
"FilterPerms",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"(",
"file_stat",
".",
"st_mode",
"&",
"request",
".",
"perm_mask",
")",
"!=",
"request",
".",
"perm_mode",
"result",
".",
"append",
"(",
"FilterPerms",
")",
"if",
"request",
".",
"HasField",
"(",
"\"uid\"",
")",
":",
"def",
"FilterUID",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"st_uid",
"!=",
"request",
".",
"uid",
"result",
".",
"append",
"(",
"FilterUID",
")",
"if",
"request",
".",
"HasField",
"(",
"\"gid\"",
")",
":",
"def",
"FilterGID",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"st_gid",
"!=",
"request",
".",
"gid",
"result",
".",
"append",
"(",
"FilterGID",
")",
"if",
"request",
".",
"HasField",
"(",
"\"path_regex\"",
")",
":",
"regex",
"=",
"request",
".",
"path_regex",
"def",
"FilterPath",
"(",
"file_stat",
",",
"regex",
"=",
"regex",
")",
":",
"\"\"\"Suppress any filename not matching the regular expression.\"\"\"",
"return",
"not",
"regex",
".",
"Search",
"(",
"file_stat",
".",
"pathspec",
".",
"Basename",
"(",
")",
")",
"result",
".",
"append",
"(",
"FilterPath",
")",
"if",
"request",
".",
"HasField",
"(",
"\"data_regex\"",
")",
":",
"def",
"FilterData",
"(",
"file_stat",
",",
"*",
"*",
"_",
")",
":",
"\"\"\"Suppress files that do not match the content.\"\"\"",
"return",
"not",
"self",
".",
"TestFileContent",
"(",
"file_stat",
")",
"result",
".",
"append",
"(",
"FilterData",
")",
"return",
"result"
] |
Resume session logging .
|
def resume_session_logging ( self ) : self . _chain . ctrl . set_session_log ( self . session_fd ) self . log ( "Session logging resumed" )
| 3,057
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L371-L374
|
[
"def",
"download_song",
"(",
"song_url",
",",
"song_title",
")",
":",
"outtmpl",
"=",
"song_title",
"+",
"'.%(ext)s'",
"ydl_opts",
"=",
"{",
"'format'",
":",
"'bestaudio/best'",
",",
"'outtmpl'",
":",
"outtmpl",
",",
"'postprocessors'",
":",
"[",
"{",
"'key'",
":",
"'FFmpegExtractAudio'",
",",
"'preferredcodec'",
":",
"'mp3'",
",",
"'preferredquality'",
":",
"'192'",
",",
"}",
",",
"{",
"'key'",
":",
"'FFmpegMetadata'",
"}",
",",
"]",
",",
"}",
"with",
"youtube_dl",
".",
"YoutubeDL",
"(",
"ydl_opts",
")",
"as",
"ydl",
":",
"info_dict",
"=",
"ydl",
".",
"extract_info",
"(",
"song_url",
",",
"download",
"=",
"True",
")"
] |
Rollback the configuration .
|
def rollback ( self , label = None , plane = 'sdr' ) : begin = time . time ( ) rb_label = self . _chain . target_device . rollback ( label = label , plane = plane ) elapsed = time . time ( ) - begin if label : self . emit_message ( "Configuration rollback last {:.0f}s. Label: {}" . format ( elapsed , rb_label ) , log_level = logging . INFO ) else : self . emit_message ( "Configuration failed." , log_level = logging . WARNING ) return rb_label
| 3,058
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L424-L446
|
[
"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",
")"
] |
Discover the device details .
|
def discovery ( self , logfile = None , tracefile = None ) : self . _enable_logging ( logfile = logfile , tracefile = tracefile ) self . log ( "'discovery' method is deprecated. Please 'connect' with force_discovery=True." ) self . log ( "Device discovery process started" ) self . connect ( logfile = logfile , force_discovery = True , tracefile = tracefile ) self . disconnect ( )
| 3,059
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L453-L469
|
[
"def",
"get",
"(",
"self",
")",
":",
"chunk_size",
"=",
"self",
".",
"_smallest_buffer",
"(",
")",
"all_full",
"=",
"self",
".",
"_all_full",
"(",
")",
"if",
"all_full",
":",
"right_context",
"=",
"0",
"num_frames",
"=",
"chunk_size",
"-",
"self",
".",
"current_left_context",
"else",
":",
"right_context",
"=",
"self",
".",
"right_context",
"num_frames",
"=",
"self",
".",
"min_frames",
"chunk_size_needed",
"=",
"num_frames",
"+",
"self",
".",
"current_left_context",
"+",
"right_context",
"if",
"chunk_size",
">=",
"chunk_size_needed",
":",
"data",
"=",
"[",
"]",
"keep_frames",
"=",
"self",
".",
"left_context",
"+",
"self",
".",
"right_context",
"keep_from",
"=",
"max",
"(",
"0",
",",
"chunk_size",
"-",
"keep_frames",
")",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"num_buffers",
")",
":",
"data",
".",
"append",
"(",
"self",
".",
"buffers",
"[",
"index",
"]",
"[",
":",
"chunk_size",
"]",
")",
"self",
".",
"buffers",
"[",
"index",
"]",
"=",
"self",
".",
"buffers",
"[",
"index",
"]",
"[",
"keep_from",
":",
"]",
"if",
"self",
".",
"num_buffers",
"==",
"1",
":",
"data",
"=",
"data",
"[",
"0",
"]",
"chunk",
"=",
"Chunk",
"(",
"data",
",",
"self",
".",
"current_frame",
",",
"all_full",
",",
"self",
".",
"current_left_context",
",",
"right_context",
")",
"self",
".",
"current_left_context",
"=",
"min",
"(",
"self",
".",
"left_context",
",",
"chunk_size",
")",
"self",
".",
"current_frame",
"=",
"max",
"(",
"self",
".",
"current_frame",
"+",
"chunk_size",
"-",
"keep_frames",
",",
"0",
")",
"return",
"chunk"
] |
Reload the device and wait for device to boot up .
|
def reload ( self , reload_timeout = 300 , save_config = True , no_reload_cmd = False ) : begin = time . time ( ) self . _chain . target_device . clear_info ( ) result = False try : result = self . _chain . target_device . reload ( reload_timeout , save_config , no_reload_cmd ) except ConnectionStandbyConsole as exc : message = exc . message self . log ( "Active RP became standby: {}" . format ( message ) ) self . disconnect ( ) # self._conn_status.clear() result = self . reconnect ( ) # connection error caused by device booting up except ConnectionError as exc : message = exc . message self . log ( "Connection error: {}" . format ( message ) ) self . disconnect ( ) result = self . reconnect ( ) if result : elapsed = time . time ( ) - begin self . emit_message ( "Target device reload last {:.0f}s." . format ( elapsed ) , log_level = logging . INFO ) else : self . emit_message ( "Target device not reloaded." , log_level = logging . ERROR ) return result
| 3,060
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L482-L512
|
[
"def",
"is_local_url",
"(",
"target",
")",
":",
"ref_url",
"=",
"urlparse",
"(",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
")",
"test_url",
"=",
"urlparse",
"(",
"urljoin",
"(",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
",",
"target",
")",
")",
"return",
"test_url",
".",
"scheme",
"in",
"(",
"'http'",
",",
"'https'",
")",
"and",
"ref_url",
".",
"netloc",
"==",
"test_url",
".",
"netloc"
] |
Instantiate and run the Finite State Machine for the current device connection .
|
def run_fsm ( self , name , command , events , transitions , timeout , max_transitions = 20 ) : return self . _chain . target_device . run_fsm ( name , command , events , transitions , timeout , max_transitions )
| 3,061
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L514-L588
|
[
"def",
"away_wins",
"(",
"self",
")",
":",
"try",
":",
"wins",
",",
"losses",
"=",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"self",
".",
"_away_record",
")",
"return",
"wins",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"0"
] |
Call the msg callback function with the message .
|
def emit_message ( self , message , log_level ) : self . log ( message ) if log_level == logging . ERROR : if self . _error_msg_callback : self . _error_msg_callback ( message ) return if log_level == logging . WARNING : if self . _warning_msg_callback : self . _warning_msg_callback ( message ) return if log_level == logging . INFO : if self . _info_msg_callback : self . _info_msg_callback ( message ) return if self . _msg_callback : self . _msg_callback ( message )
| 3,062
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L590-L609
|
[
"def",
"check_internal_consistency",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"inconsistent_vars",
"=",
"{",
"}",
"for",
"variable",
"in",
"self",
".",
"variables",
"(",
")",
":",
"diff_agg",
"=",
"self",
".",
"check_aggregate",
"(",
"variable",
",",
"*",
"*",
"kwargs",
")",
"if",
"diff_agg",
"is",
"not",
"None",
":",
"inconsistent_vars",
"[",
"variable",
"+",
"\"-aggregate\"",
"]",
"=",
"diff_agg",
"diff_regional",
"=",
"self",
".",
"check_aggregate_region",
"(",
"variable",
",",
"*",
"*",
"kwargs",
")",
"if",
"diff_regional",
"is",
"not",
"None",
":",
"inconsistent_vars",
"[",
"variable",
"+",
"\"-regional\"",
"]",
"=",
"diff_regional",
"return",
"inconsistent_vars",
"if",
"inconsistent_vars",
"else",
"None"
] |
Set the message callback .
|
def msg_callback ( self , callback ) : if callable ( callback ) : self . _msg_callback = callback else : self . _msg_callback = None
| 3,063
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L617-L622
|
[
"def",
"configure",
"(",
"self",
",",
"organization",
",",
"base_url",
"=",
"''",
",",
"ttl",
"=",
"''",
",",
"max_ttl",
"=",
"''",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'organization'",
":",
"organization",
",",
"'base_url'",
":",
"base_url",
",",
"'ttl'",
":",
"ttl",
",",
"'max_ttl'",
":",
"max_ttl",
",",
"}",
"api_path",
"=",
"'/v1/auth/{mount_point}/config'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
")",
"return",
"self",
".",
"_adapter",
".",
"post",
"(",
"url",
"=",
"api_path",
",",
"json",
"=",
"params",
",",
")"
] |
Set the error message callback .
|
def error_msg_callback ( self , callback ) : if callable ( callback ) : self . _error_msg_callback = callback else : self . _error_msg_callback = None
| 3,064
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L630-L635
|
[
"def",
"modify",
"(",
"self",
",",
"symbol",
",",
"base_value",
")",
":",
"self",
".",
"_unit_system_id",
"=",
"None",
"if",
"symbol",
"not",
"in",
"self",
".",
"lut",
":",
"raise",
"SymbolNotFoundError",
"(",
"\"Tried to modify the symbol '%s', but it does not exist \"",
"\"in this registry.\"",
"%",
"symbol",
")",
"if",
"hasattr",
"(",
"base_value",
",",
"\"in_base\"",
")",
":",
"new_dimensions",
"=",
"base_value",
".",
"units",
".",
"dimensions",
"base_value",
"=",
"base_value",
".",
"in_base",
"(",
"\"mks\"",
")",
"base_value",
"=",
"base_value",
".",
"value",
"else",
":",
"new_dimensions",
"=",
"self",
".",
"lut",
"[",
"symbol",
"]",
"[",
"1",
"]",
"self",
".",
"lut",
"[",
"symbol",
"]",
"=",
"(",
"float",
"(",
"base_value",
")",
",",
"new_dimensions",
")",
"+",
"self",
".",
"lut",
"[",
"symbol",
"]",
"[",
"2",
":",
"]"
] |
Set the warning message callback .
|
def warning_msg_callback ( self , callback ) : if callable ( callback ) : self . _warning_msg_callback = callback else : self . _warning_msg_callback = None
| 3,065
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L643-L648
|
[
"def",
"_intersection",
"(",
"self",
",",
"keys",
",",
"rows",
")",
":",
"# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.",
"if",
"not",
"keys",
":",
"return",
"rows",
"ret",
"=",
"list",
"(",
")",
"for",
"row",
"in",
"rows",
":",
"start_date",
"=",
"row",
"[",
"self",
".",
"_key_start_date",
"]",
"end_date",
"=",
"row",
"[",
"self",
".",
"_key_end_date",
"]",
"for",
"key_start_date",
",",
"key_end_date",
"in",
"keys",
":",
"start_date",
",",
"end_date",
"=",
"Type2JoinHelper",
".",
"_intersect",
"(",
"start_date",
",",
"end_date",
",",
"row",
"[",
"key_start_date",
"]",
",",
"row",
"[",
"key_end_date",
"]",
")",
"if",
"not",
"start_date",
":",
"break",
"if",
"key_start_date",
"not",
"in",
"[",
"self",
".",
"_key_start_date",
",",
"self",
".",
"_key_end_date",
"]",
":",
"del",
"row",
"[",
"key_start_date",
"]",
"if",
"key_end_date",
"not",
"in",
"[",
"self",
".",
"_key_start_date",
",",
"self",
".",
"_key_end_date",
"]",
":",
"del",
"row",
"[",
"key_end_date",
"]",
"if",
"start_date",
":",
"row",
"[",
"self",
".",
"_key_start_date",
"]",
"=",
"start_date",
"row",
"[",
"self",
".",
"_key_end_date",
"]",
"=",
"end_date",
"ret",
".",
"append",
"(",
"row",
")",
"return",
"ret"
] |
Set the info message callback .
|
def info_msg_callback ( self , callback ) : if callable ( callback ) : self . _info_msg_callback = callback else : self . _info_msg_callback = None
| 3,066
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/connection.py#L656-L661
|
[
"def",
"convert_to_experiment_list",
"(",
"experiments",
")",
":",
"exp_list",
"=",
"experiments",
"# Transform list if necessary",
"if",
"experiments",
"is",
"None",
":",
"exp_list",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"experiments",
",",
"Experiment",
")",
":",
"exp_list",
"=",
"[",
"experiments",
"]",
"elif",
"type",
"(",
"experiments",
")",
"is",
"dict",
":",
"exp_list",
"=",
"[",
"Experiment",
".",
"from_json",
"(",
"name",
",",
"spec",
")",
"for",
"name",
",",
"spec",
"in",
"experiments",
".",
"items",
"(",
")",
"]",
"# Validate exp_list",
"if",
"(",
"type",
"(",
"exp_list",
")",
"is",
"list",
"and",
"all",
"(",
"isinstance",
"(",
"exp",
",",
"Experiment",
")",
"for",
"exp",
"in",
"exp_list",
")",
")",
":",
"if",
"len",
"(",
"exp_list",
")",
">",
"1",
":",
"logger",
".",
"warning",
"(",
"\"All experiments will be \"",
"\"using the same SearchAlgorithm.\"",
")",
"else",
":",
"raise",
"TuneError",
"(",
"\"Invalid argument: {}\"",
".",
"format",
"(",
"experiments",
")",
")",
"return",
"exp_list"
] |
Recursive function to extract all url details
|
def _get_view_details ( self , urlpatterns , parent = '' ) : for pattern in urlpatterns : if isinstance ( pattern , ( URLPattern , RegexURLPattern ) ) : try : d = describe_pattern ( pattern ) docstr = pattern . callback . __doc__ method = None expected_json_response = '' expected_url = '' if docstr : # Get expected URL u = re . findall ( r'URL: (.*)' , docstr , flags = re . DOTALL ) if u : expected_url = u [ 0 ] # Get all possible methods if 'view_class' not in dir ( pattern . callback ) : continue possible_methods = [ m for m in dir ( pattern . callback . view_class ) if m in METHODS ] for method in possible_methods : view_method_docstr = getattr ( pattern . callback . view_class , method ) . __doc__ if view_method_docstr : # Check if method is modifier if method in [ 'put' , 'patch' , 'delete' ] : self . url_details . append ( { 'url' : expected_url , 'method' : method } ) continue # Extract request method and JSON response from docstring of request method j = re . findall ( r'```(.*)```' , view_method_docstr , flags = re . DOTALL ) if j is not None : for match in j : expected_json_response = match . strip ( ) # Only add the details if all 3 values are filled if method is not None and expected_json_response and expected_url : self . url_details . append ( { 'url' : expected_url , 'method' : method , 'response' : expected_json_response } ) continue except ViewDoesNotExist : pass elif isinstance ( pattern , ( URLResolver , RegexURLResolver ) ) : try : patterns = pattern . url_patterns except ImportError : continue d = describe_pattern ( pattern ) current_full_url = parent + d self . _get_view_details ( patterns , current_full_url )
| 3,067
|
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/extractor.py#L81-L139
|
[
"def",
"write_lockfile",
"(",
"self",
",",
"content",
")",
":",
"s",
"=",
"self",
".",
"_lockfile_encoder",
".",
"encode",
"(",
"content",
")",
"open_kwargs",
"=",
"{",
"\"newline\"",
":",
"self",
".",
"_lockfile_newlines",
",",
"\"encoding\"",
":",
"\"utf-8\"",
"}",
"with",
"vistir",
".",
"contextmanagers",
".",
"atomic_open_for_write",
"(",
"self",
".",
"lockfile_location",
",",
"*",
"*",
"open_kwargs",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"s",
")",
"# Write newline at end of document. GH-319.",
"# Only need '\\n' here; the file object handles the rest.",
"if",
"not",
"s",
".",
"endswith",
"(",
"u\"\\n\"",
")",
":",
"f",
".",
"write",
"(",
"u\"\\n\"",
")"
] |
Calls the callback for each AST node that s a child of the given node .
|
def for_each_child ( node , callback ) : for name in node . _fields : value = getattr ( node , name ) if isinstance ( value , list ) : for item in value : if isinstance ( item , ast . AST ) : callback ( item ) elif isinstance ( value , ast . AST ) : callback ( value )
| 3,068
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L51-L60
|
[
"def",
"_write_cors_configuration",
"(",
"self",
",",
"config",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'user'",
",",
"'config'",
",",
"'cors'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"put",
"(",
"endpoint",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"config",
",",
"cls",
"=",
"self",
".",
"encoder",
")",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"response_to_json_dict",
"(",
"resp",
")"
] |
Resolves the path of the module referred to by from .. x import y .
|
def resolve_frompath ( pkgpath , relpath , level = 0 ) : if level == 0 : return relpath parts = pkgpath . split ( '.' ) + [ '_' ] parts = parts [ : - level ] + ( relpath . split ( '.' ) if relpath else [ ] ) return '.' . join ( parts )
| 3,069
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L62-L68
|
[
"def",
"SetHeaders",
"(",
"self",
",",
"soap_headers",
",",
"http_headers",
")",
":",
"self",
".",
"suds_client",
".",
"set_options",
"(",
"soapheaders",
"=",
"soap_headers",
",",
"headers",
"=",
"http_headers",
")"
] |
Determines whether a module exists with the given modpath .
|
def find_module ( modpath ) : module_path = modpath . replace ( '.' , '/' ) + '.py' init_path = modpath . replace ( '.' , '/' ) + '/__init__.py' for root_path in sys . path : path = os . path . join ( root_path , module_path ) if os . path . isfile ( path ) : return path path = os . path . join ( root_path , init_path ) if os . path . isfile ( path ) : return path
| 3,070
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L70-L80
|
[
"def",
"win32_refresh_window",
"(",
"cls",
")",
":",
"# Get console handle",
"handle",
"=",
"windll",
".",
"kernel32",
".",
"GetConsoleWindow",
"(",
")",
"RDW_INVALIDATE",
"=",
"0x0001",
"windll",
".",
"user32",
".",
"RedrawWindow",
"(",
"handle",
",",
"None",
",",
"None",
",",
"c_uint",
"(",
"RDW_INVALIDATE",
")",
")"
] |
Adds a possible origin for the given name in the given module .
|
def add ( self , modpath , name , origin ) : self . map . setdefault ( modpath , { } ) . setdefault ( name , set ( ) ) . add ( origin )
| 3,071
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L116-L118
|
[
"def",
"reset",
"(",
"self",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_count",
">",
"0",
":",
"if",
"self",
".",
"_state",
"==",
"0",
":",
"#reset the barrier, waking up threads",
"self",
".",
"_state",
"=",
"-",
"1",
"elif",
"self",
".",
"_state",
"==",
"-",
"2",
":",
"#was broken, set it to reset state",
"#which clears when the last thread exits",
"self",
".",
"_state",
"=",
"-",
"1",
"else",
":",
"self",
".",
"_state",
"=",
"0",
"self",
".",
"_cond",
".",
"notify_all",
"(",
")"
] |
Whenever you import a . b . c Python automatically binds b in a to the a . b module and binds c in a . b to the a . b . c module .
|
def add_package_origins ( self , modpath ) : parts = modpath . split ( '.' ) parent = parts [ 0 ] for part in parts [ 1 : ] : child = parent + '.' + part if self . find_module ( child ) : self . add ( parent , part , child ) parent = child
| 3,072
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L120-L129
|
[
"def",
"get_description_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"dict",
"(",
"self",
".",
"_mdata",
"[",
"'description'",
"]",
")",
"metadata",
".",
"update",
"(",
"{",
"'existing_string_values'",
":",
"self",
".",
"_my_map",
"[",
"'description'",
"]",
"[",
"'text'",
"]",
"}",
")",
"return",
"Metadata",
"(",
"*",
"*",
"metadata",
")"
] |
Scans a module collecting possible origins for all names assuming names can only become bound to values in other modules by import .
|
def scan_module ( self , pkgpath , modpath , node ) : def scan_imports ( node ) : if node_type ( node ) == 'Import' : for binding in node . names : name , asname = binding . name , binding . asname if asname : self . add ( modpath , asname , name ) else : top_name = name . split ( '.' ) [ 0 ] self . add ( modpath , top_name , top_name ) self . add_package_origins ( name ) elif node_type ( node ) == 'ImportFrom' : frompath = resolve_frompath ( pkgpath , node . module , node . level ) for binding in node . names : name , asname = binding . name , binding . asname if name == '*' : for name in self . get_star_names ( frompath ) : self . add ( modpath , name , frompath + '.' + name ) self . add_package_origins ( frompath ) else : self . add ( modpath , asname or name , frompath + '.' + name ) self . add_package_origins ( frompath + '.' + name ) else : for_each_child ( node , scan_imports ) for_each_child ( node , scan_imports )
| 3,073
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L131-L161
|
[
"def",
"_HasId",
"(",
"self",
",",
"schedule",
",",
"entity_id",
")",
":",
"try",
":",
"self",
".",
"_GetById",
"(",
"schedule",
",",
"entity_id",
")",
"has",
"=",
"True",
"except",
"KeyError",
":",
"has",
"=",
"False",
"return",
"has"
] |
Returns the set of possible origins for a name in a module .
|
def get_origins ( self , modpath , name ) : return self . map . get ( modpath , { } ) . get ( name , set ( ) )
| 3,074
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L163-L165
|
[
"def",
"touch",
"(",
"self",
",",
"message_id",
",",
"reservation_id",
",",
"timeout",
"=",
"None",
")",
":",
"url",
"=",
"\"queues/%s/messages/%s/touch\"",
"%",
"(",
"self",
".",
"name",
",",
"message_id",
")",
"qitems",
"=",
"{",
"'reservation_id'",
":",
"reservation_id",
"}",
"if",
"timeout",
"is",
"not",
"None",
":",
"qitems",
"[",
"'timeout'",
"]",
"=",
"timeout",
"body",
"=",
"json",
".",
"dumps",
"(",
"qitems",
")",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"url",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"response",
"[",
"'body'",
"]"
] |
Prints out the contents of the import map .
|
def dump ( self ) : for modpath in sorted ( self . map ) : title = 'Imports in %s' % modpath print ( '\n' + title + '\n' + '-' * len ( title ) ) for name , value in sorted ( self . map . get ( modpath , { } ) . items ( ) ) : print ( ' %s -> %s' % ( name , ', ' . join ( sorted ( value ) ) ) )
| 3,075
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L167-L173
|
[
"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_alarm",
"+=",
"handle_alarm",
"with",
"device",
".",
"open",
"(",
"baudrate",
"=",
"BAUDRATE",
")",
":",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"except",
"Exception",
"as",
"ex",
":",
"print",
"(",
"'Exception:'",
",",
"ex",
")"
] |
Scans a module collecting all used origins assuming that modules are obtained only by dotted paths and no other kinds of expressions .
|
def scan_module ( self , modpath , node ) : used_origins = self . map . setdefault ( modpath , set ( ) ) def get_origins ( modpath , name ) : """Returns the chain of all origins for a given name in a module.""" origins = set ( ) def walk_origins ( modpath , name ) : for origin in self . import_map . get_origins ( modpath , name ) : if origin not in origins : origins . add ( origin ) if '.' in origin : walk_origins ( * origin . rsplit ( '.' , 1 ) ) walk_origins ( modpath , name ) return origins def get_origins_for_node ( node ) : """Returns the set of all possible origins to which the given
dotted-path expression might dereference.""" if node_type ( node ) == 'Name' and node_type ( node . ctx ) == 'Load' : return { modpath + '.' + node . id } | get_origins ( modpath , node . id ) if node_type ( node ) == 'Attribute' and node_type ( node . ctx ) == 'Load' : return set . union ( set ( ) , * [ { parent + '.' + node . attr } | get_origins ( parent , node . attr ) for parent in get_origins_for_node ( node . value ) ] ) return set ( ) def get_origins_used_by_node ( node ) : """Returns the set of all possible origins that could be used
during dereferencing of the given dotted-path expression.""" if node_type ( node ) == 'Name' : return get_origins_for_node ( node ) if node_type ( node ) == 'Attribute' : return set . union ( get_origins_used_by_node ( node . value ) , get_origins_for_node ( node ) ) return set ( ) def scan_loads ( node ) : if node_type ( node ) in [ 'Name' , 'Attribute' ] : used_origins . update ( get_origins_used_by_node ( node ) ) for_each_child ( node , scan_loads ) for_each_child ( node , scan_loads ) intermediate_origins = set ( ) for origin in used_origins : parts = origin . split ( '.' ) for i in range ( 1 , len ( parts ) ) : intermediate_origins . add ( '.' . join ( parts [ : i ] ) ) used_origins . update ( intermediate_origins )
| 3,076
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L186-L239
|
[
"def",
"readKerningElement",
"(",
"self",
",",
"kerningElement",
",",
"instanceObject",
")",
":",
"kerningLocation",
"=",
"self",
".",
"locationFromElement",
"(",
"kerningElement",
")",
"instanceObject",
".",
"addKerning",
"(",
"kerningLocation",
")"
] |
Prints out the contents of the usage map .
|
def dump ( self ) : for modpath in sorted ( self . map ) : title = 'Used by %s' % modpath print ( '\n' + title + '\n' + '-' * len ( title ) ) for origin in sorted ( self . get_used_origins ( modpath ) ) : print ( ' %s' % origin )
| 3,077
|
https://github.com/zestyping/star-destroyer/blob/e23584c85d1e8b8f098e5c75977c6a98a41f3f68/star_destroyer.py#L247-L253
|
[
"def",
"trace_integration",
"(",
"tracer",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"'Integrated module: {}'",
".",
"format",
"(",
"MODULE_NAME",
")",
")",
"# Wrap the httplib request function",
"request_func",
"=",
"getattr",
"(",
"httplib",
".",
"HTTPConnection",
",",
"HTTPLIB_REQUEST_FUNC",
")",
"wrapped_request",
"=",
"wrap_httplib_request",
"(",
"request_func",
")",
"setattr",
"(",
"httplib",
".",
"HTTPConnection",
",",
"request_func",
".",
"__name__",
",",
"wrapped_request",
")",
"# Wrap the httplib response function",
"response_func",
"=",
"getattr",
"(",
"httplib",
".",
"HTTPConnection",
",",
"HTTPLIB_RESPONSE_FUNC",
")",
"wrapped_response",
"=",
"wrap_httplib_response",
"(",
"response_func",
")",
"setattr",
"(",
"httplib",
".",
"HTTPConnection",
",",
"response_func",
".",
"__name__",
",",
"wrapped_response",
")"
] |
Convert int to timestamp string .
|
def convert_to_timestamp ( time ) : if time == - 1 : return None time = int ( time * 1000 ) hour = time // 1000 // 3600 minute = ( time // 1000 // 60 ) % 60 second = ( time // 1000 ) % 60 return str ( hour ) . zfill ( 2 ) + ":" + str ( minute ) . zfill ( 2 ) + ":" + str ( second ) . zfill ( 2 )
| 3,078
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L43-L51
|
[
"def",
"pass_community",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"community_id",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"c",
"=",
"Community",
".",
"get",
"(",
"community_id",
")",
"if",
"c",
"is",
"None",
":",
"abort",
"(",
"404",
")",
"return",
"f",
"(",
"c",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner"
] |
Parse tunnel .
|
def _parse ( self , stream , context , path ) : length = self . length ( context ) new_stream = BytesIO ( construct . core . _read_stream ( stream , length ) ) return self . subcon . _parse ( new_stream , context , path )
| 3,079
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L26-L30
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Parse stream to find a given byte string .
|
def _parse ( self , stream , context , path ) : start = stream . tell ( ) read_bytes = "" if self . max_length : read_bytes = stream . read ( self . max_length ) else : read_bytes = stream . read ( ) skip = read_bytes . find ( self . find ) + len ( self . find ) stream . seek ( start + skip ) return skip
| 3,080
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L94-L104
|
[
"def",
"oauth_error_handler",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# OAuthErrors should not happen, so they are not caught here. Hence",
"# they will result in a 500 Internal Server Error which is what we",
"# are interested in.",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OAuthClientError",
"as",
"e",
":",
"current_app",
".",
"logger",
".",
"warning",
"(",
"e",
".",
"message",
",",
"exc_info",
"=",
"True",
")",
"return",
"oauth2_handle_error",
"(",
"e",
".",
"remote",
",",
"e",
".",
"response",
",",
"e",
".",
"code",
",",
"e",
".",
"uri",
",",
"e",
".",
"description",
")",
"except",
"OAuthCERNRejectedAccountError",
"as",
"e",
":",
"current_app",
".",
"logger",
".",
"warning",
"(",
"e",
".",
"message",
",",
"exc_info",
"=",
"True",
")",
"flash",
"(",
"_",
"(",
"'CERN account not allowed.'",
")",
",",
"category",
"=",
"'danger'",
")",
"return",
"redirect",
"(",
"'/'",
")",
"except",
"OAuthRejectedRequestError",
":",
"flash",
"(",
"_",
"(",
"'You rejected the authentication request.'",
")",
",",
"category",
"=",
"'info'",
")",
"return",
"redirect",
"(",
"'/'",
")",
"except",
"AlreadyLinkedError",
":",
"flash",
"(",
"_",
"(",
"'External service is already linked to another account.'",
")",
",",
"category",
"=",
"'danger'",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'invenio_oauthclient_settings.index'",
")",
")",
"return",
"inner"
] |
Parse until a given byte string is found .
|
def _parse ( self , stream , context , path ) : objs = [ ] while True : start = stream . tell ( ) test = stream . read ( len ( self . find ) ) stream . seek ( start ) if test == self . find : break else : subobj = self . subcon . _parse ( stream , context , path ) objs . append ( subobj ) return objs
| 3,081
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L117-L129
|
[
"def",
"_mmUpdateDutyCycles",
"(",
"self",
")",
":",
"period",
"=",
"self",
".",
"getDutyCyclePeriod",
"(",
")",
"unionSDRArray",
"=",
"numpy",
".",
"zeros",
"(",
"self",
".",
"getNumColumns",
"(",
")",
")",
"unionSDRArray",
"[",
"list",
"(",
"self",
".",
"_mmTraces",
"[",
"\"unionSDR\"",
"]",
".",
"data",
"[",
"-",
"1",
"]",
")",
"]",
"=",
"1",
"self",
".",
"_mmData",
"[",
"\"unionSDRDutyCycle\"",
"]",
"=",
"UnionTemporalPoolerMonitorMixin",
".",
"_mmUpdateDutyCyclesHelper",
"(",
"self",
".",
"_mmData",
"[",
"\"unionSDRDutyCycle\"",
"]",
",",
"unionSDRArray",
",",
"period",
")",
"self",
".",
"_mmData",
"[",
"\"persistenceDutyCycle\"",
"]",
"=",
"UnionTemporalPoolerMonitorMixin",
".",
"_mmUpdateDutyCyclesHelper",
"(",
"self",
".",
"_mmData",
"[",
"\"persistenceDutyCycle\"",
"]",
",",
"self",
".",
"_poolingActivation",
",",
"period",
")"
] |
Parse until the end of objects data .
|
def _parse ( self , stream , context , path ) : num_players = context . _ . _ . _ . replay . num_players start = stream . tell ( ) # Have to read everything to be able to use find() read_bytes = stream . read ( ) # Try to find the first marker, a portion of the next player structure marker_up14 = read_bytes . find ( b"\x16\xc6\x00\x00\x00\x21" ) marker_up15 = read_bytes . find ( b"\x16\xf0\x00\x00\x00\x21" ) marker = - 1 if marker_up14 > 0 and marker_up15 < 0 : marker = marker_up14 elif marker_up15 > 0 and marker_up14 < 0 : marker = marker_up15 # If it exists, we're not on the last player yet if marker > 0 : # Backtrack through the player name count = 0 while struct . unpack ( "<H" , read_bytes [ marker - 2 : marker ] ) [ 0 ] != count : marker -= 1 count += 1 # Backtrack through the rest of the next player structure backtrack = 43 + num_players # Otherwise, this is the last player else : # Search for the scenario header marker = read_bytes . find ( b"\xf6\x28\x9c\x3f" ) # Backtrack through the achievements and initial structure footer backtrack = ( ( 1817 * ( num_players - 1 ) ) + 4 + 19 ) # Seek to the position we found end = start + marker - backtrack stream . seek ( end ) return end
| 3,082
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L138-L170
|
[
"def",
"adjust_privileges",
"(",
"state",
",",
"privileges",
")",
":",
"with",
"win32",
".",
"OpenProcessToken",
"(",
"win32",
".",
"GetCurrentProcess",
"(",
")",
",",
"win32",
".",
"TOKEN_ADJUST_PRIVILEGES",
")",
"as",
"hToken",
":",
"NewState",
"=",
"(",
"(",
"priv",
",",
"state",
")",
"for",
"priv",
"in",
"privileges",
")",
"win32",
".",
"AdjustTokenPrivileges",
"(",
"hToken",
",",
"NewState",
")"
] |
Rollback config .
|
def rollback ( self , label , plane ) : cm_label = 'condoor-{}' . format ( int ( time . time ( ) ) ) self . device . send ( self . rollback_cmd . format ( label ) , timeout = 120 ) return cm_label
| 3,083
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/XR.py#L145-L149
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Starts profiling all threads and all greenlets .
|
def start ( builtins = False , profile_threads = True ) : # TODO: what about builtins False or profile_threads False? _vendorized_yappi . yappi . set_context_id_callback ( lambda : greenlet and id ( greenlet . getcurrent ( ) ) or 0 ) _vendorized_yappi . yappi . set_context_name_callback ( lambda : greenlet and greenlet . getcurrent ( ) . __class__ . __name__ or '' ) _vendorized_yappi . yappi . start ( builtins , profile_threads )
| 3,084
|
https://github.com/ajdavis/GreenletProfiler/blob/700349864a4f368a8a73a2a60f048c2e818d7cea/GreenletProfiler.py#L18-L35
|
[
"def",
"_uri_to_etext",
"(",
"cls",
",",
"uri_ref",
")",
":",
"try",
":",
"return",
"validate_etextno",
"(",
"int",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"uri_ref",
".",
"toPython",
"(",
")",
")",
")",
")",
"except",
"InvalidEtextIdException",
":",
"return",
"None"
] |
Connect using the Telnet protocol specific FSM .
|
def connect ( self , driver ) : # 0 1 2 3 events = [ ESCAPE_CHAR , driver . press_return_re , driver . standby_re , driver . username_re , # 4 5 6 7 driver . password_re , driver . more_re , self . device . prompt_re , driver . rommon_re , # 8 9 10 11 12 driver . unable_to_connect_re , driver . timeout_re , pexpect . TIMEOUT , PASSWORD_OK , driver . syntax_error_re ] transitions = [ ( ESCAPE_CHAR , [ 0 ] , 1 , None , _C [ 'esc_char_timeout' ] ) , ( driver . syntax_error_re , [ 0 ] , - 1 , CommandSyntaxError ( "Command syntax error" ) , 0 ) , ( driver . press_return_re , [ 0 , 1 ] , 1 , a_send_newline , 10 ) , ( PASSWORD_OK , [ 0 , 1 ] , 1 , a_send_newline , 10 ) , ( driver . standby_re , [ 0 , 5 ] , - 1 , partial ( a_standby_console ) , 0 ) , ( driver . username_re , [ 0 , 1 , 5 , 6 ] , - 1 , partial ( a_save_last_pattern , self ) , 0 ) , ( driver . password_re , [ 0 , 1 , 5 ] , - 1 , partial ( a_save_last_pattern , self ) , 0 ) , ( driver . more_re , [ 0 , 5 ] , 7 , partial ( a_send , "q" ) , 10 ) , # router sends it again to delete ( driver . more_re , [ 7 ] , 8 , None , 10 ) , # (prompt, [0, 1, 5], 6, a_send_newline, 10), ( self . device . prompt_re , [ 0 , 1 , 5 ] , 0 , None , 10 ) , ( self . device . prompt_re , [ 6 , 8 , 5 ] , - 1 , partial ( a_save_last_pattern , self ) , 0 ) , ( driver . rommon_re , [ 0 , 1 , 5 ] , - 1 , partial ( a_save_last_pattern , self ) , 0 ) , ( driver . unable_to_connect_re , [ 0 , 1 , 5 ] , - 1 , a_unable_to_connect , 0 ) , ( driver . timeout_re , [ 0 , 1 , 5 ] , - 1 , ConnectionTimeoutError ( "Connection Timeout" , self . hostname ) , 0 ) , ( pexpect . TIMEOUT , [ 0 , 1 ] , 5 , a_send_newline , 10 ) , ( pexpect . TIMEOUT , [ 5 ] , - 1 , ConnectionTimeoutError ( "Connection timeout" , self . hostname ) , 0 ) ] self . log ( "EXPECTED_PROMPT={}" . format ( pattern_to_str ( self . device . prompt_re ) ) ) # setting max_transitions to large number to swallow prompt like strings from prompt fsm = FSM ( "TELNET-CONNECT" , self . device , events , transitions , timeout = _C [ 'connect_timeout' ] , init_pattern = self . last_pattern , max_transitions = 500 ) return fsm . run ( )
| 3,085
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/telnet.py#L37-L71
|
[
"def",
"cancelRealTimeBars",
"(",
"self",
",",
"bars",
":",
"RealTimeBarList",
")",
":",
"self",
".",
"client",
".",
"cancelRealTimeBars",
"(",
"bars",
".",
"reqId",
")",
"self",
".",
"wrapper",
".",
"endSubscription",
"(",
"bars",
")"
] |
Disconnect from the console .
|
def disconnect ( self , driver ) : self . log ( "TELNETCONSOLE disconnect" ) try : while self . device . mode != 'global' : self . device . send ( 'exit' , timeout = 10 ) except OSError : self . log ( "TELNETCONSOLE already disconnected" ) except pexpect . TIMEOUT : self . log ( "TELNETCONSOLE unable to get the root prompt" ) try : self . device . ctrl . send ( chr ( 4 ) ) except OSError : self . log ( "TELNETCONSOLE already disconnected" )
| 3,086
|
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/telnet.py#L147-L161
|
[
"def",
"mainview",
"(",
"request",
",",
"*",
"*",
"criterias",
")",
":",
"view_data",
"=",
"initview",
"(",
"request",
")",
"wrap",
"=",
"lambda",
"func",
":",
"ft",
".",
"partial",
"(",
"func",
",",
"_view_data",
"=",
"view_data",
",",
"*",
"*",
"criterias",
")",
"return",
"condition",
"(",
"etag_func",
"=",
"wrap",
"(",
"cache_etag",
")",
",",
"last_modified_func",
"=",
"wrap",
"(",
"cache_last_modified",
")",
")",
"(",
"_mainview",
")",
"(",
"request",
",",
"view_data",
",",
"*",
"*",
"criterias",
")"
] |
Calculate player s rAPM .
|
def _calculate_apm ( index , player_actions , other_actions , duration ) : apm_per_player = { } for player_index , histogram in player_actions . items ( ) : apm_per_player [ player_index ] = sum ( histogram . values ( ) ) total_unattributed = sum ( other_actions . values ( ) ) total_attributed = sum ( apm_per_player . values ( ) ) player_proportion = apm_per_player [ index ] / total_attributed player_unattributed = total_unattributed * player_proportion apm = ( apm_per_player [ index ] + player_unattributed ) / ( duration / 60 ) return int ( apm )
| 3,087
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L59-L69
|
[
"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.\"",
")"
] |
Sometimes a game is finished but not recorded as such .
|
def guess_finished ( summary , postgame ) : if postgame and postgame . complete : return True for player in summary [ 'players' ] : if 'resign' in player [ 'action_histogram' ] : return True return False
| 3,088
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L72-L79
|
[
"def",
"prior_const",
"(",
"C",
",",
"alpha",
"=",
"0.001",
")",
":",
"if",
"isdense",
"(",
"C",
")",
":",
"return",
"sparse",
".",
"prior",
".",
"prior_const",
"(",
"C",
",",
"alpha",
"=",
"alpha",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"Prior will be a dense matrix for sparse input\"",
")",
"return",
"sparse",
".",
"prior",
".",
"prior_const",
"(",
"C",
",",
"alpha",
"=",
"alpha",
")"
] |
Compute number of players both human and computer .
|
def _num_players ( self ) : self . _player_num = 0 self . _computer_num = 0 for player in self . _header . scenario . game_settings . player_info : if player . type == 'human' : self . _player_num += 1 elif player . type == 'computer' : self . _computer_num += 1
| 3,089
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L124-L132
|
[
"def",
"_resolve_default",
"(",
"data_type",
",",
"listify",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data_type",
",",
"_ATOMIC",
")",
":",
"# A Python's object type needs to be left as is instead of being",
"# wrapped into a NumPy type.",
"out",
"=",
"(",
"data_type",
".",
"default",
"if",
"isinstance",
"(",
"data_type",
",",
"Object",
")",
"else",
"_get_atomic_dtype",
"(",
"data_type",
")",
"(",
"data_type",
".",
"default",
")",
")",
"elif",
"isinstance",
"(",
"data_type",
",",
"Array",
")",
":",
"element_default",
"=",
"_resolve_default",
"(",
"data_type",
".",
"element_type",
",",
"listify",
"=",
"listify",
")",
"Sequence",
"=",
"list",
"if",
"listify",
"else",
"tuple",
"shape",
"=",
"(",
"(",
"data_type",
".",
"shape",
",",
")",
"if",
"isinstance",
"(",
"data_type",
".",
"shape",
",",
"int",
")",
"else",
"data_type",
".",
"shape",
")",
"out",
"=",
"element_default",
"for",
"dimension",
"in",
"shape",
":",
"out",
"=",
"Sequence",
"(",
"copy",
".",
"deepcopy",
"(",
"out",
")",
"for",
"_",
"in",
"_range",
"(",
"dimension",
")",
")",
"elif",
"isinstance",
"(",
"data_type",
",",
"Structure",
")",
":",
"if",
"listify",
":",
"out",
"=",
"[",
"_resolve_default",
"(",
"field",
".",
"type",
",",
"listify",
"=",
"listify",
")",
"for",
"field",
"in",
"data_type",
".",
"fields",
"]",
"else",
":",
"field_defaults",
"=",
"collections",
".",
"OrderedDict",
"(",
"(",
"field",
".",
"name",
",",
"_resolve_default",
"(",
"field",
".",
"type",
",",
"listify",
"=",
"listify",
")",
")",
"for",
"field",
"in",
"data_type",
".",
"fields",
")",
"name",
"=",
"(",
"'StructureDefault_%s'",
"%",
"(",
"data_type",
".",
"name",
",",
")",
"if",
"data_type",
".",
"name",
"else",
"'StructureDefault'",
")",
"struct",
"=",
"collections",
".",
"namedtuple",
"(",
"name",
",",
"field_defaults",
".",
"keys",
"(",
")",
")",
"out",
"=",
"struct",
"(",
"*",
"*",
"field_defaults",
")",
"return",
"out"
] |
Parse a lobby chat message .
|
def _parse_lobby_chat ( self , messages , source , timestamp ) : for message in messages : if message . message_length == 0 : continue chat = ChatMessage ( message . message , timestamp , self . _players ( ) , source = source ) self . _parse_chat ( chat )
| 3,090
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L134-L140
|
[
"def",
"query",
"(",
"path",
",",
"method",
"=",
"'GET'",
",",
"data",
"=",
"None",
",",
"params",
"=",
"None",
",",
"header_dict",
"=",
"None",
",",
"decode",
"=",
"True",
")",
":",
"certificate_path",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'certificate_path'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"subscription_id",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str",
"(",
"config",
".",
"get_cloud_config_value",
"(",
"'subscription_id'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
")",
"management_host",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'management_host'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"'management.core.windows.net'",
")",
"backend",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'backend'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"url",
"=",
"'https://{management_host}/{subscription_id}/{path}'",
".",
"format",
"(",
"management_host",
"=",
"management_host",
",",
"subscription_id",
"=",
"subscription_id",
",",
"path",
"=",
"path",
",",
")",
"if",
"header_dict",
"is",
"None",
":",
"header_dict",
"=",
"{",
"}",
"header_dict",
"[",
"'x-ms-version'",
"]",
"=",
"'2014-06-01'",
"result",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"url",
",",
"method",
"=",
"method",
",",
"params",
"=",
"params",
",",
"data",
"=",
"data",
",",
"header_dict",
"=",
"header_dict",
",",
"port",
"=",
"443",
",",
"text",
"=",
"True",
",",
"cert",
"=",
"certificate_path",
",",
"backend",
"=",
"backend",
",",
"decode",
"=",
"decode",
",",
"decode_type",
"=",
"'xml'",
",",
")",
"if",
"'dict'",
"in",
"result",
":",
"return",
"result",
"[",
"'dict'",
"]",
"return"
] |
Parse a player action .
|
def _parse_action ( self , action , current_time ) : if action . action_type == 'research' : name = mgz . const . TECHNOLOGIES [ action . data . technology_type ] self . _research [ action . data . player_id ] . append ( { 'technology' : name , 'timestamp' : _timestamp_to_time ( action . timestamp ) } ) elif action . action_type == 'build' : self . _build [ action . data . player_id ] . append ( { 'building' : mgz . const . UNITS [ action . data . building_type ] , 'timestamp' : _timestamp_to_time ( current_time ) , 'coordinates' : { 'x' : action . data . x , 'y' : action . data . y } } ) elif action . action_type == 'queue' : for _ in range ( 0 , int ( action . data . number ) ) : self . _queue . append ( { 'unit' : mgz . const . UNITS [ action . data . unit_type ] , 'timestamp' : _timestamp_to_time ( current_time ) } )
| 3,091
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L142-L164
|
[
"def",
"get_catalog",
"(",
"self",
",",
"query",
")",
":",
"# TODO: Refactor TDSCatalog so we don't need two requests, or to do URL munging",
"try",
":",
"url",
"=",
"self",
".",
"_base",
"[",
":",
"-",
"1",
"]",
"if",
"self",
".",
"_base",
"[",
"-",
"1",
"]",
"==",
"'/'",
"else",
"self",
".",
"_base",
"url",
"+=",
"'?'",
"+",
"str",
"(",
"query",
")",
"return",
"TDSCatalog",
"(",
"url",
")",
"except",
"ET",
".",
"ParseError",
":",
"raise",
"BadQueryError",
"(",
"self",
".",
"get_catalog_raw",
"(",
"query",
")",
")"
] |
Process operation stream .
|
def operations ( self , op_types = None ) : if not op_types : op_types = [ 'message' , 'action' , 'sync' , 'viewlock' , 'savedchapter' ] while self . _handle . tell ( ) < self . _eof : current_time = mgz . util . convert_to_timestamp ( self . _time / 1000 ) try : operation = mgz . body . operation . parse_stream ( self . _handle ) except ( ConstructError , ValueError ) : raise MgzError ( 'failed to parse body operation' ) if operation . type == 'action' : if operation . action . type in ACTIONS_WITH_PLAYER_ID : counter = self . _actions_by_player [ operation . action . player_id ] counter . update ( [ operation . action . type ] ) else : self . _actions_without_player . update ( [ operation . action . type ] ) if operation . type == 'action' and isinstance ( operation . action . type , int ) : print ( operation . action ) if operation . type == 'sync' : self . _time += operation . time_increment if operation . type == 'action' and operation . action . type == 'postgame' : self . _postgame = operation if operation . type == 'action' : action = Action ( operation , current_time ) self . _parse_action ( action , current_time ) if operation . type == 'savedchapter' : # fix: Don't load messages we already saw in header or prev saved chapters self . _parse_lobby_chat ( operation . lobby . messages , 'save' , current_time ) if operation . type == 'viewlock' : if operation . type in op_types : yield Viewlock ( operation ) elif operation . type == 'action' and operation . action . type != 'postgame' : if operation . type in op_types : yield Action ( operation , current_time ) elif ( ( operation . type == 'message' or operation . type == 'embedded' ) and operation . subtype == 'chat' ) : chat = ChatMessage ( operation . data . text , current_time , self . _players ( ) , self . _diplomacy [ 'type' ] , 'game' ) self . _parse_chat ( chat ) if operation . type in op_types : yield chat
| 3,092
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L167-L207
|
[
"def",
"coordination_geometry_symmetry_measures_fallback_random",
"(",
"self",
",",
"coordination_geometry",
",",
"NRANDOM",
"=",
"10",
",",
"points_perfect",
"=",
"None",
")",
":",
"permutations_symmetry_measures",
"=",
"[",
"None",
"]",
"*",
"NRANDOM",
"permutations",
"=",
"list",
"(",
")",
"algos",
"=",
"list",
"(",
")",
"perfect2local_maps",
"=",
"list",
"(",
")",
"local2perfect_maps",
"=",
"list",
"(",
")",
"for",
"iperm",
"in",
"range",
"(",
"NRANDOM",
")",
":",
"perm",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"coordination_geometry",
".",
"coordination_number",
")",
"permutations",
".",
"append",
"(",
"perm",
")",
"p2l",
"=",
"{",
"}",
"l2p",
"=",
"{",
"}",
"for",
"i_p",
",",
"pp",
"in",
"enumerate",
"(",
"perm",
")",
":",
"p2l",
"[",
"i_p",
"]",
"=",
"pp",
"l2p",
"[",
"pp",
"]",
"=",
"i_p",
"perfect2local_maps",
".",
"append",
"(",
"p2l",
")",
"local2perfect_maps",
".",
"append",
"(",
"l2p",
")",
"points_distorted",
"=",
"self",
".",
"local_geometry",
".",
"points_wcs_ctwcc",
"(",
"permutation",
"=",
"perm",
")",
"sm_info",
"=",
"symmetry_measure",
"(",
"points_distorted",
"=",
"points_distorted",
",",
"points_perfect",
"=",
"points_perfect",
")",
"sm_info",
"[",
"'translation_vector'",
"]",
"=",
"self",
".",
"local_geometry",
".",
"centroid_with_centre",
"permutations_symmetry_measures",
"[",
"iperm",
"]",
"=",
"sm_info",
"algos",
".",
"append",
"(",
"'APPROXIMATE_FALLBACK'",
")",
"return",
"permutations_symmetry_measures",
",",
"permutations",
",",
"algos",
",",
"local2perfect_maps",
",",
"perfect2local_maps"
] |
Summarize game .
|
def summarize ( self ) : if not self . _achievements_summarized : for _ in self . operations ( ) : pass self . _summarize ( ) return self . _summary
| 3,093
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L214-L220
|
[
"def",
"delete_entity",
"(",
"self",
",",
"entity_id",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"'/v1/{mount_point}/entity/id/{id}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"id",
"=",
"entity_id",
",",
")",
"return",
"self",
".",
"_adapter",
".",
"delete",
"(",
"url",
"=",
"api_path",
",",
")"
] |
Is this game nomad .
|
def is_nomad ( self ) : nomad = self . _header . initial . restore_time == 0 or None for i in range ( 1 , self . _header . replay . num_players ) : for obj in self . _header . initial . players [ i ] . objects : if obj . type == 'building' and obj . object_type == 'tc_1' : return False return nomad
| 3,094
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L222-L232
|
[
"def",
"_init_config",
"(",
"self",
",",
"width",
",",
"height",
",",
"spi",
"=",
"None",
",",
"spiMosi",
"=",
"None",
",",
"spiDC",
"=",
"None",
",",
"spiCS",
"=",
"None",
",",
"spiReset",
"=",
"None",
",",
"spiClk",
"=",
"None",
")",
":",
"self",
".",
"_spi",
"=",
"spi",
"self",
".",
"_spi_mosi",
"=",
"spiMosi",
"self",
".",
"_spi_dc",
"=",
"spiDC",
"self",
".",
"_spi_cs",
"=",
"spiCS",
"self",
".",
"_spi_reset",
"=",
"spiReset",
"self",
".",
"_spi_clk",
"=",
"spiClk",
"self",
".",
"width",
"=",
"width",
"self",
".",
"height",
"=",
"height"
] |
Is this game regicide .
|
def is_regicide ( self ) : for i in range ( 1 , self . _header . replay . num_players ) : for obj in self . _header . initial . players [ i ] . objects : if obj . type == 'unit' and obj . object_type == 'king' : return True return False
| 3,095
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L234-L240
|
[
"def",
"_configure_manager",
"(",
"self",
")",
":",
"self",
".",
"_manager",
"=",
"CloudBlockStorageManager",
"(",
"self",
",",
"resource_class",
"=",
"CloudBlockStorageVolume",
",",
"response_key",
"=",
"\"volume\"",
",",
"uri_base",
"=",
"\"volumes\"",
")",
"self",
".",
"_types_manager",
"=",
"BaseManager",
"(",
"self",
",",
"resource_class",
"=",
"CloudBlockStorageVolumeType",
",",
"response_key",
"=",
"\"volume_type\"",
",",
"uri_base",
"=",
"\"types\"",
")",
"self",
".",
"_snapshot_manager",
"=",
"CloudBlockStorageSnapshotManager",
"(",
"self",
",",
"resource_class",
"=",
"CloudBlockStorageSnapshot",
",",
"response_key",
"=",
"\"snapshot\"",
",",
"uri_base",
"=",
"\"snapshots\"",
")"
] |
Parse a chat message .
|
def _parse_chat ( self , chat ) : if chat . data [ 'type' ] == 'chat' : if chat . data [ 'player' ] in [ p . player_name for i , p in self . _players ( ) ] : self . _chat . append ( chat . data ) elif chat . data [ 'type' ] == 'ladder' : self . _ladder = chat . data [ 'ladder' ] elif chat . data [ 'type' ] == 'rating' : if chat . data [ 'rating' ] != 1600 : self . _ratings [ chat . data [ 'player' ] ] = chat . data [ 'rating' ]
| 3,096
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L253-L262
|
[
"def",
"fetch",
"(",
"self",
",",
"vault_client",
")",
":",
"backends",
"=",
"[",
"(",
"self",
".",
"mounts",
",",
"SecretBackend",
")",
",",
"(",
"self",
".",
"auths",
",",
"AuthBackend",
")",
",",
"(",
"self",
".",
"logs",
",",
"LogBackend",
")",
"]",
"for",
"b_list",
",",
"b_class",
"in",
"backends",
":",
"backend_list",
"=",
"b_list",
"(",
")",
"if",
"backend_list",
":",
"existing",
"=",
"getattr",
"(",
"vault_client",
",",
"b_class",
".",
"list_fun",
")",
"(",
")",
"for",
"backend",
"in",
"backend_list",
":",
"backend",
".",
"fetch",
"(",
"vault_client",
",",
"existing",
")",
"for",
"rsc",
"in",
"self",
".",
"resources",
"(",
")",
":",
"if",
"issubclass",
"(",
"type",
"(",
"rsc",
")",
",",
"Secret",
")",
":",
"nc_exists",
"=",
"(",
"rsc",
".",
"mount",
"!=",
"'cubbyhole'",
"and",
"find_backend",
"(",
"rsc",
".",
"mount",
",",
"self",
".",
"_mounts",
")",
".",
"existing",
")",
"if",
"nc_exists",
"or",
"rsc",
".",
"mount",
"==",
"'cubbyhole'",
":",
"rsc",
".",
"fetch",
"(",
"vault_client",
")",
"elif",
"issubclass",
"(",
"type",
"(",
"rsc",
")",
",",
"Auth",
")",
":",
"if",
"find_backend",
"(",
"rsc",
".",
"mount",
",",
"self",
".",
"_auths",
")",
".",
"existing",
":",
"rsc",
".",
"fetch",
"(",
"vault_client",
")",
"elif",
"issubclass",
"(",
"type",
"(",
"rsc",
")",
",",
"Mount",
")",
":",
"rsc",
".",
"existing",
"=",
"find_backend",
"(",
"rsc",
".",
"mount",
",",
"self",
".",
"_mounts",
")",
".",
"existing",
"else",
":",
"rsc",
".",
"fetch",
"(",
"vault_client",
")",
"return",
"self"
] |
Get compass position of player .
|
def _compass_position ( self , player_x , player_y ) : map_dim = self . _map . size_x third = map_dim * ( 1 / 3.0 ) for direction in mgz . const . COMPASS : point = mgz . const . COMPASS [ direction ] xlower = point [ 0 ] * map_dim xupper = ( point [ 0 ] * map_dim ) + third ylower = point [ 1 ] * map_dim yupper = ( point [ 1 ] * map_dim ) + third if ( player_x >= xlower and player_x < xupper and player_y >= ylower and player_y < yupper ) : return direction
| 3,097
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L340-L352
|
[
"def",
"delete",
"(",
"self",
",",
"subscription_id",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"subscription_id",
"or",
"not",
"subscription_id",
".",
"startswith",
"(",
"self",
".",
"RESOURCE_ID_PREFIX",
")",
":",
"raise",
"IdentifierError",
"(",
"\"Invalid subscription ID: '{id}'. A subscription ID should start with '{prefix}'.\"",
".",
"format",
"(",
"id",
"=",
"subscription_id",
",",
"prefix",
"=",
"self",
".",
"RESOURCE_ID_PREFIX",
")",
")",
"result",
"=",
"super",
"(",
"CustomerSubscriptions",
",",
"self",
")",
".",
"delete",
"(",
"subscription_id",
",",
"data",
")",
"return",
"self",
".",
"get_resource_object",
"(",
"result",
")"
] |
Get player attributes with index . No Gaia .
|
def _players ( self ) : for i in range ( 1 , self . _header . replay . num_players ) : yield i , self . _header . initial . players [ i ] . attributes
| 3,098
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L354-L357
|
[
"def",
"restore",
"(",
"archive",
",",
"oqdata",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"oqdata",
")",
":",
"sys",
".",
"exit",
"(",
"'%s exists already'",
"%",
"oqdata",
")",
"if",
"'://'",
"in",
"archive",
":",
"# get the zip archive from an URL",
"resp",
"=",
"requests",
".",
"get",
"(",
"archive",
")",
"_",
",",
"archive",
"=",
"archive",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"with",
"open",
"(",
"archive",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"resp",
".",
"content",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archive",
")",
":",
"sys",
".",
"exit",
"(",
"'%s does not exist'",
"%",
"archive",
")",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"oqdata",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"oqdata",
")",
"assert",
"archive",
".",
"endswith",
"(",
"'.zip'",
")",
",",
"archive",
"os",
".",
"mkdir",
"(",
"oqdata",
")",
"zipfile",
".",
"ZipFile",
"(",
"archive",
")",
".",
"extractall",
"(",
"oqdata",
")",
"dbpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"oqdata",
",",
"'db.sqlite3'",
")",
"db",
"=",
"Db",
"(",
"sqlite3",
".",
"connect",
",",
"dbpath",
",",
"isolation_level",
"=",
"None",
",",
"detect_types",
"=",
"sqlite3",
".",
"PARSE_DECLTYPES",
")",
"n",
"=",
"0",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"oqdata",
")",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"'calc_(\\d+)\\.hdf5'",
",",
"fname",
")",
"if",
"mo",
":",
"job_id",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"oqdata",
",",
"fname",
")",
"[",
":",
"-",
"5",
"]",
"# strip .hdf5",
"db",
"(",
"\"UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x\"",
",",
"getpass",
".",
"getuser",
"(",
")",
",",
"fullname",
",",
"job_id",
")",
"safeprint",
"(",
"'Restoring '",
"+",
"fname",
")",
"n",
"+=",
"1",
"dt",
"=",
"time",
".",
"time",
"(",
")",
"-",
"t0",
"safeprint",
"(",
"'Extracted %d calculations into %s in %d seconds'",
"%",
"(",
"n",
",",
"oqdata",
",",
"dt",
")",
")"
] |
Return parsed players .
|
def players ( self , postgame , game_type ) : for i , attributes in self . _players ( ) : yield self . _parse_player ( i , attributes , postgame , game_type )
| 3,099
|
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L359-L362
|
[
"def",
"apply_binding",
"(",
"self",
",",
"binding",
",",
"msg_str",
",",
"destination",
"=",
"\"\"",
",",
"relay_state",
"=",
"\"\"",
",",
"response",
"=",
"False",
",",
"sign",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# unless if BINDING_HTTP_ARTIFACT",
"if",
"response",
":",
"typ",
"=",
"\"SAMLResponse\"",
"else",
":",
"typ",
"=",
"\"SAMLRequest\"",
"if",
"binding",
"==",
"BINDING_HTTP_POST",
":",
"logger",
".",
"info",
"(",
"\"HTTP POST\"",
")",
"# if self.entity_type == 'sp':",
"# info = self.use_http_post(msg_str, destination, relay_state,",
"# typ)",
"# info[\"url\"] = destination",
"# info[\"method\"] = \"POST\"",
"# else:",
"info",
"=",
"self",
".",
"use_http_form_post",
"(",
"msg_str",
",",
"destination",
",",
"relay_state",
",",
"typ",
")",
"info",
"[",
"\"url\"",
"]",
"=",
"destination",
"info",
"[",
"\"method\"",
"]",
"=",
"\"POST\"",
"elif",
"binding",
"==",
"BINDING_HTTP_REDIRECT",
":",
"logger",
".",
"info",
"(",
"\"HTTP REDIRECT\"",
")",
"sigalg",
"=",
"kwargs",
".",
"get",
"(",
"\"sigalg\"",
")",
"if",
"sign",
"and",
"sigalg",
":",
"signer",
"=",
"self",
".",
"sec",
".",
"sec_backend",
".",
"get_signer",
"(",
"sigalg",
")",
"else",
":",
"signer",
"=",
"None",
"info",
"=",
"self",
".",
"use_http_get",
"(",
"msg_str",
",",
"destination",
",",
"relay_state",
",",
"typ",
",",
"signer",
"=",
"signer",
",",
"*",
"*",
"kwargs",
")",
"info",
"[",
"\"url\"",
"]",
"=",
"str",
"(",
"destination",
")",
"info",
"[",
"\"method\"",
"]",
"=",
"\"GET\"",
"elif",
"binding",
"==",
"BINDING_SOAP",
"or",
"binding",
"==",
"BINDING_PAOS",
":",
"info",
"=",
"self",
".",
"use_soap",
"(",
"msg_str",
",",
"destination",
",",
"sign",
"=",
"sign",
",",
"*",
"*",
"kwargs",
")",
"elif",
"binding",
"==",
"BINDING_URI",
":",
"info",
"=",
"self",
".",
"use_http_uri",
"(",
"msg_str",
",",
"typ",
",",
"destination",
")",
"elif",
"binding",
"==",
"BINDING_HTTP_ARTIFACT",
":",
"if",
"response",
":",
"info",
"=",
"self",
".",
"use_http_artifact",
"(",
"msg_str",
",",
"destination",
",",
"relay_state",
")",
"info",
"[",
"\"method\"",
"]",
"=",
"\"GET\"",
"info",
"[",
"\"status\"",
"]",
"=",
"302",
"else",
":",
"info",
"=",
"self",
".",
"use_http_artifact",
"(",
"msg_str",
",",
"destination",
",",
"relay_state",
")",
"else",
":",
"raise",
"SAMLError",
"(",
"\"Unknown binding type: %s\"",
"%",
"binding",
")",
"return",
"info"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.