query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
filter_by query helper that handles soft delete logic . If your query conditions require expressions use read .
def read_by ( cls , removed = False , * * kwargs ) : if not removed : kwargs [ 'time_removed' ] = 0 return cls . query . filter_by ( * * kwargs )
12,300
https://github.com/JawboneHealth/jhhalchemy/blob/ca0011d644e404561a142c9d7f0a8a569f1f4f27/jhhalchemy/model/__init__.py#L45-L55
[ "def", "add", "(", "name", ",", "*", "*", "kwargs", ")", ":", "_CONFIG", ".", "add_section", "(", "name", ")", "for", "(", "key", ",", "value", ")", "in", "kwargs", ".", "items", "(", ")", ":", "_CONFIG", ".", "set", "(", "name", ",", "key", ",", "value", ")", "with", "open", "(", "_CONFIG_FILEPATH", ",", "'w'", ")", "as", "configfile", ":", "_CONFIG", ".", "write", "(", "configfile", ")", "info", "(", "'Configuration updated at %s'", "%", "_JUT_HOME", ")" ]
filter query helper that handles soft delete logic . If your query conditions do not require expressions consider using read_by .
def read ( cls , * criteria , * * kwargs ) : if not kwargs . get ( 'removed' , False ) : return cls . query . filter ( cls . time_removed == 0 , * criteria ) return cls . query . filter ( * criteria )
12,301
https://github.com/JawboneHealth/jhhalchemy/blob/ca0011d644e404561a142c9d7f0a8a569f1f4f27/jhhalchemy/model/__init__.py#L58-L69
[ "def", "time_annotated", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "start", "=", "time", "(", ")", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "end", "=", "time", "(", ")", "result", ".", "time", "=", "round", "(", "end", "-", "start", ",", "config", ".", "PRECISION", ")", "return", "result" ]
Delete a row from the DB .
def delete ( self , session , commit = True , soft = True ) : if soft : self . time_removed = sqlalchemy . func . unix_timestamp ( ) else : session . delete ( self ) if commit : session . commit ( )
12,302
https://github.com/JawboneHealth/jhhalchemy/blob/ca0011d644e404561a142c9d7f0a8a569f1f4f27/jhhalchemy/model/__init__.py#L71-L85
[ "def", "MakeRequest", "(", "self", ",", "data", ")", ":", "stats_collector_instance", ".", "Get", "(", ")", ".", "IncrementCounter", "(", "\"grr_client_sent_bytes\"", ",", "len", "(", "data", ")", ")", "# Verify the response is as it should be from the control endpoint.", "response", "=", "self", ".", "http_manager", ".", "OpenServerEndpoint", "(", "path", "=", "\"control?api=%s\"", "%", "config", ".", "CONFIG", "[", "\"Network.api\"", "]", ",", "verify_cb", "=", "self", ".", "VerifyServerControlResponse", ",", "data", "=", "data", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"binary/octet-stream\"", "}", ")", "if", "response", ".", "code", "==", "406", ":", "self", ".", "InitiateEnrolment", "(", ")", "return", "response", "if", "response", ".", "code", "==", "200", ":", "stats_collector_instance", ".", "Get", "(", ")", ".", "IncrementCounter", "(", "\"grr_client_received_bytes\"", ",", "len", "(", "response", ".", "data", ")", ")", "return", "response", "# An unspecified error occured.", "return", "response" ]
Recursively traverse all paths inside this entity including the entity itself .
def walk_paths ( self , base : Optional [ pathlib . PurePath ] = pathlib . PurePath ( ) ) -> Iterator [ pathlib . PurePath ] : raise NotImplementedError ( )
12,303
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L27-L37
[ "def", "to_td", "(", "frame", ",", "name", ",", "con", ",", "if_exists", "=", "'fail'", ",", "time_col", "=", "None", ",", "time_index", "=", "None", ",", "index", "=", "True", ",", "index_label", "=", "None", ",", "chunksize", "=", "10000", ",", "date_format", "=", "None", ")", ":", "database", ",", "table", "=", "name", ".", "split", "(", "'.'", ")", "uploader", "=", "StreamingUploader", "(", "con", ".", "client", ",", "database", ",", "table", ",", "show_progress", "=", "True", ",", "clear_progress", "=", "True", ")", "uploader", ".", "message", "(", "'Streaming import into: {0}.{1}'", ".", "format", "(", "database", ",", "table", ")", ")", "# check existence", "if", "if_exists", "==", "'fail'", ":", "try", ":", "con", ".", "client", ".", "table", "(", "database", ",", "table", ")", "except", "tdclient", ".", "api", ".", "NotFoundError", ":", "uploader", ".", "message", "(", "'creating new table...'", ")", "con", ".", "client", ".", "create_log_table", "(", "database", ",", "table", ")", "else", ":", "raise", "RuntimeError", "(", "'table \"%s\" already exists'", "%", "name", ")", "elif", "if_exists", "==", "'replace'", ":", "try", ":", "con", ".", "client", ".", "table", "(", "database", ",", "table", ")", "except", "tdclient", ".", "api", ".", "NotFoundError", ":", "pass", "else", ":", "uploader", ".", "message", "(", "'deleting old table...'", ")", "con", ".", "client", ".", "delete_table", "(", "database", ",", "table", ")", "uploader", ".", "message", "(", "'creating new table...'", ")", "con", ".", "client", ".", "create_log_table", "(", "database", ",", "table", ")", "elif", "if_exists", "==", "'append'", ":", "try", ":", "con", ".", "client", ".", "table", "(", "database", ",", "table", ")", "except", "tdclient", ".", "api", ".", "NotFoundError", ":", "uploader", ".", "message", "(", "'creating new table...'", ")", "con", ".", "client", ".", "create_log_table", "(", "database", ",", "table", ")", "else", ":", "raise", "ValueError", "(", "'invalid value for if_exists: %s'", "%", "if_exists", ")", "# \"time_index\" implies \"index=False\"", "if", "time_index", ":", "index", "=", "None", "# convert", "frame", "=", "frame", ".", "copy", "(", ")", "frame", "=", "_convert_time_column", "(", "frame", ",", "time_col", ",", "time_index", ")", "frame", "=", "_convert_index_column", "(", "frame", ",", "index", ",", "index_label", ")", "frame", "=", "_convert_date_format", "(", "frame", ",", "date_format", ")", "# upload", "uploader", ".", "upload_frame", "(", "frame", ",", "chunksize", ")", "uploader", ".", "wait_for_import", "(", "len", "(", "frame", ")", ")" ]
Internal helper for walking paths . This is required to exclude the name of the root entity from the walk .
def _walk_paths ( self , base : pathlib . PurePath ) -> Iterator [ pathlib . PurePath ] : return self . walk_paths ( base )
12,304
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L39-L48
[ "def", "_CreateZMQSocket", "(", "self", ")", ":", "super", "(", "ZeroMQBufferedQueue", ",", "self", ")", ".", "_CreateZMQSocket", "(", ")", "if", "not", "self", ".", "_zmq_thread", ":", "thread_name", "=", "'{0:s}_zmq_responder'", ".", "format", "(", "self", ".", "name", ")", "self", ".", "_zmq_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_ZeroMQResponder", ",", "args", "=", "[", "self", ".", "_queue", "]", ",", "name", "=", "thread_name", ")", "self", ".", "_zmq_thread", ".", "start", "(", ")" ]
Create an entity from a local path .
def from_path ( cls , path : pathlib . Path ) -> 'Entity' : if path . is_file ( ) : return File . from_path ( path ) return Directory . from_path ( path )
12,305
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L61-L70
[ "def", "_compute_adaptation", "(", "self", ",", "xyz", ",", "xyz_w", ",", "f_l", ",", "d", ")", ":", "# Transform input colors to cone responses", "rgb", "=", "self", ".", "_xyz_to_rgb", "(", "xyz", ")", "logger", ".", "debug", "(", "\"RGB: {}\"", ".", "format", "(", "rgb", ")", ")", "rgb_b", "=", "self", ".", "_xyz_to_rgb", "(", "self", ".", "_xyz_b", ")", "rgb_w", "=", "self", ".", "_xyz_to_rgb", "(", "xyz_w", ")", "rgb_w", "=", "Hunt", ".", "adjust_white_for_scc", "(", "rgb", ",", "rgb_b", ",", "rgb_w", ",", "self", ".", "_p", ")", "logger", ".", "debug", "(", "\"RGB_W: {}\"", ".", "format", "(", "rgb_w", ")", ")", "# Compute adapted tristimulus-responses", "rgb_c", "=", "self", ".", "_white_adaption", "(", "rgb", ",", "rgb_w", ",", "d", ")", "logger", ".", "debug", "(", "\"RGB_C: {}\"", ".", "format", "(", "rgb_c", ")", ")", "rgb_cw", "=", "self", ".", "_white_adaption", "(", "rgb_w", ",", "rgb_w", ",", "d", ")", "logger", ".", "debug", "(", "\"RGB_CW: {}\"", ".", "format", "(", "rgb_cw", ")", ")", "# Convert adapted tristimulus-responses to Hunt-Pointer-Estevez fundamentals", "rgb_p", "=", "self", ".", "_compute_hunt_pointer_estevez_fundamentals", "(", "rgb_c", ")", "logger", ".", "debug", "(", "\"RGB': {}\"", ".", "format", "(", "rgb_p", ")", ")", "rgb_wp", "=", "self", ".", "_compute_hunt_pointer_estevez_fundamentals", "(", "rgb_cw", ")", "logger", ".", "debug", "(", "\"RGB'_W: {}\"", ".", "format", "(", "rgb_wp", ")", ")", "# Compute post-adaptation non-linearities", "rgb_ap", "=", "self", ".", "_compute_nonlinearities", "(", "f_l", ",", "rgb_p", ")", "rgb_awp", "=", "self", ".", "_compute_nonlinearities", "(", "f_l", ",", "rgb_wp", ")", "return", "rgb_ap", ",", "rgb_awp" ]
Calculate the MD5 checksum of a file .
def _md5 ( path : pathlib . PurePath ) : hash_ = hashlib . md5 ( ) with open ( path , 'rb' ) as f : for chunk in iter ( lambda : f . read ( 4096 ) , b'' ) : hash_ . update ( chunk ) return hash_ . hexdigest ( )
12,306
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L119-L131
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Create a file entity from a file path .
def from_path ( cls , path : pathlib . Path ) -> 'File' : if not path . is_file ( ) : raise ValueError ( 'Path does not point to a file' ) return File ( path . name , path . stat ( ) . st_size , cls . _md5 ( path ) )
12,307
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L134-L144
[ "def", "should_reuse_driver", "(", "self", ",", "scope", ",", "test_passed", ",", "context", "=", "None", ")", ":", "reuse_driver", "=", "self", ".", "config", ".", "getboolean_optional", "(", "'Driver'", ",", "'reuse_driver'", ")", "reuse_driver_session", "=", "self", ".", "config", ".", "getboolean_optional", "(", "'Driver'", ",", "'reuse_driver_session'", ")", "restart_driver_after_failure", "=", "(", "self", ".", "config", ".", "getboolean_optional", "(", "'Driver'", ",", "'restart_driver_after_failure'", ")", "or", "self", ".", "config", ".", "getboolean_optional", "(", "'Driver'", ",", "'restart_driver_fail'", ")", ")", "if", "context", "and", "scope", "==", "'function'", ":", "reuse_driver", "=", "reuse_driver", "or", "(", "hasattr", "(", "context", ",", "'reuse_driver_from_tags'", ")", "and", "context", ".", "reuse_driver_from_tags", ")", "return", "(", "(", "(", "reuse_driver", "and", "scope", "==", "'function'", ")", "or", "(", "reuse_driver_session", "and", "scope", "!=", "'session'", ")", ")", "and", "(", "test_passed", "or", "not", "restart_driver_after_failure", ")", ")" ]
Create a directory entity from a directory path .
def from_path ( cls , path : pathlib . Path ) -> 'Directory' : if not path . is_dir ( ) : raise ValueError ( 'Path does not point to a directory' ) return Directory ( path . name , { entity . name : Entity . from_path ( entity ) for entity in path . iterdir ( ) } )
12,308
https://github.com/gebn/wood/blob/efc71879890dbd2f2d7a0b1a65ed22a0843139dd/wood/entities.py#L186-L197
[ "def", "_update_specs", "(", "self", ",", "instance", ",", "specs", ")", ":", "if", "specs", "is", "None", ":", "return", "# N.B. we copy the records here, otherwise the spec will be written to", "# the attached specification of this AR", "rr", "=", "{", "item", "[", "\"keyword\"", "]", ":", "item", ".", "copy", "(", ")", "for", "item", "in", "instance", ".", "getResultsRange", "(", ")", "}", "for", "spec", "in", "specs", ":", "keyword", "=", "spec", ".", "get", "(", "\"keyword\"", ")", "if", "keyword", "in", "rr", ":", "# overwrite the instance specification only, if the specific", "# analysis spec has min/max values set", "if", "all", "(", "[", "spec", ".", "get", "(", "\"min\"", ")", ",", "spec", ".", "get", "(", "\"max\"", ")", "]", ")", ":", "rr", "[", "keyword", "]", ".", "update", "(", "spec", ")", "else", ":", "rr", "[", "keyword", "]", "=", "spec", "else", ":", "rr", "[", "keyword", "]", "=", "spec", "return", "instance", ".", "setResultsRange", "(", "rr", ".", "values", "(", ")", ")" ]
The best result of the grid search . That is the result output by the non linear search that had the highest maximum figure of merit .
def best_result ( self ) : best_result = None for result in self . results : if best_result is None or result . figure_of_merit > best_result . figure_of_merit : best_result = result return best_result
12,309
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/grid_search.py#L36-L49
[ "def", "reset_flags", "(", "self", ")", ":", "self", ".", "C", "=", "None", "self", ".", "Z", "=", "None", "self", ".", "P", "=", "None", "self", ".", "S", "=", "None" ]
Produces a list of lists of floats where each list of floats represents the values in each dimension for one step of the grid search .
def make_lists ( self , grid_priors ) : return optimizer . make_lists ( len ( grid_priors ) , step_size = self . hyper_step_size , centre_steps = False )
12,310
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/grid_search.py#L147-L161
[ "def", "codon2aa", "(", "codon", ",", "trans_table", ")", ":", "return", "Seq", "(", "''", ".", "join", "(", "codon", ")", ",", "IUPAC", ".", "ambiguous_dna", ")", ".", "translate", "(", "table", "=", "trans_table", ")", "[", "0", "]" ]
Fit an analysis with a set of grid priors . The grid priors are priors associated with the model mapper of this instance that are replaced by uniform priors for each step of the grid search .
def fit ( self , analysis , grid_priors ) : grid_priors = list ( set ( grid_priors ) ) results = [ ] lists = self . make_lists ( grid_priors ) results_list = [ list ( map ( self . variable . name_for_prior , grid_priors ) ) + [ "figure_of_merit" ] ] def write_results ( ) : with open ( "{}/results" . format ( self . phase_output_path ) , "w+" ) as f : f . write ( "\n" . join ( map ( lambda ls : ", " . join ( map ( lambda value : "{:.2f}" . format ( value ) if isinstance ( value , float ) else str ( value ) , ls ) ) , results_list ) ) ) for values in lists : arguments = self . make_arguments ( values , grid_priors ) model_mapper = self . variable . mapper_from_partial_prior_arguments ( arguments ) labels = [ ] for prior in arguments . values ( ) : labels . append ( "{}_{:.2f}_{:.2f}" . format ( model_mapper . name_for_prior ( prior ) , prior . lower_limit , prior . upper_limit ) ) name_path = "{}{}/{}" . format ( self . phase_name , self . phase_tag , "_" . join ( labels ) ) optimizer_instance = self . optimizer_instance ( model_mapper , name_path ) optimizer_instance . constant = self . constant result = optimizer_instance . fit ( analysis ) results . append ( result ) results_list . append ( [ * [ prior . lower_limit for prior in arguments . values ( ) ] , result . figure_of_merit ] ) write_results ( ) return GridSearchResult ( results , lists )
12,311
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/grid_search.py#L181-L229
[ "def", "db_dict", "(", "c", ")", ":", "db_d", "=", "{", "}", "c", ".", "execute", "(", "'SELECT * FROM library_spectra'", ")", "db_d", "[", "'library_spectra'", "]", "=", "[", "list", "(", "row", ")", "for", "row", "in", "c", "]", "c", ".", "execute", "(", "'SELECT * FROM library_spectra_meta'", ")", "db_d", "[", "'library_spectra_meta'", "]", "=", "[", "list", "(", "row", ")", "for", "row", "in", "c", "]", "c", ".", "execute", "(", "'SELECT * FROM library_spectra_annotation'", ")", "db_d", "[", "'library_spectra_annotations'", "]", "=", "[", "list", "(", "row", ")", "for", "row", "in", "c", "]", "c", ".", "execute", "(", "'SELECT * FROM library_spectra_source'", ")", "db_d", "[", "'library_spectra_source'", "]", "=", "[", "list", "(", "row", ")", "for", "row", "in", "c", "]", "c", ".", "execute", "(", "'SELECT * FROM metab_compound'", ")", "db_d", "[", "'metab_compound'", "]", "=", "[", "list", "(", "row", ")", "for", "row", "in", "c", "]", "return", "db_d" ]
Check if majority of children is connected to same port if it is the case reduce children and connect this port instead children
def portTryReduce ( root : LNode , port : LPort ) : if not port . children : return for p in port . children : portTryReduce ( root , p ) target_nodes = { } ch_cnt = countDirectlyConnected ( port , target_nodes ) if not target_nodes : # disconnected port return new_target , children_edge_to_destroy = max ( target_nodes . items ( ) , key = lambda x : len ( x [ 1 ] ) ) cnt = len ( children_edge_to_destroy ) if cnt < ch_cnt / 2 or cnt == 1 and ch_cnt == 2 : # too small to few shared connection to reduce return children_to_destroy = set ( ) on_target_children_to_destroy = set ( ) for child , edge in children_edge_to_destroy : if child . direction == PortType . OUTPUT : target_ch = edge . dsts elif child . direction == PortType . INPUT : target_ch = edge . srcs else : raise ValueError ( child . direction ) if len ( target_ch ) != 1 : raise NotImplementedError ( "multiple connected nodes" , target_ch ) target_ch = target_ch [ 0 ] try : assert target_ch . parent is new_target , ( target_ch , target_ch . parent , new_target ) except AssertionError : print ( 'Wrong target:\n' , edge . src , "\n" , edge . dst , "\n" , target_ch . parent , "\n" , new_target ) raise if child . direction == PortType . OUTPUT : edge . removeTarget ( target_ch ) elif child . direction == PortType . INPUT : edge . removeTarget ( child ) if not edge . srcs or not edge . dsts : edge . remove ( ) if not target_ch . incomingEdges and not target_ch . outgoingEdges : # disconnect selected children from this port and target on_target_children_to_destroy . add ( target_ch ) if not child . incomingEdges and not child . outgoingEdges : children_to_destroy . add ( child ) # destroy children of new target and this port if possible port . children = [ ch for ch in port . children if ch not in children_to_destroy ] new_target . children = [ ch for ch in new_target . children if ch not in on_target_children_to_destroy ] # connect this port to new target as it was connected by children before # [TODO] names for new edges if port . direction == PortType . OUTPUT : root . addEdge ( port , new_target ) elif port . direction == PortType . INPUT : root . addEdge ( new_target , port ) else : raise NotImplementedError ( port . direction )
12,312
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/resolveSharedConnections.py#L6-L84
[ "def", "show_formats", "(", ")", ":", "fmts", "=", "{", "\"ann\"", ":", "\"Kvis annotation\"", ",", "\"reg\"", ":", "\"DS9 regions file\"", ",", "\"fits\"", ":", "\"FITS Binary Table\"", ",", "\"csv\"", ":", "\"Comma separated values\"", ",", "\"tab\"", ":", "\"tabe separated values\"", ",", "\"tex\"", ":", "\"LaTeX table format\"", ",", "\"html\"", ":", "\"HTML table\"", ",", "\"vot\"", ":", "\"VO-Table\"", ",", "\"xml\"", ":", "\"VO-Table\"", ",", "\"db\"", ":", "\"Sqlite3 database\"", ",", "\"sqlite\"", ":", "\"Sqlite3 database\"", "}", "supported", "=", "get_table_formats", "(", ")", "print", "(", "\"Extension | Description | Supported?\"", ")", "for", "k", "in", "sorted", "(", "fmts", ".", "keys", "(", ")", ")", ":", "print", "(", "\"{0:10s} {1:24s} {2}\"", ".", "format", "(", "k", ",", "fmts", "[", "k", "]", ",", "k", "in", "supported", ")", ")", "return" ]
Walk all ports on all nodes and group subinterface connections to only parent interface connection if it is possible
def resolveSharedConnections ( root : LNode ) : for ch in root . children : resolveSharedConnections ( ch ) for ch in root . children : for p in ch . iterPorts ( ) : portTryReduce ( root , p )
12,313
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/resolveSharedConnections.py#L87-L97
[ "def", "archive", "(", "base_dir", ":", "str", ")", "->", "int", ":", "LOGGER", ".", "debug", "(", "'archive >>> base_dir: %s'", ",", "base_dir", ")", "rv", "=", "int", "(", "time", "(", ")", ")", "timestamp_dir", "=", "join", "(", "base_dir", ",", "str", "(", "rv", ")", ")", "makedirs", "(", "timestamp_dir", ",", "exist_ok", "=", "True", ")", "with", "SCHEMA_CACHE", ".", "lock", ":", "with", "open", "(", "join", "(", "timestamp_dir", ",", "'schema'", ")", ",", "'w'", ")", "as", "archive", ":", "print", "(", "json", ".", "dumps", "(", "SCHEMA_CACHE", ".", "schemata", "(", ")", ")", ",", "file", "=", "archive", ")", "with", "CRED_DEF_CACHE", ".", "lock", ":", "with", "open", "(", "join", "(", "timestamp_dir", ",", "'cred_def'", ")", ",", "'w'", ")", "as", "archive", ":", "print", "(", "json", ".", "dumps", "(", "CRED_DEF_CACHE", ")", ",", "file", "=", "archive", ")", "with", "REVO_CACHE", ".", "lock", ":", "with", "open", "(", "join", "(", "timestamp_dir", ",", "'revocation'", ")", ",", "'w'", ")", "as", "archive", ":", "revo_cache_dict", "=", "{", "}", "for", "rr_id", "in", "REVO_CACHE", ":", "revo_cache_dict", "[", "rr_id", "]", "=", "{", "'rev_reg_def'", ":", "REVO_CACHE", "[", "rr_id", "]", ".", "rev_reg_def", ",", "'rr_delta_frames'", ":", "[", "vars", "(", "f", ")", "for", "f", "in", "REVO_CACHE", "[", "rr_id", "]", ".", "rr_delta_frames", "]", ",", "'rr_state_frames'", ":", "[", "vars", "(", "f", ")", "for", "f", "in", "REVO_CACHE", "[", "rr_id", "]", ".", "rr_state_frames", "]", "}", "print", "(", "json", ".", "dumps", "(", "revo_cache_dict", ")", ",", "file", "=", "archive", ")", "LOGGER", ".", "debug", "(", "'archive <<< %s'", ",", "rv", ")", "return", "rv" ]
Count how many ports are directly connected to other nodes
def countDirectlyConnected ( port : LPort , result : dict ) -> int : inEdges = port . incomingEdges outEdges = port . outgoingEdges if port . children : ch_cnt = 0 # try: # assert not inEdges, (port, port.children, inEdges) # assert not outEdges, (port, port.children, outEdges) # except AssertionError: # raise for ch in port . children : ch_cnt += countDirectlyConnected ( ch , result ) return ch_cnt elif not inEdges and not outEdges : # this port is not connected, just check if it expected state if port . direction == PortType . INPUT : if port . originObj is not None : assert not port . originObj . src . drivers , port . originObj else : print ( "Warning" , port , "not connected" ) return 0 else : connectedElemCnt = 0 for e in inEdges : connectedElemCnt += len ( e . srcs ) if connectedElemCnt > 1 : return 0 for e in outEdges : connectedElemCnt += len ( e . dsts ) if connectedElemCnt > 1 : return 0 if connectedElemCnt != 1 : return 0 if inEdges : e = inEdges [ 0 ] else : e = outEdges [ 0 ] # if is connected to different port if e . srcs [ 0 ] . name != e . dsts [ 0 ] . name : return 0 if e . srcs [ 0 ] is port : p = e . dsts [ 0 ] . parent else : # (can be hyperedge and then this does not have to be) # assert e.dsts[0] is port, (e, port) p = e . srcs [ 0 ] . parent # if is part of interface which can be reduced if not isinstance ( p , LNode ) : connections = result . get ( p , [ ] ) connections . append ( ( port , e ) ) result [ p ] = connections return 1
12,314
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/fromHwt/resolveSharedConnections.py#L110-L176
[ "def", "_get_request_param", "(", "self", ",", "request", ")", ":", "params", "=", "{", "}", "try", ":", "params", "=", "request", ".", "POST", ".", "copy", "(", ")", "if", "not", "params", ":", "params", "=", "json", ".", "loads", "(", "request", ".", "body", ")", "except", "Exception", ":", "pass", "for", "key", "in", "params", ":", "# replace a value to a masked characters", "if", "key", "in", "self", ".", "mask_fields", ":", "params", "[", "key", "]", "=", "'*'", "*", "8", "# when a file uploaded (E.g create image)", "files", "=", "request", ".", "FILES", ".", "values", "(", ")", "if", "list", "(", "files", ")", ":", "filenames", "=", "', '", ".", "join", "(", "[", "up_file", ".", "name", "for", "up_file", "in", "files", "]", ")", "params", "[", "'file_name'", "]", "=", "filenames", "try", ":", "return", "json", ".", "dumps", "(", "params", ",", "ensure_ascii", "=", "False", ")", "except", "Exception", ":", "return", "'Unserializable Object'" ]
Create the node .
def deploy ( self , image_name , ip , flavor = 'm1.small' ) : body_value = { "port" : { "admin_state_up" : True , "name" : self . name + '_provision' , "network_id" : os_utils . get_network_id ( self . nova_api , 'provision_bob' ) , 'fixed_ips' : [ { 'ip_address' : ip } ] } } response = self . neutron . create_port ( body = body_value ) self . _provision_port_id = response [ 'port' ] [ 'id' ] self . mac = response [ 'port' ] [ 'mac_address' ] image_id_to_boot_from = os_utils . get_image_id ( self . nova_api , image_name ) flavor_id = os_utils . get_flavor_id ( self . nova_api , flavor ) # TODO(Gonéri): We don't need keypair for the BM nodes keypair_id = os_utils . get_keypair_id ( self . nova_api , self . _keypair ) # Ensure with get DHCP lease on the provision network first nics = [ { 'port-id' : self . _provision_port_id } ] self . _os_instance = os_provisioner . build_openstack_instance ( self . nova_api , self . name , image_id_to_boot_from , flavor_id , keypair_id , nics ) if not self . _os_instance : LOG . error ( "deployment has failed" ) raise Exception ( ) os_provisioner . add_provision_security_group ( self . nova_api ) os_utils . add_security_groups ( self . _os_instance , [ 'provision' ] ) os_utils . add_security_groups ( self . _os_instance , self . _security_groups ) LOG . info ( "add security groups '%s'" % self . _security_groups ) LOG . info ( "instance '%s' ready to use" % self . name ) # the instance should be off for Ironic self . _os_instance . stop ( )
12,315
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/ovb_baremetal.py#L47-L88
[ "def", "compose", "(", "list_of_files", ",", "destination_file", ",", "files_metadata", "=", "None", ",", "content_type", "=", "None", ",", "retry_params", "=", "None", ",", "_account_id", "=", "None", ")", ":", "api", "=", "storage_api", ".", "_get_storage_api", "(", "retry_params", "=", "retry_params", ",", "account_id", "=", "_account_id", ")", "if", "os", ".", "getenv", "(", "'SERVER_SOFTWARE'", ")", ".", "startswith", "(", "'Dev'", ")", ":", "def", "_temp_func", "(", "file_list", ",", "destination_file", ",", "content_type", ")", ":", "bucket", "=", "'/'", "+", "destination_file", ".", "split", "(", "'/'", ")", "[", "1", "]", "+", "'/'", "with", "open", "(", "destination_file", ",", "'w'", ",", "content_type", "=", "content_type", ")", "as", "gcs_merge", ":", "for", "source_file", "in", "file_list", ":", "with", "open", "(", "bucket", "+", "source_file", "[", "'Name'", "]", ",", "'r'", ")", "as", "gcs_source", ":", "gcs_merge", ".", "write", "(", "gcs_source", ".", "read", "(", ")", ")", "compose_object", "=", "_temp_func", "else", ":", "compose_object", "=", "api", ".", "compose_object", "file_list", ",", "_", "=", "_validate_compose_list", "(", "destination_file", ",", "list_of_files", ",", "files_metadata", ",", "32", ")", "compose_object", "(", "file_list", ",", "destination_file", ",", "content_type", ")" ]
Specify which file ipxe should load during the netboot .
def pxe_netboot ( self , filename ) : new_port = { 'extra_dhcp_opts' : [ { 'opt_name' : 'bootfile-name' , 'opt_value' : 'http://192.0.2.240:8088/' + filename , 'ip_version' : 4 , } , { 'opt_name' : 'tftp-server' , 'opt_value' : '192.0.2.240' , 'ip_version' : '4' } , { 'opt_name' : 'server-ip-address' , 'opt_value' : '192.0.2.240' , 'ip_version' : '4' } ] } self . neutron . update_port ( self . _provision_port_id , { 'port' : new_port } )
12,316
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/ovb_baremetal.py#L94-L103
[ "def", "get_backreferences", "(", "context", ",", "relationship", "=", "None", ",", "as_brains", "=", "None", ")", ":", "instance", "=", "context", ".", "aq_base", "raw_backrefs", "=", "get_storage", "(", "instance", ")", "if", "not", "relationship", ":", "assert", "not", "as_brains", ",", "\"You cannot use as_brains with no relationship\"", "return", "raw_backrefs", "backrefs", "=", "list", "(", "raw_backrefs", ".", "get", "(", "relationship", ",", "[", "]", ")", ")", "if", "not", "backrefs", ":", "return", "[", "]", "if", "not", "as_brains", ":", "return", "backrefs", "cat", "=", "_get_catalog_for_uid", "(", "backrefs", "[", "0", "]", ")", "return", "cat", "(", "UID", "=", "backrefs", ")" ]
Populate the node poll .
def initialize ( self , size = 2 ) : # The IP should be in this range, this is the default DHCP range used by the introspection. # inspection_iprange = 192.0.2.100,192.0.2.120 for i in range ( 0 , size ) : self . nodes . append ( Baremetal ( self . nova_api , self . neutron , self . _keypair , self . _key_filename , self . _security_groups , name = 'baremetal_%d' % i ) ) with concurrent . futures . ThreadPoolExecutor ( max_workers = 5 ) as executor : for bm_node in self . nodes : future = executor . submit ( bm_node . deploy , 'ipxe.usb' , '192.0.2.%d' % self . _idx , flavor = 'm1.large' ) self . _idx += 1 bm_node . _future = future for bm_node in self . nodes : bm_node . _future . result ( ) pm_addr = self . bmc . register_host ( bm_node . name ) self . instackenv . append ( { "pm_type" : "pxe_ipmitool" , "mac" : [ bm_node . mac ] , # TODO(Gonéri): We should get these informations from the baremetal node's flavor "cpu" : "4" , "memory" : "8196" , "disk" : "80" , "arch" : "x86_64" , "pm_user" : "admin" , "pm_password" : "password" , "pm_addr" : pm_addr } ) self . bmc . ssh_pool . stop_all ( )
12,317
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/ovb_baremetal.py#L141-L181
[ "def", "create_doc_jar", "(", "self", ",", "target", ",", "open_jar", ",", "version", ")", ":", "javadoc", "=", "self", ".", "_java_doc", "(", "target", ")", "scaladoc", "=", "self", ".", "_scala_doc", "(", "target", ")", "if", "javadoc", "or", "scaladoc", ":", "jar_path", "=", "self", ".", "artifact_path", "(", "open_jar", ",", "version", ",", "suffix", "=", "'-javadoc'", ")", "with", "self", ".", "open_jar", "(", "jar_path", ",", "overwrite", "=", "True", ",", "compressed", "=", "True", ")", "as", "open_jar", ":", "def", "add_docs", "(", "docs", ")", ":", "if", "docs", ":", "for", "basedir", ",", "doc_files", "in", "docs", ".", "items", "(", ")", ":", "for", "doc_file", "in", "doc_files", ":", "open_jar", ".", "write", "(", "os", ".", "path", ".", "join", "(", "basedir", ",", "doc_file", ")", ",", "doc_file", ")", "add_docs", "(", "javadoc", ")", "add_docs", "(", "scaladoc", ")", "return", "jar_path", "else", ":", "return", "None" ]
Deploy the BMC machine .
def create_bmc ( self , os_username , os_password , os_project_id , os_auth_url ) : bmc = ovb_bmc . OvbBmc ( nova_api = self . nova_api , neutron = self . neutron , keypair = self . _keypair , key_filename = self . _key_filename , security_groups = self . _security_groups , image_name = 'Fedora 23 x86_64' , ip = '192.0.2.254' , os_username = os_username , os_password = os_password , os_project_id = os_project_id , os_auth_url = os_auth_url ) return bmc
12,318
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/ovb_baremetal.py#L213-L231
[ "def", "diff_files", "(", "from_file", ",", "to_file", ",", "index_columns", ",", "sep", "=", "','", ",", "ignored_columns", "=", "None", ")", ":", "with", "open", "(", "from_file", ")", "as", "from_stream", ":", "with", "open", "(", "to_file", ")", "as", "to_stream", ":", "from_records", "=", "records", ".", "load", "(", "from_stream", ",", "sep", "=", "sep", ")", "to_records", "=", "records", ".", "load", "(", "to_stream", ",", "sep", "=", "sep", ")", "return", "patch", ".", "create", "(", "from_records", ",", "to_records", ",", "index_columns", ",", "ignore_columns", "=", "ignored_columns", ")" ]
Parse a UNTL XML file object into a pyuntl element tree .
def untlxml2py ( untl_filename ) : # Create a stack to hold parents. parent_stack = [ ] # Use iterparse to open the file and loop through elements. for event , element in iterparse ( untl_filename , events = ( 'start' , 'end' ) ) : if NAMESPACE_REGEX . search ( element . tag , 0 ) : element_tag = NAMESPACE_REGEX . search ( element . tag , 0 ) . group ( 1 ) else : element_tag = element . tag # Process the element if it exists in UNTL. if element_tag in PYUNTL_DISPATCH : # If it is the element's opening tag, # add it to the parent stack. if event == 'start' : parent_stack . append ( PYUNTL_DISPATCH [ element_tag ] ( ) ) # If it is the element's closing tag, # remove element from stack. Add qualifier and content. elif event == 'end' : child = parent_stack . pop ( ) if element . text is not None : content = element . text . strip ( ) if content != '' : child . set_content ( element . text ) if element . get ( 'qualifier' , False ) : child . set_qualifier ( element . get ( 'qualifier' ) ) # Add the element to its parent. if len ( parent_stack ) > 0 : parent_stack [ - 1 ] . add_child ( child ) # If it doesn't have a parent, it is the root element, # so return it. else : return child else : raise PyuntlException ( 'Element "%s" not in UNTL dispatch.' % ( element_tag ) )
12,319
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L45-L87
[ "def", "register_simulants", "(", "self", ",", "simulants", ":", "pd", ".", "DataFrame", ")", ":", "if", "not", "all", "(", "k", "in", "simulants", ".", "columns", "for", "k", "in", "self", ".", "_key_columns", ")", ":", "raise", "RandomnessError", "(", "\"The simulants dataframe does not have all specified key_columns.\"", ")", "self", ".", "_key_mapping", ".", "update", "(", "simulants", ".", "set_index", "(", "self", ".", "_key_columns", ")", ".", "index", ")" ]
Convert a UNTL dictionary into a Python object .
def untldict2py ( untl_dict ) : # Create the root element. untl_root = PYUNTL_DISPATCH [ 'metadata' ] ( ) untl_py_list = [ ] for element_name , element_list in untl_dict . items ( ) : # Loop through the element dictionaries in the element list. for element_dict in element_list : qualifier = element_dict . get ( 'qualifier' , None ) content = element_dict . get ( 'content' , None ) child_list = [ ] # Handle content that is children elements. if isinstance ( content , dict ) : for key , value in content . items ( ) : child_list . append ( PYUNTL_DISPATCH [ key ] ( content = value ) , ) # Create the UNTL element that will have children elements # added to it. if qualifier is not None : untl_element = PYUNTL_DISPATCH [ element_name ] ( qualifier = qualifier ) else : untl_element = PYUNTL_DISPATCH [ element_name ] ( ) # Add the element's children to the element. for child in child_list : untl_element . add_child ( child ) # If not child element, create the element and # add qualifier and content as available. elif content is not None and qualifier is not None : untl_element = PYUNTL_DISPATCH [ element_name ] ( qualifier = qualifier , content = content , ) elif qualifier is not None : untl_element = PYUNTL_DISPATCH [ element_name ] ( qualifier = qualifier , ) elif content is not None : untl_element = PYUNTL_DISPATCH [ element_name ] ( content = content , ) # Create element that only has children. elif len ( child_list ) > 0 : untl_element = PYUNTL_DISPATCH [ element_name ] ( ) # Add the UNTL element to the Python element list. untl_py_list . append ( untl_element ) # Add the UNTL elements to the root element. for untl_element in untl_py_list : untl_root . add_child ( untl_element ) return untl_root
12,320
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L121-L172
[ "def", "_wait_for_save", "(", "nb_name", ",", "timeout", "=", "5", ")", ":", "modification_time", "=", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "time", ".", "time", "(", ")", "<", "start_time", "+", "timeout", ":", "if", "(", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", ">", "modification_time", "and", "os", ".", "path", ".", "getsize", "(", "nb_name", ")", ">", "0", ")", ":", "return", "True", "time", ".", "sleep", "(", "0.2", ")", "return", "False" ]
Convert the UNTL posted data to a Python dictionary .
def post2pydict ( post , ignore_list ) : root_element = PYUNTL_DISPATCH [ 'metadata' ] ( ) untl_form_dict = { } # Turn the posted data into usable data # (otherwise the value lists get messed up). form_post = dict ( post . copy ( ) ) # Loop through all the field lists. for key , value_list in form_post . items ( ) : if key not in ignore_list : # Split the key into the element_tag (ex. title) # and element attribute (ex. qualifier, content). ( element_tag , element_attribute ) = key . split ( '-' , 1 ) if element_tag not in untl_form_dict : untl_form_dict [ element_tag ] = ( ) # Add the value list to the dictionary. untl_form_dict [ element_tag ] += ( element_attribute , value_list ) , for element_tag , attribute_tuple in untl_form_dict . items ( ) : # Get the count of attributes/content in the element tuple. attribute_count = len ( attribute_tuple ) # Get the count of the first attribute's values. value_count = len ( attribute_tuple [ 0 ] [ 1 ] ) # Check to see that all attribute/content values align numerically. for i in range ( 0 , attribute_count ) : if not len ( attribute_tuple [ i ] [ 1 ] ) == value_count : raise PyuntlException ( 'Field values did not match up ' 'numerically for %s' % ( element_tag ) ) # Create a value loop to get all values from the tuple. for i in range ( 0 , value_count ) : untl_element = None content = '' qualifier = '' child_list = [ ] # Loop through the attributes. # attribute_tuple[j][0] represents the attribute/content name. # attribute_tuple[j][1][i] represents the # current attribute/content value. for j in range ( 0 , attribute_count ) : if attribute_tuple [ j ] [ 0 ] == 'content' : content = unicode ( attribute_tuple [ j ] [ 1 ] [ i ] ) elif attribute_tuple [ j ] [ 0 ] == 'qualifier' : qualifier = attribute_tuple [ j ] [ 1 ] [ i ] # Create a child UNTL element from the data. else : # If the child has content, append it to the child list. if attribute_tuple [ j ] [ 1 ] [ i ] != '' : child_tag = attribute_tuple [ j ] [ 0 ] # Check if the child is the attribute of the element. if child_tag in PARENT_FORM : qualifier = attribute_tuple [ j ] [ 1 ] [ i ] # Else, the child is a normal child of the element. else : child_list . append ( PYUNTL_DISPATCH [ attribute_tuple [ j ] [ 0 ] ] ( content = attribute_tuple [ j ] [ 1 ] [ i ] ) ) # Create the UNTL element. if content != '' and qualifier != '' : untl_element = PYUNTL_DISPATCH [ element_tag ] ( content = content , qualifier = qualifier ) elif content != '' : untl_element = PYUNTL_DISPATCH [ element_tag ] ( content = content ) elif qualifier != '' : untl_element = PYUNTL_DISPATCH [ element_tag ] ( qualifier = qualifier ) # This element only has children elements. elif len ( child_list ) > 0 : untl_element = PYUNTL_DISPATCH [ element_tag ] ( ) # If the element has children, add them. if len ( child_list ) > 0 and untl_element is not None : for child in child_list : untl_element . add_child ( child ) # Add the UNTL element to the root element. if untl_element is not None : root_element . add_child ( untl_element ) return root_element . create_element_dict ( )
12,321
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L175-L251
[ "def", "write_bits", "(", "self", ",", "*", "args", ")", ":", "# Would be nice to make this a bit smarter", "if", "len", "(", "args", ")", ">", "8", ":", "raise", "ValueError", "(", "\"Can only write 8 bits at a time\"", ")", "self", ".", "_output_buffer", ".", "append", "(", "chr", "(", "reduce", "(", "lambda", "x", ",", "y", ":", "xor", "(", "x", ",", "args", "[", "y", "]", "<<", "y", ")", ",", "xrange", "(", "len", "(", "args", ")", ")", ",", "0", ")", ")", ")", "return", "self" ]
Convert the UNTL elements structure into a DC structure .
def untlpy2dcpy ( untl_elements , * * kwargs ) : sDate = None eDate = None ark = kwargs . get ( 'ark' , None ) domain_name = kwargs . get ( 'domain_name' , None ) scheme = kwargs . get ( 'scheme' , 'http' ) resolve_values = kwargs . get ( 'resolve_values' , None ) resolve_urls = kwargs . get ( 'resolve_urls' , None ) verbose_vocabularies = kwargs . get ( 'verbose_vocabularies' , None ) # If either resolvers were requested, get the vocabulary data. if resolve_values or resolve_urls : if verbose_vocabularies : # If the vocabularies were passed to the function, use them. vocab_data = verbose_vocabularies else : # Otherwise, retrieve them using the pyuntl method. vocab_data = retrieve_vocab ( ) else : vocab_data = None # Create the DC parent element. dc_root = DC_CONVERSION_DISPATCH [ 'dc' ] ( ) for element in untl_elements . children : # Check if the UNTL element should be converted to DC. if element . tag in DC_CONVERSION_DISPATCH : # Check if the element has its content stored in children nodes. if element . children : dc_element = DC_CONVERSION_DISPATCH [ element . tag ] ( qualifier = element . qualifier , children = element . children , resolve_values = resolve_values , resolve_urls = resolve_urls , vocab_data = vocab_data , ) # It is a normal element. else : dc_element = DC_CONVERSION_DISPATCH [ element . tag ] ( qualifier = element . qualifier , content = element . content , resolve_values = resolve_values , resolve_urls = resolve_urls , vocab_data = vocab_data , ) if element . tag == 'coverage' : # Handle start and end dates. if element . qualifier == 'sDate' : sDate = dc_element elif element . qualifier == 'eDate' : eDate = dc_element # Otherwise, add the coverage element to the structure. else : dc_root . add_child ( dc_element ) # Add non coverage DC element to the structure. elif dc_element : dc_root . add_child ( dc_element ) # If the domain and ark were specified # try to turn them into indentifier elements. if ark and domain_name : # Create and add the permalink identifier. permalink_identifier = DC_CONVERSION_DISPATCH [ 'identifier' ] ( qualifier = 'permalink' , domain_name = domain_name , ark = ark , scheme = scheme ) dc_root . add_child ( permalink_identifier ) # Create and add the ark identifier. ark_identifier = DC_CONVERSION_DISPATCH [ 'identifier' ] ( qualifier = 'ark' , content = ark , ) dc_root . add_child ( ark_identifier ) if sDate and eDate : # If a start and end date exist, combine them into one element. dc_element = DC_CONVERSION_DISPATCH [ 'coverage' ] ( content = '%s-%s' % ( sDate . content , eDate . content ) , ) dc_root . add_child ( dc_element ) elif sDate : dc_root . add_child ( sDate ) elif eDate : dc_root . add_child ( eDate ) return dc_root
12,322
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L254-L372
[ "def", "_wait_for_save", "(", "nb_name", ",", "timeout", "=", "5", ")", ":", "modification_time", "=", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "time", ".", "time", "(", ")", "<", "start_time", "+", "timeout", ":", "if", "(", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", ">", "modification_time", "and", "os", ".", "path", ".", "getsize", "(", "nb_name", ")", ">", "0", ")", ":", "return", "True", "time", ".", "sleep", "(", "0.2", ")", "return", "False" ]
Convert a UNTL Python object to a highwire Python object .
def untlpy2highwirepy ( untl_elements , * * kwargs ) : highwire_list = [ ] title = None publisher = None creation = None escape = kwargs . get ( 'escape' , False ) for element in untl_elements . children : # If the UNTL element should be converted to highwire, # create highwire element. if element . tag in HIGHWIRE_CONVERSION_DISPATCH : highwire_element = HIGHWIRE_CONVERSION_DISPATCH [ element . tag ] ( qualifier = element . qualifier , content = element . content , children = element . children , escape = escape , ) if highwire_element : if element . tag == 'title' : if element . qualifier != 'officialtitle' and not title : title = highwire_element elif element . qualifier == 'officialtitle' : title = highwire_element elif element . tag == 'publisher' : if not publisher : # This is the first publisher element. publisher = highwire_element highwire_list . append ( publisher ) elif element . tag == 'date' : # If a creation date hasn't been found yet, # verify this date is acceptable. if not creation and element . qualifier == 'creation' : if highwire_element . content : creation = highwire_element if creation : highwire_list . append ( creation ) # Otherwise, add the element to the list if it has content. elif highwire_element . content : highwire_list . append ( highwire_element ) # If the title was found, add it to the list. if title : highwire_list . append ( title ) return highwire_list
12,323
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L375-L417
[ "def", "_wait_for_save", "(", "nb_name", ",", "timeout", "=", "5", ")", ":", "modification_time", "=", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "time", ".", "time", "(", ")", "<", "start_time", "+", "timeout", ":", "if", "(", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", ">", "modification_time", "and", "os", ".", "path", ".", "getsize", "(", "nb_name", ")", ">", "0", ")", ":", "return", "True", "time", ".", "sleep", "(", "0.2", ")", "return", "False" ]
Convert a UNTL data dictionary to a formatted DC data dictionary .
def untlpydict2dcformatteddict ( untl_dict , * * kwargs ) : ark = kwargs . get ( 'ark' , None ) domain_name = kwargs . get ( 'domain_name' , None ) scheme = kwargs . get ( 'scheme' , 'http' ) resolve_values = kwargs . get ( 'resolve_values' , None ) resolve_urls = kwargs . get ( 'resolve_urls' , None ) verbose_vocabularies = kwargs . get ( 'verbose_vocabularies' , None ) # Get the UNTL object. untl_py = untldict2py ( untl_dict ) # Convert it to a DC object. dc_py = untlpy2dcpy ( untl_py , ark = ark , domain_name = domain_name , resolve_values = resolve_values , resolve_urls = resolve_urls , verbose_vocabularies = verbose_vocabularies , scheme = scheme ) # Return a formatted DC dictionary. return dcpy2formatteddcdict ( dc_py )
12,324
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L420-L441
[ "def", "_wait_for_save", "(", "nb_name", ",", "timeout", "=", "5", ")", ":", "modification_time", "=", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "time", ".", "time", "(", ")", "<", "start_time", "+", "timeout", ":", "if", "(", "os", ".", "path", ".", "getmtime", "(", "nb_name", ")", ">", "modification_time", "and", "os", ".", "path", ".", "getsize", "(", "nb_name", ")", ">", "0", ")", ":", "return", "True", "time", ".", "sleep", "(", "0.2", ")", "return", "False" ]
Change the formatting of the DC data dictionary .
def formatted_dc_dict ( dc_dict ) : for key , element_list in dc_dict . items ( ) : new_element_list = [ ] # Add the content for each element to the new element list. for element in element_list : new_element_list . append ( element [ 'content' ] ) dc_dict [ key ] = new_element_list return dc_dict
12,325
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L457-L470
[ "def", "_notify_remove", "(", "self", ",", "slice_", ")", ":", "change", "=", "RemoveChange", "(", "self", ",", "slice_", ")", "self", ".", "notify_observers", "(", "change", ")" ]
Generate a DC XML string .
def generate_dc_xml ( dc_dict ) : # Define the root namespace. root_namespace = '{%s}' % DC_NAMESPACES [ 'oai_dc' ] # Set the elements namespace URL. elements_namespace = '{%s}' % DC_NAMESPACES [ 'dc' ] schema_location = ( 'http://www.openarchives.org/OAI/2.0/oai_dc/ ' 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd' ) root_attributes = { '{%s}schemaLocation' % XSI : schema_location , } # Return the DC XML string. return pydict2xmlstring ( dc_dict , ordering = DC_ORDER , root_label = 'dc' , root_namespace = root_namespace , elements_namespace = elements_namespace , namespace_map = DC_NAMESPACES , root_attributes = root_attributes , )
12,326
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L473-L493
[ "def", "find_best_frametype", "(", "channel", ",", "start", ",", "end", ",", "frametype_match", "=", "None", ",", "allow_tape", "=", "True", ",", "connection", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "try", ":", "return", "find_frametype", "(", "channel", ",", "gpstime", "=", "(", "start", ",", "end", ")", ",", "frametype_match", "=", "frametype_match", ",", "allow_tape", "=", "allow_tape", ",", "on_gaps", "=", "'error'", ",", "connection", "=", "connection", ",", "host", "=", "host", ",", "port", "=", "port", ")", "except", "RuntimeError", ":", "# gaps (or something else went wrong)", "ftout", "=", "find_frametype", "(", "channel", ",", "gpstime", "=", "(", "start", ",", "end", ")", ",", "frametype_match", "=", "frametype_match", ",", "return_all", "=", "True", ",", "allow_tape", "=", "allow_tape", ",", "on_gaps", "=", "'ignore'", ",", "connection", "=", "connection", ",", "host", "=", "host", ",", "port", "=", "port", ")", "try", ":", "if", "isinstance", "(", "ftout", ",", "dict", ")", ":", "return", "{", "key", ":", "ftout", "[", "key", "]", "[", "0", "]", "for", "key", "in", "ftout", "}", "return", "ftout", "[", "0", "]", "except", "IndexError", ":", "raise", "ValueError", "(", "\"Cannot find any valid frametypes for channel(s)\"", ")" ]
Generate DC JSON data .
def generate_dc_json ( dc_dict ) : formatted_dict = formatted_dc_dict ( dc_dict ) return json . dumps ( formatted_dict , sort_keys = True , indent = 4 )
12,327
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L496-L502
[ "def", "remover", "(", "self", ",", "id_perms", ")", ":", "if", "not", "is_valid_int_param", "(", "id_perms", ")", ":", "raise", "InvalidParameterError", "(", "u'The identifier of Administrative Permission is invalid or was not informed.'", ")", "url", "=", "'aperms/'", "+", "str", "(", "id_perms", ")", "+", "'/'", "code", ",", "xml", "=", "self", ".", "submit", "(", "None", ",", "'DELETE'", ",", "url", ")", "return", "self", ".", "response", "(", "code", ",", "xml", ")" ]
Convert a list of highwire elements into a dictionary .
def highwirepy2dict ( highwire_elements ) : highwire_dict = { } # Make a list of content dictionaries for each element name. for element in highwire_elements : if element . name not in highwire_dict : highwire_dict [ element . name ] = [ ] highwire_dict [ element . name ] . append ( { 'content' : element . content } ) return highwire_dict
12,328
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L510-L522
[ "def", "_preprocess_movie_lens", "(", "ratings_df", ")", ":", "ratings_df", "[", "\"data\"", "]", "=", "1.0", "num_timestamps", "=", "ratings_df", "[", "[", "\"userId\"", ",", "\"timestamp\"", "]", "]", ".", "groupby", "(", "\"userId\"", ")", ".", "nunique", "(", ")", "last_user_timestamp", "=", "ratings_df", "[", "[", "\"userId\"", ",", "\"timestamp\"", "]", "]", ".", "groupby", "(", "\"userId\"", ")", ".", "max", "(", ")", "ratings_df", "[", "\"numberOfTimestamps\"", "]", "=", "ratings_df", "[", "\"userId\"", "]", ".", "apply", "(", "lambda", "x", ":", "num_timestamps", "[", "\"timestamp\"", "]", "[", "x", "]", ")", "ratings_df", "[", "\"lastTimestamp\"", "]", "=", "ratings_df", "[", "\"userId\"", "]", ".", "apply", "(", "lambda", "x", ":", "last_user_timestamp", "[", "\"timestamp\"", "]", "[", "x", "]", ")", "ratings_df", "=", "ratings_df", "[", "ratings_df", "[", "\"numberOfTimestamps\"", "]", ">", "2", "]", "ratings_df", "=", "_create_row_col_indices", "(", "ratings_df", ")", "train_ratings_df", "=", "ratings_df", "[", "ratings_df", "[", "\"timestamp\"", "]", "<", "ratings_df", "[", "\"lastTimestamp\"", "]", "]", "test_ratings_df", "=", "ratings_df", "[", "ratings_df", "[", "\"timestamp\"", "]", "==", "ratings_df", "[", "\"lastTimestamp\"", "]", "]", "return", "ratings_df", ",", "train_ratings_df", ",", "test_ratings_df" ]
Convert highwire elements into a JSON structure .
def generate_highwire_json ( highwire_elements ) : highwire_dict = highwirepy2dict ( highwire_elements ) return json . dumps ( highwire_dict , sort_keys = True , indent = 4 )
12,329
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L530-L536
[ "def", "client_getter", "(", ")", ":", "def", "wrapper", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'client_id'", "not", "in", "kwargs", ":", "abort", "(", "500", ")", "client", "=", "Client", ".", "query", ".", "filter_by", "(", "client_id", "=", "kwargs", ".", "pop", "(", "'client_id'", ")", ",", "user_id", "=", "current_user", ".", "get_id", "(", ")", ",", ")", ".", "first", "(", ")", "if", "client", "is", "None", ":", "abort", "(", "404", ")", "return", "f", "(", "client", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorated", "return", "wrapper" ]
Convert a DC dictionary into an RDF Python object .
def dcdict2rdfpy ( dc_dict ) : ark_prefix = 'ark: ark:' uri = URIRef ( '' ) # Create the RDF Python object. rdf_py = ConjunctiveGraph ( ) # Set DC namespace definition. DC = Namespace ( 'http://purl.org/dc/elements/1.1/' ) # Get the ark for the subject URI from the ark identifier. for element_value in dc_dict [ 'identifier' ] : if element_value [ 'content' ] . startswith ( ark_prefix ) : uri = URIRef ( element_value [ 'content' ] . replace ( ark_prefix , 'info:ark' ) ) # Bind the prefix/namespace pair. rdf_py . bind ( 'dc' , DC ) # Get the values for each element in the ordered DC elements. for element_name in DC_ORDER : element_value_list = dc_dict . get ( element_name , [ ] ) # Add the values to the RDF object. for element_value in element_value_list : # Handle URL values differently. if ( 'http' in element_value [ 'content' ] and ' ' not in element_value [ 'content' ] ) : rdf_py . add ( ( uri , DC [ element_name ] , URIRef ( element_value [ 'content' ] ) ) ) else : rdf_py . add ( ( uri , DC [ element_name ] , Literal ( element_value [ 'content' ] ) ) ) return rdf_py
12,330
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L545-L581
[ "def", "create_supercut_in_batches", "(", "composition", ",", "outputfile", ",", "padding", ")", ":", "total_clips", "=", "len", "(", "composition", ")", "start_index", "=", "0", "end_index", "=", "BATCH_SIZE", "batch_comp", "=", "[", "]", "while", "start_index", "<", "total_clips", ":", "filename", "=", "outputfile", "+", "'.tmp'", "+", "str", "(", "start_index", ")", "+", "'.mp4'", "try", ":", "create_supercut", "(", "composition", "[", "start_index", ":", "end_index", "]", ",", "filename", ",", "padding", ")", "batch_comp", ".", "append", "(", "filename", ")", "gc", ".", "collect", "(", ")", "start_index", "+=", "BATCH_SIZE", "end_index", "+=", "BATCH_SIZE", "except", ":", "start_index", "+=", "BATCH_SIZE", "end_index", "+=", "BATCH_SIZE", "next", "clips", "=", "[", "VideoFileClip", "(", "filename", ")", "for", "filename", "in", "batch_comp", "]", "video", "=", "concatenate", "(", "clips", ")", "video", ".", "to_videofile", "(", "outputfile", ",", "codec", "=", "\"libx264\"", ",", "temp_audiofile", "=", "'temp-audio.m4a'", ",", "remove_temp", "=", "True", ",", "audio_codec", "=", "'aac'", ")", "# remove partial video files", "for", "filename", "in", "batch_comp", ":", "os", ".", "remove", "(", "filename", ")", "cleanup_log_files", "(", "outputfile", ")" ]
Add empty values if UNTL fields don t have values .
def add_empty_fields ( untl_dict ) : # Iterate the ordered UNTL XML element list to determine # which elements are missing from the untl_dict. for element in UNTL_XML_ORDER : if element not in untl_dict : # Try to create an element with content and qualifier. try : py_object = PYUNTL_DISPATCH [ element ] ( content = '' , qualifier = '' , ) except : # Try to create an element with content. try : py_object = PYUNTL_DISPATCH [ element ] ( content = '' ) except : # Try to create an element without content. try : py_object = PYUNTL_DISPATCH [ element ] ( ) except : raise PyuntlException ( 'Could not add empty element field.' ) else : untl_dict [ element ] = [ { 'content' : { } } ] else : # Handle element without children. if not py_object . contained_children : untl_dict [ element ] = [ { 'content' : '' } ] else : untl_dict [ element ] = [ { 'content' : { } } ] else : # Handle element without children. if not py_object . contained_children : untl_dict [ element ] = [ { 'content' : '' , 'qualifier' : '' } ] else : untl_dict [ element ] = [ { 'content' : { } , 'qualifier' : '' } ] # Add empty contained children. for child in py_object . contained_children : untl_dict [ element ] [ 0 ] . setdefault ( 'content' , { } ) untl_dict [ element ] [ 0 ] [ 'content' ] [ child ] = '' return untl_dict
12,331
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L606-L648
[ "def", "TxKazooClient", "(", "reactor", ",", "pool", ",", "client", ")", ":", "make_thimble", "=", "partial", "(", "Thimble", ",", "reactor", ",", "pool", ")", "wrapper", "=", "_RunCallbacksInReactorThreadWrapper", "(", "reactor", ",", "client", ")", "client_thimble", "=", "make_thimble", "(", "wrapper", ",", "_blocking_client_methods", ")", "def", "_Lock", "(", "path", ",", "identifier", "=", "None", ")", ":", "\"\"\"Return a wrapped :class:`kazoo.recipe.lock.Lock` for this client.\"\"\"", "lock", "=", "client", ".", "Lock", "(", "path", ",", "identifier", ")", "return", "Thimble", "(", "reactor", ",", "pool", ",", "lock", ",", "_blocking_lock_methods", ")", "client_thimble", ".", "Lock", "=", "_Lock", "client_thimble", ".", "SetPartitioner", "=", "partial", "(", "_SetPartitionerWrapper", ",", "reactor", ",", "pool", ",", "client", ")", "# Expose these so e.g. recipes can access them from the kzclient", "client", ".", "reactor", "=", "reactor", "client", ".", "pool", "=", "pool", "client", ".", "kazoo_client", "=", "client", "return", "client_thimble" ]
Add empty values for ETD_MS fields that don t have values .
def add_empty_etd_ms_fields ( etd_ms_dict ) : # Determine which ETD MS elements are missing from the etd_ms_dict. for element in ETD_MS_ORDER : if element not in etd_ms_dict : # Try to create an element with content and qualifier. try : py_object = ETD_MS_CONVERSION_DISPATCH [ element ] ( content = '' , qualifier = '' , ) except : # Try to create an element with content. try : py_object = ETD_MS_CONVERSION_DISPATCH [ element ] ( content = '' ) except : # Try to create an element without content. try : py_object = ETD_MS_CONVERSION_DISPATCH [ element ] ( ) except : raise PyuntlException ( 'Could not add empty element field.' ) else : etd_ms_dict [ element ] = [ { 'content' : { } } ] else : # Handle element without children. if not py_object . contained_children : etd_ms_dict [ element ] = [ { 'content' : '' } ] else : etd_ms_dict [ element ] = [ { 'content' : { } } ] else : # Handle element without children. if py_object : if not py_object . contained_children : etd_ms_dict [ element ] = [ { 'content' : '' , 'qualifier' : '' } ] else : etd_ms_dict [ element ] = [ { 'content' : { } , 'qualifier' : '' } ] # Add empty contained children. if py_object : for child in py_object . contained_children : etd_ms_dict [ element ] [ 0 ] . setdefault ( 'content' , { } ) etd_ms_dict [ element ] [ 0 ] [ 'content' ] [ child ] = '' return etd_ms_dict
12,332
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L651-L696
[ "def", "unlisten_to_node", "(", "self", ",", "id_", ")", ":", "id_pubsub", "=", "_pubsub_key", "(", "id_", ")", "if", "id_pubsub", "in", "self", ".", "_listening_to", ":", "del", "self", ".", "_listening_to", "[", "id_pubsub", "]", "self", ".", "toredis", ".", "unsubscribe", "(", "id_pubsub", ")", "parent", "=", "json_decode", "(", "r_client", ".", "get", "(", "id_", ")", ")", ".", "get", "(", "'parent'", ",", "None", ")", "if", "parent", "is", "not", "None", ":", "r_client", ".", "srem", "(", "_children_key", "(", "parent", ")", ",", "id_", ")", "r_client", ".", "srem", "(", "self", ".", "group_children", ",", "id_", ")", "return", "id_" ]
Add empty required qualifiers to create valid UNTL .
def find_untl_errors ( untl_dict , * * kwargs ) : fix_errors = kwargs . get ( 'fix_errors' , False ) error_dict = { } # Loop through all elements that require qualifiers. for element_name in REQUIRES_QUALIFIER : # Loop through the existing elements that require qualifers. for element in untl_dict . get ( element_name , [ ] ) : error_dict [ element_name ] = 'no_qualifier' # If it should be fixed, set an empty qualifier # if it doesn't have one. if fix_errors : element . setdefault ( 'qualifier' , '' ) # Combine the error dict and UNTL dict into a dict. found_data = { 'untl_dict' : untl_dict , 'error_dict' : error_dict , } return found_data
12,333
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L699-L717
[ "def", "fuzzer", "(", "buffer", ",", "fuzz_factor", "=", "101", ")", ":", "buf", "=", "deepcopy", "(", "buffer", ")", "num_writes", "=", "number_of_bytes_to_modify", "(", "len", "(", "buf", ")", ",", "fuzz_factor", ")", "for", "_", "in", "range", "(", "num_writes", ")", ":", "random_byte", "=", "random", ".", "randrange", "(", "256", ")", "random_position", "=", "random", ".", "randrange", "(", "len", "(", "buf", ")", ")", "buf", "[", "random_position", "]", "=", "random_byte", "return", "buf" ]
Convert the UNTL elements structure into an ETD_MS structure .
def untlpy2etd_ms ( untl_elements , * * kwargs ) : degree_children = { } date_exists = False seen_creation = False # Make the root element. etd_ms_root = ETD_MS_CONVERSION_DISPATCH [ 'thesis' ] ( ) for element in untl_elements . children : etd_ms_element = None # Convert the UNTL element to etd_ms where applicable. if element . tag in ETD_MS_CONVERSION_DISPATCH : # Create the etd_ms_element if the element's content # is stored in children nodes. if element . children : etd_ms_element = ETD_MS_CONVERSION_DISPATCH [ element . tag ] ( qualifier = element . qualifier , children = element . children , ) # If we hit a degree element, make just that one. elif element . tag == 'degree' : # Make a dict of the degree children information. if element . qualifier in [ 'name' , 'level' , 'discipline' , 'grantor' ] : degree_children [ element . qualifier ] = element . content # For date elements, limit to first instance of creation date. elif element . tag == 'date' : if element . qualifier == 'creation' : # If the root already has a date, delete the child. for child in etd_ms_root . children : if child . tag == 'date' : del child if not seen_creation : date_exists = False seen_creation = True if not date_exists : # Create the etd_ms element. etd_ms_element = ETD_MS_CONVERSION_DISPATCH [ element . tag ] ( qualifier = element . qualifier , content = element . content , ) date_exists = True # It is a normal element. elif element . tag not in [ 'date' , 'degree' ] : # Create the etd_ms_element. etd_ms_element = ETD_MS_CONVERSION_DISPATCH [ element . tag ] ( qualifier = element . qualifier , content = element . content , ) # Add the element to the structure if the element exists. if etd_ms_element : etd_ms_root . add_child ( etd_ms_element ) if element . tag == 'meta' : # Initialize ark to False because it may not exist yet. ark = False # Iterate through children and look for ark. for i in etd_ms_root . children : if i . tag == 'identifier' and i . content . startswith ( 'http://digital.library.unt.edu/' ) : ark = True # If the ark doesn't yet exist, try and create it. if not ark : # Reset for future tests. ark = False if element . qualifier == 'ark' : ark = element . content if ark is not None : # Create the ark identifier element and add it. ark_identifier = ETD_MS_CONVERSION_DISPATCH [ 'identifier' ] ( ark = ark , ) etd_ms_root . add_child ( ark_identifier ) # If children exist for the degree, make a degree element. if degree_children : degree_element = ETD_MS_CONVERSION_DISPATCH [ 'degree' ] ( ) # When we have all the elements stored, add the children to the # degree node. degree_child_element = None for k , v in degree_children . iteritems ( ) : # Create the individual classes for degrees. degree_child_element = ETD_MS_DEGREE_DISPATCH [ k ] ( content = v , ) # If the keys in degree_children are valid, # add it to the child. if degree_child_element : degree_element . add_child ( degree_child_element ) etd_ms_root . add_child ( degree_element ) return etd_ms_root
12,334
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L720-L813
[ "def", "register_keepalive", "(", "self", ",", "cmd", ",", "callback", ")", ":", "regid", "=", "random", ".", "random", "(", ")", "if", "self", ".", "_customkeepalives", "is", "None", ":", "self", ".", "_customkeepalives", "=", "{", "regid", ":", "(", "cmd", ",", "callback", ")", "}", "else", ":", "while", "regid", "in", "self", ".", "_customkeepalives", ":", "regid", "=", "random", ".", "random", "(", ")", "self", ".", "_customkeepalives", "[", "regid", "]", "=", "(", "cmd", ",", "callback", ")", "return", "regid" ]
Create an ETD MS XML file .
def etd_ms_dict2xmlfile ( filename , metadata_dict ) : try : f = open ( filename , 'w' ) f . write ( generate_etd_ms_xml ( metadata_dict ) . encode ( "utf-8" ) ) f . close ( ) except : raise MetadataGeneratorException ( 'Failed to create an XML file. Filename: %s' % ( filename ) )
12,335
https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untldoc.py#L826-L835
[ "def", "watch_and_wait", "(", "self", ",", "poll_interval", "=", "10", ",", "idle_log_timeout", "=", "None", ",", "kill_on_timeout", "=", "False", ",", "stash_log_method", "=", "None", ",", "tag_instances", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "wait_for_complete", "(", "self", ".", "_job_queue", ",", "job_list", "=", "self", ".", "job_list", ",", "job_name_prefix", "=", "self", ".", "basename", ",", "poll_interval", "=", "poll_interval", ",", "idle_log_timeout", "=", "idle_log_timeout", ",", "kill_on_log_timeout", "=", "kill_on_timeout", ",", "stash_log_method", "=", "stash_log_method", ",", "tag_instances", "=", "tag_instances", ",", "*", "*", "kwargs", ")" ]
The signal - to - noise_map of the data and noise - map which are fitted .
def signal_to_noise_map ( self ) : signal_to_noise_map = np . divide ( self . data , self . noise_map ) signal_to_noise_map [ signal_to_noise_map < 0 ] = 0 return signal_to_noise_map
12,336
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/tools/fit.py#L59-L63
[ "async", "def", "set_version", "(", "self", ",", "tp", ",", "params", ",", "version", "=", "None", ",", "elem", "=", "None", ")", ":", "self", ".", "registry", ".", "set_tr", "(", "None", ")", "tw", "=", "TypeWrapper", "(", "tp", ",", "params", ")", "if", "not", "tw", ".", "is_versioned", "(", ")", ":", "return", "TypeWrapper", ".", "ELEMENTARY_RES", "# If not in the DB, store to the archive at the current position", "if", "not", "self", ".", "version_db", ".", "is_versioned", "(", "tw", ")", ":", "if", "version", "is", "None", ":", "version", "=", "self", ".", "_cur_version", "(", "tw", ",", "elem", ")", "await", "dump_uvarint", "(", "self", ".", "iobj", ",", "0", ")", "await", "dump_uvarint", "(", "self", ".", "iobj", ",", "version", ")", "self", ".", "version_db", ".", "set_version", "(", "tw", ",", "0", ",", "version", ")", "return", "self", ".", "version_db", ".", "get_version", "(", "tw", ")", "[", "1", "]" ]
Get the part structure as a DNA regex pattern .
def structure ( cls ) : # type: () -> Text if cls . signature is NotImplemented : raise NotImplementedError ( "no signature defined" ) up = cls . cutter . elucidate ( ) down = str ( Seq ( up ) . reverse_complement ( ) ) ovhg = cls . cutter . ovhgseq upsig , downsig = cls . signature if cls . cutter . is_5overhang ( ) : upsite = "^{}_" . format ( ovhg ) downsite = "_{}^" . format ( Seq ( ovhg ) . reverse_complement ( ) ) else : upsite = "_{}^" . format ( ovhg ) downsite = "^{}_" . format ( Seq ( ovhg ) . reverse_complement ( ) ) if issubclass ( cls , AbstractModule ) : return "" . join ( [ up . replace ( upsite , "({})(" . format ( upsig ) ) , "N*" , down . replace ( downsite , ")({})" . format ( downsig ) ) , ] ) elif issubclass ( cls , AbstractVector ) : return "" . join ( [ down . replace ( downsite , "({})(" . format ( downsig ) ) , "N*" , up . replace ( upsite , ")({})" . format ( upsig ) ) , ] ) else : raise RuntimeError ( "Part must be either a module or a vector!" )
12,337
https://github.com/althonos/moclo/blob/28a03748df8a2fa43f0c0c8098ca64d11559434e/moclo/moclo/core/parts.py#L49-L99
[ "def", "cublasGetVersion", "(", "handle", ")", ":", "version", "=", "ctypes", ".", "c_int", "(", ")", "status", "=", "_libcublas", ".", "cublasGetVersion_v2", "(", "handle", ",", "ctypes", ".", "byref", "(", "version", ")", ")", "cublasCheckStatus", "(", "status", ")", "return", "version", ".", "value" ]
Load the record in a concrete subclass of this type .
def characterize ( cls , record ) : classes = list ( cls . __subclasses__ ( ) ) if not isabstract ( cls ) : classes . append ( cls ) for subclass in classes : entity = subclass ( record ) if entity . is_valid ( ) : return entity raise RuntimeError ( "could not find the type for '{}'" . format ( record . id ) )
12,338
https://github.com/althonos/moclo/blob/28a03748df8a2fa43f0c0c8098ca64d11559434e/moclo/moclo/core/parts.py#L102-L112
[ "def", "set_guest_access", "(", "self", ",", "allow_guests", ")", ":", "guest_access", "=", "\"can_join\"", "if", "allow_guests", "else", "\"forbidden\"", "try", ":", "self", ".", "client", ".", "api", ".", "set_guest_access", "(", "self", ".", "room_id", ",", "guest_access", ")", "self", ".", "guest_access", "=", "allow_guests", "return", "True", "except", "MatrixRequestError", ":", "return", "False" ]
Make a global request to the remote host . These are normally extensions to the SSH2 protocol .
def global_request ( self , kind , data = None , wait = True ) : if wait : self . completion_event = threading . Event ( ) m = Message ( ) m . add_byte ( cMSG_GLOBAL_REQUEST ) m . add_string ( kind ) m . add_boolean ( wait ) if data is not None : m . add ( * data ) self . _log ( DEBUG , 'Sending global request "%s"' % kind ) self . _send_user_message ( m ) if not wait : return None while True : self . completion_event . wait ( 0.1 ) if not self . active : return None if self . completion_event . isSet ( ) : break return self . global_response
12,339
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/transport.py#L777-L812
[ "def", "assemble", "(", "cls", ",", "header_json", ",", "metadata_json", ",", "content_json", ")", ":", "try", ":", "header", "=", "json_decode", "(", "header_json", ")", "except", "ValueError", ":", "raise", "MessageError", "(", "\"header could not be decoded\"", ")", "try", ":", "metadata", "=", "json_decode", "(", "metadata_json", ")", "except", "ValueError", ":", "raise", "MessageError", "(", "\"metadata could not be decoded\"", ")", "try", ":", "content", "=", "json_decode", "(", "content_json", ")", "except", "ValueError", ":", "raise", "MessageError", "(", "\"content could not be decoded\"", ")", "msg", "=", "cls", "(", "header", ",", "metadata", ",", "content", ")", "msg", ".", "_header_json", "=", "header_json", "msg", ".", "_metadata_json", "=", "metadata_json", "msg", ".", "_content_json", "=", "content_json", "return", "msg" ]
switch on newly negotiated encryption parameters for inbound traffic
def _activate_inbound ( self ) : block_size = self . _cipher_info [ self . remote_cipher ] [ 'block-size' ] if self . server_mode : IV_in = self . _compute_key ( 'A' , block_size ) key_in = self . _compute_key ( 'C' , self . _cipher_info [ self . remote_cipher ] [ 'key-size' ] ) else : IV_in = self . _compute_key ( 'B' , block_size ) key_in = self . _compute_key ( 'D' , self . _cipher_info [ self . remote_cipher ] [ 'key-size' ] ) engine = self . _get_cipher ( self . remote_cipher , key_in , IV_in ) mac_size = self . _mac_info [ self . remote_mac ] [ 'size' ] mac_engine = self . _mac_info [ self . remote_mac ] [ 'class' ] # initial mac keys are done in the hash's natural size (not the potentially truncated # transmission size) if self . server_mode : mac_key = self . _compute_key ( 'E' , mac_engine ( ) . digest_size ) else : mac_key = self . _compute_key ( 'F' , mac_engine ( ) . digest_size ) self . packetizer . set_inbound_cipher ( engine , block_size , mac_engine , mac_size , mac_key ) compress_in = self . _compression_info [ self . remote_compression ] [ 1 ] if ( compress_in is not None ) and ( ( self . remote_compression != 'zlib@openssh.com' ) or self . authenticated ) : self . _log ( DEBUG , 'Switching on inbound compression ...' ) self . packetizer . set_inbound_compressor ( compress_in ( ) )
12,340
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/transport.py#L1702-L1724
[ "def", "getOverlayTransformTrackedDeviceRelative", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getOverlayTransformTrackedDeviceRelative", "punTrackedDevice", "=", "TrackedDeviceIndex_t", "(", ")", "pmatTrackedDeviceToOverlayTransform", "=", "HmdMatrix34_t", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "byref", "(", "punTrackedDevice", ")", ",", "byref", "(", "pmatTrackedDeviceToOverlayTransform", ")", ")", "return", "result", ",", "punTrackedDevice", ",", "pmatTrackedDeviceToOverlayTransform" ]
Enable the root account on the remote host .
def enable_user ( self , user ) : if user in self . ssh_pool . _ssh_clients : return if user == 'root' : _root_ssh_client = ssh . SshClient ( hostname = self . hostname , user = 'root' , key_filename = self . _key_filename , via_ip = self . via_ip ) # connect as a root user _root_ssh_client . start ( ) result , _ = _root_ssh_client . run ( 'uname -a' ) image_user = None # check if root is not allowed if 'Please login as the user "cloud-user"' in result : image_user = 'cloud-user' _root_ssh_client . stop ( ) elif 'Please login as the user "fedora" rather than the user "root"' in result : image_user = 'fedora' _root_ssh_client . stop ( ) elif 'Please login as the user "centos" rather than the user "root"' in result : image_user = 'centos' _root_ssh_client . stop ( ) if image_user : self . enable_user ( image_user ) LOG . info ( 'enabling the root user' ) _cmd = "sudo sed -i 's,.*ssh-rsa,ssh-rsa,' /root/.ssh/authorized_keys" self . ssh_pool . run ( image_user , _cmd ) _root_ssh_client . start ( ) self . ssh_pool . add_ssh_client ( 'root' , _root_ssh_client ) return # add the cloud user to the ssh pool self . ssh_pool . build_ssh_client ( hostname = self . hostname , user = user , key_filename = self . _key_filename , via_ip = self . via_ip )
12,341
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L54-L103
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Upload a local file on the remote host .
def send_file ( self , local_path , remote_path , user = 'root' , unix_mode = None ) : self . enable_user ( user ) return self . ssh_pool . send_file ( user , local_path , remote_path , unix_mode = unix_mode )
12,342
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L105-L109
[ "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", ")" ]
Upload a directory on the remote host .
def send_dir ( self , local_path , remote_path , user = 'root' ) : self . enable_user ( user ) return self . ssh_pool . send_dir ( user , local_path , remote_path )
12,343
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L111-L115
[ "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", ")" ]
Create a file on the remote host .
def create_file ( self , path , content , mode = 'w' , user = 'root' ) : self . enable_user ( user ) return self . ssh_pool . create_file ( user , path , content , mode )
12,344
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L121-L125
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "augment_args", "(", "args", ",", "kwargs", ")", "kwargs", "[", "'log_action'", "]", "=", "kwargs", ".", "get", "(", "'log_action'", ",", "'update'", ")", "if", "not", "self", ".", "rec", ":", "return", "self", ".", "add", "(", "*", "*", "kwargs", ")", "else", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "# Don't update object; use whatever was set in the original record", "if", "k", "not", "in", "(", "'source'", ",", "'s_vid'", ",", "'table'", ",", "'t_vid'", ",", "'partition'", ",", "'p_vid'", ")", ":", "setattr", "(", "self", ".", "rec", ",", "k", ",", "v", ")", "self", ".", "_session", ".", "merge", "(", "self", ".", "rec", ")", "if", "self", ".", "_logger", ":", "self", ".", "_logger", ".", "info", "(", "self", ".", "rec", ".", "log_str", ")", "self", ".", "_session", ".", "commit", "(", ")", "self", ".", "_ai_rec_id", "=", "None", "return", "self", ".", "rec", ".", "id" ]
Install some packages on the remote host .
def yum_install ( self , packages , ignore_error = False ) : return self . run ( 'yum install -y --quiet ' + ' ' . join ( packages ) , ignore_error = ignore_error , retry = 5 )
12,345
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L141-L146
[ "def", "_format_device", "(", "var", ")", ":", "if", "var", ".", "dtype", ".", "name", ".", "endswith", "(", "\"_ref\"", ")", ":", "resource_var_annotation", "=", "\"(legacy)\"", "else", ":", "resource_var_annotation", "=", "\"(resource)\"", "if", "var", ".", "device", ":", "return", "\"{} {}\"", ".", "format", "(", "var", ".", "device", ",", "resource_var_annotation", ")", "else", ":", "return", "resource_var_annotation" ]
Register the host on the RHSM .
def rhsm_register ( self , rhsm ) : # Get rhsm credentials login = rhsm . get ( 'login' ) password = rhsm . get ( 'password' , os . environ . get ( 'RHN_PW' ) ) pool_id = rhsm . get ( 'pool_id' ) # Ensure the RHEL beta channel are disabled self . run ( 'rm /etc/pki/product/69.pem' , ignore_error = True ) custom_log = 'subscription-manager register --username %s --password *******' % login self . run ( 'subscription-manager register --username %s --password "%s"' % ( login , password ) , success_status = ( 0 , 64 ) , custom_log = custom_log , retry = 3 ) if pool_id : self . run ( 'subscription-manager attach --pool %s' % pool_id ) else : self . run ( 'subscription-manager attach --auto' ) self . rhsm_active = True
12,346
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L155-L177
[ "def", "add", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_disposed", ":", "raise", "ValueError", "(", "'Cannot add value: this _WatchStore instance is already disposed'", ")", "self", ".", "_data", ".", "append", "(", "value", ")", "if", "hasattr", "(", "value", ",", "'nbytes'", ")", ":", "self", ".", "_in_mem_bytes", "+=", "value", ".", "nbytes", "self", ".", "_ensure_bytes_limits", "(", ")" ]
Enable a list of RHSM repositories .
def enable_repositories ( self , repositories ) : for r in repositories : if r [ 'type' ] != 'rhsm_channel' : continue if r [ 'name' ] not in self . rhsm_channels : self . rhsm_channels . append ( r [ 'name' ] ) if self . rhsm_active : subscription_cmd = "subscription-manager repos '--disable=*' --enable=" + ' --enable=' . join ( self . rhsm_channels ) self . run ( subscription_cmd ) repo_files = [ r for r in repositories if r [ 'type' ] == 'yum_repo' ] for repo_file in repo_files : self . create_file ( repo_file [ 'dest' ] , repo_file [ 'content' ] ) packages = [ r [ 'name' ] for r in repositories if r [ 'type' ] == 'package' ] if packages : self . yum_install ( packages )
12,347
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L179-L202
[ "def", "_gcd_array", "(", "X", ")", ":", "greatest_common_divisor", "=", "0.0", "for", "x", "in", "X", ":", "greatest_common_divisor", "=", "_gcd", "(", "greatest_common_divisor", ",", "x", ")", "return", "greatest_common_divisor" ]
Create the stack user on the machine .
def create_stack_user ( self ) : self . run ( 'adduser -m stack' , success_status = ( 0 , 9 ) ) self . create_file ( '/etc/sudoers.d/stack' , 'stack ALL=(root) NOPASSWD:ALL\n' ) self . run ( 'mkdir -p /home/stack/.ssh' ) self . run ( 'cp /root/.ssh/authorized_keys /home/stack/.ssh/authorized_keys' ) self . run ( 'chown -R stack:stack /home/stack/.ssh' ) self . run ( 'chmod 700 /home/stack/.ssh' ) self . run ( 'chmod 600 /home/stack/.ssh/authorized_keys' ) self . ssh_pool . build_ssh_client ( self . hostname , 'stack' , self . _key_filename , self . via_ip )
12,348
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L204-L216
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
Store in the user home directory an image from a remote location .
def fetch_image ( self , path , dest , user = 'root' ) : self . run ( 'test -f %s || curl -L -s -o %s %s' % ( dest , dest , path ) , user = user , ignore_error = True )
12,349
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L218-L222
[ "def", "focusInEvent", "(", "self", ",", "event", ")", ":", "self", ".", "_changedRecord", "=", "-", "1", "super", "(", "XOrbRecordBox", ",", "self", ")", ".", "focusInEvent", "(", "event", ")" ]
Clean up unnecessary packages from the system .
def clean_system ( self ) : self . run ( 'systemctl disable NetworkManager' , success_status = ( 0 , 1 ) ) self . run ( 'systemctl stop NetworkManager' , success_status = ( 0 , 5 ) ) self . run ( 'pkill -9 dhclient' , success_status = ( 0 , 1 ) ) self . yum_remove ( [ 'cloud-init' , 'NetworkManager' ] ) self . run ( 'systemctl enable network' ) self . run ( 'systemctl restart network' )
12,350
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L232-L240
[ "def", "ends_with_path_separator", "(", "self", ",", "file_path", ")", ":", "if", "is_int_type", "(", "file_path", ")", ":", "return", "False", "file_path", "=", "make_string_path", "(", "file_path", ")", "return", "(", "file_path", "and", "file_path", "not", "in", "(", "self", ".", "path_separator", ",", "self", ".", "alternative_path_separator", ")", "and", "(", "file_path", ".", "endswith", "(", "self", ".", "_path_separator", "(", "file_path", ")", ")", "or", "self", ".", "alternative_path_separator", "is", "not", "None", "and", "file_path", ".", "endswith", "(", "self", ".", "_alternative_path_separator", "(", "file_path", ")", ")", ")", ")" ]
Do a yum update on the system .
def yum_update ( self , allow_reboot = False ) : self . run ( 'yum clean all' ) self . run ( 'test -f /usr/bin/subscription-manager && subscription-manager repos --list-enabled' , ignore_error = True ) self . run ( 'yum repolist' ) self . run ( 'yum update -y --quiet' , retry = 3 ) # reboot if a new initrd has been generated since the boot if allow_reboot : self . run ( 'grubby --set-default $(ls /boot/vmlinuz-*.x86_64|tail -1)' ) default_kernel = self . run ( 'grubby --default-kernel' ) [ 0 ] . rstrip ( ) cur_kernel = self . run ( 'uname -r' ) [ 0 ] . rstrip ( ) if cur_kernel not in default_kernel : self . run ( 'reboot' , ignore_error = True ) self . ssh_pool . stop_all ( )
12,351
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/server.py#L242-L260
[ "def", "wait_for", "(", "timeout", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "return", "result", ".", "wait", "(", "timeout", ")", "except", "crochet", ".", "TimeoutError", ":", "result", ".", "cancel", "(", ")", "raise" ]
Get ordered list of models for the specified time range . The timestamp on the earliest model will likely occur before start_timestamp . This is to ensure that we return the models for the entire range .
def get_by_range ( model_cls , * args , * * kwargs ) : start_timestamp = kwargs . get ( 'start_timestamp' ) end_timestamp = kwargs . get ( 'end_timestamp' ) if ( start_timestamp is not None ) and ( end_timestamp is not None ) and ( start_timestamp > end_timestamp ) : raise InvalidTimestampRange models = model_cls . read_time_range ( * args , end_timestamp = end_timestamp ) . order_by ( model_cls . time_order ) # # start time -> Loop through until you find one set before or on start # if start_timestamp is not None : index = 0 for index , model in enumerate ( models , start = 1 ) : if model . timestamp <= start_timestamp : break models = models [ : index ] return models
12,352
https://github.com/JawboneHealth/jhhalchemy/blob/ca0011d644e404561a142c9d7f0a8a569f1f4f27/jhhalchemy/model/time_order.py#L69-L99
[ "def", "isrchi", "(", "value", ",", "ndim", ",", "array", ")", ":", "value", "=", "ctypes", ".", "c_int", "(", "value", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "array", "=", "stypes", ".", "toIntVector", "(", "array", ")", "return", "libspice", ".", "isrchi_c", "(", "value", ",", "ndim", ",", "array", ")" ]
Get all timezones set within a given time . Uses time_dsc_index
def read_time_range ( cls , * args , * * kwargs ) : criteria = list ( args ) start = kwargs . get ( 'start_timestamp' ) end = kwargs . get ( 'end_timestamp' ) if start is not None : criteria . append ( cls . time_order <= - start ) if end is not None : criteria . append ( cls . time_order >= - end ) return cls . read ( * criteria )
12,353
https://github.com/JawboneHealth/jhhalchemy/blob/ca0011d644e404561a142c9d7f0a8a569f1f4f27/jhhalchemy/model/time_order.py#L34-L54
[ "def", "removeFile", "(", "file", ")", ":", "if", "\"y\"", "in", "speech", ".", "question", "(", "\"Are you sure you want to remove \"", "+", "file", "+", "\"? (Y/N): \"", ")", ":", "speech", ".", "speak", "(", "\"Removing \"", "+", "file", "+", "\" with the 'rm' command.\"", ")", "subprocess", ".", "call", "(", "[", "\"rm\"", ",", "\"-r\"", ",", "file", "]", ")", "else", ":", "speech", ".", "speak", "(", "\"Okay, I won't remove \"", "+", "file", "+", "\".\"", ")" ]
Add data to the parameter set
def add_data ( self , data , metadata = None ) : subdata = np . atleast_2d ( data ) # we try to accommodate transposed input if subdata . shape [ 1 ] != self . grid . nr_of_elements : if subdata . shape [ 0 ] == self . grid . nr_of_elements : subdata = subdata . T else : raise Exception ( 'Number of values does not match the number of ' + 'elements in the grid' ) # now make sure that metadata can be zipped with the subdata K = subdata . shape [ 0 ] if metadata is not None : if K > 1 : if ( not isinstance ( metadata , ( list , tuple ) ) or len ( metadata ) != K ) : raise Exception ( 'metadata does not fit the provided data' ) else : # K == 1 metadata = [ metadata , ] if metadata is None : metadata = [ None for i in range ( 0 , K ) ] return_ids = [ ] for dataset , meta in zip ( subdata , metadata ) : cid = self . _get_next_index ( ) self . parsets [ cid ] = dataset self . metadata [ cid ] = meta return_ids . append ( cid ) if len ( return_ids ) == 1 : return return_ids [ 0 ] else : return return_ids
12,354
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L40-L112
[ "def", "from_rep", "(", "u", ")", ":", "if", "isinstance", "(", "u", ",", "pyversion", ".", "string_types", ")", ":", "return", "uuid", ".", "UUID", "(", "u", ")", "# hack to remove signs", "a", "=", "ctypes", ".", "c_ulong", "(", "u", "[", "0", "]", ")", "b", "=", "ctypes", ".", "c_ulong", "(", "u", "[", "1", "]", ")", "combined", "=", "a", ".", "value", "<<", "64", "|", "b", ".", "value", "return", "uuid", ".", "UUID", "(", "int", "=", "combined", ")" ]
Load one parameter set from a file which contains one value per line
def load_model_from_file ( self , filename ) : assert os . path . isfile ( filename ) data = np . loadtxt ( filename ) . squeeze ( ) assert len ( data . shape ) == 1 pid = self . add_data ( data ) return pid
12,355
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L171-L190
[ "async", "def", "on_raw_422", "(", "self", ",", "message", ")", ":", "await", "self", ".", "_registration_completed", "(", "message", ")", "self", ".", "motd", "=", "None", "await", "self", ".", "on_connect", "(", ")" ]
Load real and imaginary parts from a sens . dat file generated by CRMod
def load_from_sens_file ( self , filename ) : sens_data = np . loadtxt ( filename , skiprows = 1 ) nid_re = self . add_data ( sens_data [ : , 2 ] ) nid_im = self . add_data ( sens_data [ : , 3 ] ) return nid_re , nid_im
12,356
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L192-L211
[ "def", "suspend_all", "(", "self", ")", ":", "pool", "=", "Pool", "(", "concurrency", "=", "3", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "pool", ".", "append", "(", "node", ".", "suspend", ")", "yield", "from", "pool", ".", "join", "(", ")" ]
Save one or two parameter sets in the rho . dat forward model format
def save_to_rho_file ( self , filename , cid_mag , cid_pha = None ) : mag_data = self . parsets [ cid_mag ] if cid_pha is None : pha_data = np . zeros ( mag_data . shape ) else : pha_data = self . parsets [ cid_pha ] with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( self . grid . nr_of_elements ) , 'utf-8' , ) ) np . savetxt ( fid , np . vstack ( ( mag_data , pha_data , ) ) . T , fmt = '%f %f' )
12,357
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L213-L246
[ "def", "device_removed", "(", "self", ",", "device", ")", ":", "if", "not", "self", ".", "_mounter", ".", "is_handleable", "(", "device", ")", ":", "return", "device_file", "=", "device", ".", "device_presentation", "if", "(", "device", ".", "is_drive", "or", "device", ".", "is_toplevel", ")", "and", "device_file", ":", "self", ".", "_show_notification", "(", "'device_removed'", ",", "_", "(", "'Device removed'", ")", ",", "_", "(", "'device disappeared on {0.device_presentation}'", ",", "device", ")", ",", "device", ".", "icon_name", ")" ]
if pid is a number don t do anything . If pid is a list with one entry strip the list and return the number . If pid contains more than one entries do nothing .
def _clean_pid ( self , pid ) : if isinstance ( pid , ( list , tuple ) ) : if len ( pid ) == 1 : return pid [ 0 ] else : return pid return pid
12,358
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L261-L271
[ "def", "sync_hooks", "(", "user_id", ",", "repositories", ")", ":", "from", ".", "api", "import", "GitHubAPI", "try", ":", "# Sync hooks", "gh", "=", "GitHubAPI", "(", "user_id", "=", "user_id", ")", "for", "repo_id", "in", "repositories", ":", "try", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "gh", ".", "sync_repo_hook", "(", "repo_id", ")", "# We commit per repository, because while the task is running", "# the user might enable/disable a hook.", "db", ".", "session", ".", "commit", "(", ")", "except", "RepositoryAccessError", "as", "e", ":", "current_app", ".", "logger", ".", "warning", "(", "e", ".", "message", ",", "exc_info", "=", "True", ")", "except", "NoResultFound", ":", "pass", "# Repository not in DB yet", "except", "Exception", "as", "exc", ":", "sync_hooks", ".", "retry", "(", "exc", "=", "exc", ")" ]
Modify the given dataset in the rectangular area given by the parameters and assign all parameters inside this area the given value .
def modify_area ( self , pid , xmin , xmax , zmin , zmax , value ) : area_polygon = shapgeo . Polygon ( ( ( xmin , zmax ) , ( xmax , zmax ) , ( xmax , zmin ) , ( xmin , zmin ) ) ) self . modify_polygon ( pid , area_polygon , value )
12,359
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L273-L319
[ "def", "get_canonical_key_id", "(", "self", ",", "key_id", ")", ":", "shard_num", "=", "self", ".", "get_shard_num_by_key_id", "(", "key_id", ")", "return", "self", ".", "_canonical_keys", "[", "shard_num", "]" ]
Extract values at certain points in the grid from a given parameter set . Cells are selected by interpolating the centroids of the cells towards the line using a nearest scheme .
def extract_points ( self , pid , points ) : xy = self . grid . get_element_centroids ( ) data = self . parsets [ pid ] iobj = spi . NearestNDInterpolator ( xy , data ) values = iobj ( points ) return values
12,360
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L373-L399
[ "def", "read_longlong", "(", "self", ")", ":", "self", ".", "bitcount", "=", "self", ".", "bits", "=", "0", "return", "unpack", "(", "'>Q'", ",", "self", ".", "input", ".", "read", "(", "8", ")", ")", "[", "0", "]" ]
Extract parameter values along a given line .
def extract_along_line ( self , pid , xy0 , xy1 , N = 10 ) : assert N >= 2 xy0 = np . array ( xy0 ) . squeeze ( ) xy1 = np . array ( xy1 ) . squeeze ( ) assert xy0 . size == 2 assert xy1 . size == 2 # compute points points = [ ( x , y ) for x , y in zip ( np . linspace ( xy0 [ 0 ] , xy1 [ 0 ] , N ) , np . linspace ( xy0 [ 1 ] , xy1 [ 1 ] , N ) ) ] result = self . extract_points ( pid , points ) results_xyv = np . hstack ( ( points , result [ : , np . newaxis ] ) ) return results_xyv
12,361
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L401-L437
[ "def", "rejection_sample", "(", "n_samples", ",", "pool_size", ",", "rng_state", ")", ":", "result", "=", "np", ".", "empty", "(", "n_samples", ",", "dtype", "=", "np", ".", "int64", ")", "for", "i", "in", "range", "(", "n_samples", ")", ":", "reject_sample", "=", "True", "while", "reject_sample", ":", "j", "=", "tau_rand_int", "(", "rng_state", ")", "%", "pool_size", "for", "k", "in", "range", "(", "i", ")", ":", "if", "j", "==", "result", "[", "k", "]", ":", "break", "else", ":", "reject_sample", "=", "False", "result", "[", "i", "]", "=", "j", "return", "result" ]
Extract all data points whose element centroid lies within the given polygon .
def extract_polygon_area ( self , pid , polygon_points ) : polygon = shapgeo . Polygon ( polygon_points ) xy = self . grid . get_element_centroids ( ) in_poly = [ ] for nr , point in enumerate ( xy ) : if shapgeo . Point ( point ) . within ( polygon ) : in_poly . append ( nr ) values = self . parsets [ pid ] [ in_poly ] return np . array ( in_poly ) , values
12,362
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/parManager.py#L439-L457
[ "def", "AuthorizingClient", "(", "domain", ",", "auth", ",", "user_agent", "=", "None", ")", ":", "http_transport", "=", "transport", ".", "HttpTransport", "(", "domain", ",", "build_headers", "(", "auth", ",", "user_agent", ")", ")", "return", "client", ".", "Client", "(", "http_transport", ")" ]
Rotate the given point by angle
def rotate_point ( xorigin , yorigin , x , y , angle ) : rotx = ( x - xorigin ) * np . cos ( angle ) - ( y - yorigin ) * np . sin ( angle ) roty = ( x - yorigin ) * np . sin ( angle ) + ( y - yorigin ) * np . cos ( angle ) return rotx , roty
12,363
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/grid_homogenize.py#L96-L101
[ "def", "_timestamp_regulator", "(", "self", ")", ":", "unified_timestamps", "=", "_PrettyDefaultDict", "(", "list", ")", "staged_files", "=", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", "for", "timestamp_basename", "in", "self", ".", "__timestamps_unregulated", ":", "if", "len", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ">", "1", ":", "# File has been splitted", "timestamp_name", "=", "''", ".", "join", "(", "timestamp_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "staged_splitted_files_of_timestamp", "=", "list", "(", "filter", "(", "lambda", "staged_file", ":", "(", "timestamp_name", "==", "staged_file", "[", ":", "-", "3", "]", "and", "all", "(", "[", "(", "x", "in", "set", "(", "map", "(", "str", ",", "range", "(", "10", ")", ")", ")", ")", "for", "x", "in", "staged_file", "[", "-", "3", ":", "]", "]", ")", ")", ",", "staged_files", ")", ")", "if", "len", "(", "staged_splitted_files_of_timestamp", ")", "==", "0", ":", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "timestamp_basename", ")", "]", "=", "{", "\"reason\"", ":", "\"Missing staged file\"", ",", "\"current_staged_files\"", ":", "staged_files", "}", "continue", "staged_splitted_files_of_timestamp", ".", "sort", "(", ")", "unified_timestamp", "=", "list", "(", ")", "for", "staging_digits", ",", "splitted_file", "in", "enumerate", "(", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", ")", ":", "prev_splits_sec", "=", "0", "if", "int", "(", "staging_digits", ")", "!=", "0", ":", "prev_splits_sec", "=", "self", ".", "_get_audio_duration_seconds", "(", "\"{}/staging/{}{:03d}\"", ".", "format", "(", "self", ".", "src_dir", ",", "timestamp_name", ",", "staging_digits", "-", "1", ")", ")", "for", "word_block", "in", "splitted_file", ":", "unified_timestamp", ".", "append", "(", "_WordBlock", "(", "word", "=", "word_block", ".", "word", ",", "start", "=", "round", "(", "word_block", ".", "start", "+", "prev_splits_sec", ",", "2", ")", ",", "end", "=", "round", "(", "word_block", ".", "end", "+", "prev_splits_sec", ",", "2", ")", ")", ")", "unified_timestamps", "[", "str", "(", "timestamp_basename", ")", "]", "+=", "unified_timestamp", "else", ":", "unified_timestamps", "[", "timestamp_basename", "]", "+=", "self", ".", "__timestamps_unregulated", "[", "timestamp_basename", "]", "[", "0", "]", "self", ".", "__timestamps", ".", "update", "(", "unified_timestamps", ")", "self", ".", "__timestamps_unregulated", "=", "_PrettyDefaultDict", "(", "list", ")" ]
Compute synthetic measurements over a homogeneous half - space
def get_R_mod ( options , rho0 ) : tomodir = tdManager . tdMan ( elem_file = options . elem_file , elec_file = options . elec_file , config_file = options . config_file , ) # set model tomodir . add_homogeneous_model ( magnitude = rho0 ) # only interested in magnitudes Z = tomodir . measurements ( ) [ : , 0 ] return Z
12,364
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_get_modelling_errors.py#L110-L125
[ "def", "wait_until_stale", "(", "self", ",", "locator", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "def", "wait", "(", ")", ":", "'''\n Wait function passed to executor\n '''", "element", "=", "WebDriverWait", "(", "self", ".", "driver", ",", "timeout", ")", ".", "until", "(", "EC", ".", "staleness_of", "(", "(", "self", ".", "locator_handler", ".", "parse_locator", "(", "locator", ")", ".", "By", ",", "self", ".", "locator_handler", ".", "parse_locator", "(", "locator", ")", ".", "value", ")", ")", ")", "return", "WebElementWrapper", ".", "WebElementWrapper", "(", "self", ",", "locator", ",", "element", ")", "return", "self", ".", "execute_and_handle_webdriver_exceptions", "(", "wait", ",", "timeout", ",", "locator", ",", "'Timeout waiting for element to become stale'", ")" ]
For a given path create a directory structure composed of a set of folders and return the path to the \ inner - most folder .
def make_and_return_path_from_path_and_folder_names ( path , folder_names ) : for folder_name in folder_names : path += folder_name + '/' try : os . makedirs ( path ) except FileExistsError : pass return path
12,365
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/tools/path_util.py#L42-L77
[ "def", "register_flags", "(", "self", ",", "flags", ")", ":", "self", ".", "_CONSUMED_FLAGS", ".", "update", "(", "flags", ")", "self", ".", "_flags", ".", "update", "(", "flags", ")" ]
Register an existing nova VM .
def register_host ( self , bm_instance ) : bmc_ip = '10.130.%d.100' % ( self . _bmc_range_start + self . _nic_cpt ) bmc_net = '10.130.%d.0' % ( self . _bmc_range_start + self . _nic_cpt ) bmc_gw = '10.130.%d.1' % ( self . _bmc_range_start + self . _nic_cpt ) device = 'eth%d' % ( 2 + self . _nic_cpt ) body_create_subnet = { 'subnets' : [ { 'name' : 'bmc_' + device , 'cidr' : bmc_net + '/24' , 'ip_version' : 4 , 'network_id' : self . _bmc_net [ 'id' ] } ] } subnet_id = self . neutron . create_subnet ( body = body_create_subnet ) [ 'subnets' ] [ 0 ] [ 'id' ] self . attach_subnet_to_router ( subnet_id ) self . os_instance . interface_attach ( None , self . _bmc_net [ 'id' ] , bmc_ip ) content = """ DEVICE="{device}" BOOTPROTO=static IPADDR={bmc_ip} NETMASK=255.255.255.0 ONBOOT=yes """ self . create_file ( '/etc/sysconfig/network-scripts/ifcfg-%s' % device , content = content . format ( device = device , bmc_ip = bmc_ip , bmc_gw = bmc_gw ) ) content = """ 192.0.2.0/24 via {bmc_gw} """ self . create_file ( '/etc/sysconfig/network-scripts/route-%s' % device , content = content . format ( bmc_gw = bmc_gw ) ) self . run ( 'ifup %s' % device ) # Ensure the outgoing traffic go through the correct NIC to avoid spoofing # protection # TODO(Gonéri): This should be persistant. self . run ( 'ip rule add from %s table %d' % ( bmc_ip , self . _nic_cpt + 2 ) ) self . run ( 'ip route add default via %s dev %s table %d' % ( bmc_gw , device , self . _nic_cpt + 2 ) ) content = """ [Unit] Description=openstack-bmc {bm_instance} Service [Service] ExecStart=/usr/local/bin/openstackbmc --os-user {os_username} --os-password {os_password} --os-project-id {os_project_id} --os-auth-url {os_auth_url} --instance {bm_instance} --address {bmc_ip} User=root StandardOutput=kmsg+console StandardError=inherit Restart=always [Install] WantedBy=multi-user.target """ unit = 'openstack-bmc-%d.service' % self . _nic_cpt self . create_file ( '/usr/lib/systemd/system/%s' % unit , content . format ( os_username = self . os_username , os_password = protect_password ( self . os_password ) , os_project_id = self . os_project_id , os_auth_url = self . os_auth_url , bm_instance = bm_instance , bmc_ip = bmc_ip ) ) self . run ( 'systemctl enable %s' % unit ) self . run ( 'systemctl start %s' % unit ) self . _nic_cpt += 1 return bmc_ip
12,366
https://github.com/redhat-openstack/python-tripleo-helper/blob/bfa165538335edb1088170c7a92f097167225c81/tripleohelper/ovb_bmc.py#L116-L189
[ "def", "from_header_str", "(", "cls", ",", "header", ")", ":", "if", "not", "header", ":", "return", "cls", "(", ")", "try", ":", "params", "=", "header", ".", "strip", "(", ")", ".", "split", "(", "HEADER_DELIMITER", ")", "header_dict", "=", "{", "}", "data", "=", "{", "}", "for", "param", "in", "params", ":", "entry", "=", "param", ".", "split", "(", "'='", ")", "key", "=", "entry", "[", "0", "]", "if", "key", "in", "(", "ROOT", ",", "PARENT", ",", "SAMPLE", ")", ":", "header_dict", "[", "key", "]", "=", "entry", "[", "1", "]", "# Ignore any \"Self=\" trace ids injected from ALB.", "elif", "key", "!=", "SELF", ":", "data", "[", "key", "]", "=", "entry", "[", "1", "]", "return", "cls", "(", "root", "=", "header_dict", ".", "get", "(", "ROOT", ",", "None", ")", ",", "parent", "=", "header_dict", ".", "get", "(", "PARENT", ",", "None", ")", ",", "sampled", "=", "header_dict", ".", "get", "(", "SAMPLE", ",", "None", ")", ",", "data", "=", "data", ",", ")", "except", "Exception", ":", "log", ".", "warning", "(", "\"malformed tracing header %s, ignore.\"", ",", "header", ")", "return", "cls", "(", ")" ]
Return the snapshot in Godeps . json form
def Godeps ( self ) : dict = [ ] for package in sorted ( self . _packages . keys ( ) ) : dict . append ( { "ImportPath" : str ( package ) , "Rev" : str ( self . _packages [ package ] ) } ) return dict
12,367
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/go/snapshot.py#L47-L57
[ "def", "user_agent", "(", "self", ",", "text", ",", "*", "*", "kwargs", ")", ":", "indicator_obj", "=", "UserAgent", "(", "text", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_indicator", "(", "indicator_obj", ")" ]
Return the snapshot in GLOGFILE form
def GLOGFILE ( self ) : lines = [ ] for package in sorted ( self . _packages . keys ( ) ) : lines . append ( "%s %s" % ( str ( package ) , str ( self . _packages [ package ] ) ) ) return "\n" . join ( lines )
12,368
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/go/snapshot.py#L59-L66
[ "def", "get_other_props", "(", "all_props", ",", "reserved_props", ")", ":", "# type: (Dict, Tuple) -> Optional[Dict]", "if", "hasattr", "(", "all_props", ",", "'items'", ")", "and", "callable", "(", "all_props", ".", "items", ")", ":", "return", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "list", "(", "all_props", ".", "items", "(", ")", ")", "if", "k", "not", "in", "reserved_props", "]", ")", "return", "None" ]
Return the snapshot in glide . lock form
def Glide ( self ) : dict = { "hash" : "???" , "updated" : str ( datetime . datetime . now ( tz = pytz . utc ) . isoformat ( ) ) , "imports" : [ ] , } decomposer = ImportPathsDecomposerBuilder ( ) . buildLocalDecomposer ( ) decomposer . decompose ( self . _packages . keys ( ) ) classes = decomposer . classes ( ) for ipp in classes : dep = { "name" : ipp , "version" : str ( self . _packages [ classes [ ipp ] [ 0 ] ] ) } if len ( classes [ ipp ] ) > 1 or classes [ ipp ] [ 0 ] != ipp : dep [ "subpackages" ] = map ( lambda l : l [ len ( ipp ) + 1 : ] , classes [ ipp ] ) dict [ "imports" ] . append ( dep ) return yaml . dump ( dict , default_flow_style = False )
12,369
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/go/snapshot.py#L68-L91
[ "def", "coders", "(", "self", ")", ":", "return", "(", "PrimitiveTypeCoder", ",", "TensorFlowCoder", ",", "FunctionCoder", ",", "ListCoder", ",", "DictCoder", ",", "SliceCoder", ",", "ParameterCoder", ",", "ParamListCoder", ",", "ParameterizedCoder", ",", "TransformCoder", ",", "PriorCoder", ")" ]
Render the simulated state - action trajectories for Navigation domain .
def render ( self , trajectories : Tuple [ NonFluents , Fluents , Fluents , Fluents , np . array ] , batch : Optional [ int ] = None ) -> None : non_fluents , initial_state , states , actions , interms , rewards = trajectories non_fluents = dict ( non_fluents ) states = dict ( ( name , fluent [ 0 ] ) for name , fluent in states ) actions = dict ( ( name , fluent [ 0 ] ) for name , fluent in actions ) rewards = rewards [ 0 ] idx = self . _compiler . rddl . domain . state_fluent_ordering . index ( 'location/1' ) start = initial_state [ idx ] [ 0 ] g = non_fluents [ 'GOAL/1' ] path = states [ 'location/1' ] deltas = actions [ 'move/1' ] centers = non_fluents [ 'DECELERATION_ZONE_CENTER/2' ] decays = non_fluents [ 'DECELERATION_ZONE_DECAY/1' ] zones = [ ( x , y , d ) for ( x , y ) , d in zip ( centers , decays ) ] self . _ax1 = plt . gca ( ) self . _render_state_space ( ) self . _render_start_and_goal_positions ( start , g ) self . _render_deceleration_zones ( zones ) self . _render_state_action_trajectory ( start , path , deltas ) plt . title ( 'Navigation' , fontweight = 'bold' ) plt . legend ( loc = 'lower right' ) plt . show ( )
12,370
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/navigation_visualizer.py#L44-L82
[ "def", "write_routine_method", "(", "self", ",", "routine", ")", ":", "if", "self", ".", "_lob_as_string_flag", ":", "return", "self", ".", "_write_routine_method_without_lob", "(", "routine", ")", "else", ":", "if", "self", ".", "is_lob_parameter", "(", "routine", "[", "'parameters'", "]", ")", ":", "return", "self", ".", "_write_routine_method_with_lob", "(", "routine", ")", "else", ":", "return", "self", ".", "_write_routine_method_without_lob", "(", "routine", ")" ]
Times the execution of a function . If the process is stopped and restarted then timing is continued using saved files .
def persistent_timer ( func ) : @ functools . wraps ( func ) def timed_function ( optimizer_instance , * args , * * kwargs ) : start_time_path = "{}/.start_time" . format ( optimizer_instance . phase_output_path ) try : with open ( start_time_path ) as f : start = float ( f . read ( ) ) except FileNotFoundError : start = time . time ( ) with open ( start_time_path , "w+" ) as f : f . write ( str ( start ) ) result = func ( optimizer_instance , * args , * * kwargs ) execution_time = str ( dt . timedelta ( seconds = time . time ( ) - start ) ) logger . info ( "{} took {} to run" . format ( optimizer_instance . phase_name , execution_time ) ) with open ( "{}/execution_time" . format ( optimizer_instance . phase_output_path ) , "w+" ) as f : f . write ( execution_time ) return result return timed_function
12,371
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L110-L149
[ "def", "invalid", "(", "cls", ",", "data", ",", "context", "=", "None", ")", ":", "return", "cls", "(", "cls", ".", "TagType", ".", "INVALID", ",", "data", ",", "context", ")" ]
The path to the backed up optimizer folder .
def backup_path ( self ) -> str : return "{}/{}/{}{}/optimizer_backup" . format ( conf . instance . output_path , self . phase_path , self . phase_name , self . phase_tag )
12,372
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L213-L218
[ "def", "login", "(", "self", ",", "login", ",", "password", ")", ":", "self", ".", "client", ".", "read_until", "(", "'Username: '", ")", "self", ".", "client", ".", "write", "(", "login", "+", "'\\r\\n'", ")", "self", ".", "client", ".", "read_until", "(", "'Password: '", ")", "self", ".", "client", ".", "write", "(", "password", "+", "'\\r\\n'", ")", "current_data", "=", "self", ".", "client", ".", "read_until", "(", "'$ '", ",", "10", ")", "if", "not", "current_data", ".", "endswith", "(", "'$ '", ")", ":", "raise", "InvalidLogin" ]
Copy files from the sym - linked optimizer folder to the backup folder in the workspace .
def backup ( self ) : try : shutil . rmtree ( self . backup_path ) except FileNotFoundError : pass try : shutil . copytree ( self . opt_path , self . backup_path ) except shutil . Error as e : logger . exception ( e )
12,373
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L256-L267
[ "def", "max_duration", "(", "self", ",", "value", ")", ":", "if", "not", "value", "is", "None", ":", "if", "not", "type", "(", "value", ")", "in", "[", "float", ",", "int", "]", ":", "raise", "TypeError", "(", "\"max_duration needs to be specified as a number\"", ")", "if", "value", "<", "1.0", ":", "raise", "ValueError", "(", "\"max_duration needs to be greater than 1.0\"", ")", "value", "=", "float", "(", "value", ")", "self", ".", "__max_duration", "=", "value" ]
Copy files from the backup folder to the sym - linked optimizer folder .
def restore ( self ) : if os . path . exists ( self . backup_path ) : for file in glob . glob ( self . backup_path + "/*" ) : shutil . copy ( file , self . path )
12,374
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L269-L275
[ "def", "max_duration", "(", "self", ",", "value", ")", ":", "if", "not", "value", "is", "None", ":", "if", "not", "type", "(", "value", ")", "in", "[", "float", ",", "int", "]", ":", "raise", "TypeError", "(", "\"max_duration needs to be specified as a number\"", ")", "if", "value", "<", "1.0", ":", "raise", "ValueError", "(", "\"max_duration needs to be greater than 1.0\"", ")", "value", "=", "float", "(", "value", ")", "self", ".", "__max_duration", "=", "value" ]
Get a config field from this optimizer s section in non_linear . ini by a key and value type .
def config ( self , attribute_name , attribute_type = str ) : return self . named_config . get ( self . __class__ . __name__ , attribute_name , attribute_type )
12,375
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L277-L293
[ "def", "post_gist", "(", "report_data", ",", "old_sha", ",", "new_sha", ")", ":", "payload", "=", "{", "\"description\"", ":", "(", "\"Changes in OpenStack-Ansible between \"", "\"{0} and {1}\"", ".", "format", "(", "old_sha", ",", "new_sha", ")", ")", ",", "\"public\"", ":", "True", ",", "\"files\"", ":", "{", "\"osa-diff-{0}-{1}.rst\"", ".", "format", "(", "old_sha", ",", "new_sha", ")", ":", "{", "\"content\"", ":", "report_data", "}", "}", "}", "url", "=", "\"https://api.github.com/gists\"", "r", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ")", "response", "=", "r", ".", "json", "(", ")", "return", "response", "[", "'html_url'", "]" ]
Setup a model instance of a weighted sample including its weight and likelihood .
def weighted_sample_instance_from_weighted_samples ( self , index ) : model , weight , likelihood = self . weighted_sample_model_from_weighted_samples ( index ) self . _weighted_sample_model = model return self . variable . instance_from_physical_vector ( model ) , weight , likelihood
12,376
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L724-L736
[ "def", "write_new_expr_id", "(", "self", ",", "search_group", ",", "search", ",", "lars_id", ",", "instruments", ",", "gps_start_time", ",", "gps_end_time", ",", "comments", "=", "None", ")", ":", "# check if id already exists", "check_id", "=", "self", ".", "get_expr_id", "(", "search_group", ",", "search", ",", "lars_id", ",", "instruments", ",", "gps_start_time", ",", "gps_end_time", ",", "comments", "=", "comments", ")", "if", "check_id", ":", "return", "check_id", "# experiment not found in table", "row", "=", "self", ".", "RowType", "(", ")", "row", ".", "experiment_id", "=", "self", ".", "get_next_id", "(", ")", "row", ".", "search_group", "=", "search_group", "row", ".", "search", "=", "search", "row", ".", "lars_id", "=", "lars_id", "row", ".", "instruments", "=", "ifos_from_instrument_set", "(", "instruments", ")", "row", ".", "gps_start_time", "=", "gps_start_time", "row", ".", "gps_end_time", "=", "gps_end_time", "row", ".", "comments", "=", "comments", "self", ".", "append", "(", "row", ")", "# return new ID", "return", "row", ".", "experiment_id" ]
From a weighted sample return the model weight and likelihood hood .
def weighted_sample_model_from_weighted_samples ( self , index ) : return list ( self . pdf . samples [ index ] ) , self . pdf . weights [ index ] , - 0.5 * self . pdf . loglikes [ index ]
12,377
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/optimize/non_linear.py#L738-L749
[ "def", "Run", "(", "self", ")", ":", "self", ".", "_GetArgs", "(", ")", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Using database: {0}\"", ".", "format", "(", "self", ".", "_databasePath", ")", ")", "self", ".", "_db", "=", "database", ".", "RenamerDB", "(", "self", ".", "_databasePath", ")", "if", "self", ".", "_dbPrint", "or", "self", ".", "_dbUpdate", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "self", ".", "_db", ".", "PrintAllTables", "(", ")", "if", "self", ".", "_dbUpdate", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "self", ".", "_db", ".", "ManualUpdateTables", "(", ")", "self", ".", "_GetDatabaseConfig", "(", ")", "if", "self", ".", "_enableExtract", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "extractFileList", "=", "[", "]", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Parsing source directory for compressed files\"", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent", "(", ")", "extract", ".", "GetCompressedFilesInDir", "(", "self", ".", "_sourceDir", ",", "extractFileList", ",", "self", ".", "_ignoredDirsList", ")", "goodlogging", ".", "Log", ".", "DecreaseIndent", "(", ")", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "extract", ".", "Extract", "(", "extractFileList", ",", "self", ".", "_supportedFormatsList", ",", "self", ".", "_archiveDir", ",", "self", ".", "_skipUserInputExtract", ")", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "tvFileList", "=", "[", "]", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Parsing source directory for compatible files\"", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent", "(", ")", "self", ".", "_GetSupportedFilesInDir", "(", "self", ".", "_sourceDir", ",", "tvFileList", ",", "self", ".", "_supportedFormatsList", ",", "self", ".", "_ignoredDirsList", ")", "goodlogging", ".", "Log", ".", "DecreaseIndent", "(", ")", "tvRenamer", "=", "renamer", ".", "TVRenamer", "(", "self", ".", "_db", ",", "tvFileList", ",", "self", ".", "_archiveDir", ",", "guideName", "=", "'EPGUIDES'", ",", "tvDir", "=", "self", ".", "_tvDir", ",", "inPlaceRename", "=", "self", ".", "_inPlaceRename", ",", "forceCopy", "=", "self", ".", "_crossSystemCopyEnabled", ",", "skipUserInput", "=", "self", ".", "_skipUserInputRename", ")", "tvRenamer", ".", "Run", "(", ")" ]
Compare 2 hash digest .
def compare_digest ( a , b ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _compare_digest_py3 ( a , b ) return _compare_digest_py2 ( a , b )
12,378
https://github.com/Riminder/python-riminder-api/blob/01279f0ece08cf3d1dd45f76de6d9edf7fafec90/riminder/hmacutils.py#L15-L20
[ "def", "delete_logs", "(", "room", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "base_url", "=", "ChatPlugin", ".", "settings", ".", "get", "(", "'log_url'", ")", "if", "not", "base_url", "or", "room", ".", "custom_server", ":", "return", "try", ":", "response", "=", "requests", ".", "get", "(", "posixpath", ".", "join", "(", "base_url", ",", "'delete'", ")", ",", "params", "=", "{", "'cr'", ":", "room", ".", "jid", "}", ")", ".", "json", "(", ")", "except", "(", "RequestException", ",", "ValueError", ")", ":", "current_plugin", ".", "logger", ".", "exception", "(", "'Could not delete logs for %s'", ",", "room", ".", "jid", ")", "return", "if", "not", "response", ".", "get", "(", "'success'", ")", ":", "current_plugin", ".", "logger", ".", "warning", "(", "'Could not delete logs for %s: %s'", ",", "room", ".", "jid", ",", "response", ".", "get", "(", "'error'", ")", ")" ]
Prints the first batch of simulated trajectories .
def _render_trajectories ( self , trajectories : Tuple [ NonFluents , Fluents , Fluents , Fluents , np . array ] ) -> None : if self . _verbose : non_fluents , initial_state , states , actions , interms , rewards = trajectories shape = states [ 0 ] [ 1 ] . shape batch_size , horizon , = shape [ 0 ] , shape [ 1 ] states = [ ( s [ 0 ] , s [ 1 ] [ 0 ] ) for s in states ] interms = [ ( f [ 0 ] , f [ 1 ] [ 0 ] ) for f in interms ] actions = [ ( a [ 0 ] , a [ 1 ] [ 0 ] ) for a in actions ] rewards = np . reshape ( rewards , [ batch_size , horizon ] ) [ 0 ] self . _render_batch ( non_fluents , states , actions , interms , rewards )
12,379
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L50-L65
[ "def", "set_editor", "(", "self", ",", "editor", ")", ":", "if", "self", ".", "_editor", "is", "not", "None", ":", "try", ":", "self", ".", "_editor", ".", "offset_calculator", ".", "pic_infos_available", ".", "disconnect", "(", "self", ".", "_update", ")", "except", "(", "AttributeError", ",", "RuntimeError", ",", "ReferenceError", ")", ":", "# see https://github.com/OpenCobolIDE/OpenCobolIDE/issues/89", "pass", "self", ".", "_editor", "=", "weakref", ".", "proxy", "(", "editor", ")", "if", "editor", "else", "editor", "try", ":", "self", ".", "_editor", ".", "offset_calculator", ".", "pic_infos_available", ".", "connect", "(", "self", ".", "_update", ")", "except", "AttributeError", ":", "pass" ]
Prints non_fluents states actions interms and rewards for given horizon .
def _render_batch ( self , non_fluents : NonFluents , states : Fluents , actions : Fluents , interms : Fluents , rewards : np . array , horizon : Optional [ int ] = None ) -> None : if horizon is None : horizon = len ( states [ 0 ] [ 1 ] ) self . _render_round_init ( horizon , non_fluents ) for t in range ( horizon ) : s = [ ( s [ 0 ] , s [ 1 ] [ t ] ) for s in states ] f = [ ( f [ 0 ] , f [ 1 ] [ t ] ) for f in interms ] a = [ ( a [ 0 ] , a [ 1 ] [ t ] ) for a in actions ] r = rewards [ t ] self . _render_timestep ( t , s , a , f , r ) self . _render_round_end ( rewards )
12,380
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L67-L91
[ "def", "require_session", "(", "handler", ")", ":", "@", "functools", ".", "wraps", "(", "handler", ")", "async", "def", "decorated", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "request_session_token", "=", "request", ".", "match_info", "[", "'session'", "]", "session", "=", "session_from_request", "(", "request", ")", "if", "not", "session", "or", "request_session_token", "!=", "session", ".", "token", ":", "LOG", ".", "warning", "(", "f\"request for invalid session {request_session_token}\"", ")", "return", "web", ".", "json_response", "(", "data", "=", "{", "'error'", ":", "'bad-token'", ",", "'message'", ":", "f'No such session {request_session_token}'", "}", ",", "status", "=", "404", ")", "return", "await", "handler", "(", "request", ",", "session", ")", "return", "decorated" ]
Prints fluents and rewards for the given timestep t .
def _render_timestep ( self , t : int , s : Fluents , a : Fluents , f : Fluents , r : np . float32 ) -> None : print ( "============================" ) print ( "TIME = {}" . format ( t ) ) print ( "============================" ) fluent_variables = self . _compiler . rddl . action_fluent_variables self . _render_fluent_timestep ( 'action' , a , fluent_variables ) fluent_variables = self . _compiler . rddl . interm_fluent_variables self . _render_fluent_timestep ( 'interms' , f , fluent_variables ) fluent_variables = self . _compiler . rddl . state_fluent_variables self . _render_fluent_timestep ( 'states' , s , fluent_variables ) self . _render_reward ( r )
12,381
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L93-L115
[ "def", "handleHeader", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "==", "'CIMError'", ":", "self", ".", "CIMError", "=", "urllib", ".", "parse", ".", "unquote", "(", "value", ")", "if", "key", "==", "'PGErrorDetail'", ":", "self", ".", "PGErrorDetail", "=", "urllib", ".", "parse", ".", "unquote", "(", "value", ")" ]
Prints fluents of given fluent_type as list of instantiated variables with corresponding values .
def _render_fluent_timestep ( self , fluent_type : str , fluents : Sequence [ Tuple [ str , np . array ] ] , fluent_variables : Sequence [ Tuple [ str , List [ str ] ] ] ) -> None : for fluent_pair , variable_list in zip ( fluents , fluent_variables ) : name , fluent = fluent_pair _ , variables = variable_list print ( name ) fluent = fluent . flatten ( ) for variable , value in zip ( variables , fluent ) : print ( '- {}: {} = {}' . format ( fluent_type , variable , value ) ) print ( )
12,382
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L117-L136
[ "def", "xcorr", "(", "x", ",", "y", ",", "maxlags", ")", ":", "xlen", "=", "len", "(", "x", ")", "ylen", "=", "len", "(", "y", ")", "assert", "xlen", "==", "ylen", "c", "=", "np", ".", "correlate", "(", "x", ",", "y", ",", "mode", "=", "2", ")", "# normalize", "c", "/=", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "x", ",", "x", ")", "*", "np", ".", "dot", "(", "y", ",", "y", ")", ")", "lags", "=", "np", ".", "arange", "(", "-", "maxlags", ",", "maxlags", "+", "1", ")", "c", "=", "c", "[", "xlen", "-", "1", "-", "maxlags", ":", "xlen", "+", "maxlags", "]", "return", "c" ]
Prints reward r .
def _render_reward ( self , r : np . float32 ) -> None : print ( "reward = {:.4f}" . format ( float ( r ) ) ) print ( )
12,383
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L138-L141
[ "def", "libvlc_video_set_subtitle_file", "(", "p_mi", ",", "psz_subtitle", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_subtitle_file'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_subtitle_file'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "ctypes", ".", "c_int", ",", "MediaPlayer", ",", "ctypes", ".", "c_char_p", ")", "return", "f", "(", "p_mi", ",", "psz_subtitle", ")" ]
Prints round init information about horizon and non_fluents .
def _render_round_init ( self , horizon : int , non_fluents : NonFluents ) -> None : print ( '*********************************************************' ) print ( '>>> ROUND INIT, horizon = {}' . format ( horizon ) ) print ( '*********************************************************' ) fluent_variables = self . _compiler . rddl . non_fluent_variables self . _render_fluent_timestep ( 'non-fluents' , non_fluents , fluent_variables )
12,384
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L143-L149
[ "def", "render_category", "(", "category", "=", "''", ",", "template", "=", "None", ")", ":", "# pylint:disable=too-many-return-statements", "# See if this is an aliased path", "redir", "=", "get_redirect", "(", ")", "if", "redir", ":", "return", "redir", "# Forbidden template types", "if", "template", "and", "template", ".", "startswith", "(", "'_'", ")", ":", "raise", "http_error", ".", "Forbidden", "(", "\"Template is private\"", ")", "if", "template", "in", "[", "'entry'", ",", "'error'", "]", ":", "raise", "http_error", ".", "BadRequest", "(", "\"Invalid view requested\"", ")", "if", "category", ":", "# See if there's any entries for the view...", "if", "not", "orm", ".", "select", "(", "e", "for", "e", "in", "model", ".", "Entry", "if", "e", ".", "category", "==", "category", "or", "e", ".", "category", ".", "startswith", "(", "category", "+", "'/'", ")", ")", ":", "raise", "http_error", ".", "NotFound", "(", "\"No such category\"", ")", "if", "not", "template", ":", "template", "=", "Category", "(", "category", ")", ".", "get", "(", "'Index-Template'", ")", "or", "'index'", "tmpl", "=", "map_template", "(", "category", ",", "template", ")", "if", "not", "tmpl", ":", "# this might actually be a malformed category URL", "test_path", "=", "'/'", ".", "join", "(", "(", "category", ",", "template", ")", ")", "if", "category", "else", "template", "logger", ".", "debug", "(", "\"Checking for malformed category %s\"", ",", "test_path", ")", "record", "=", "orm", ".", "select", "(", "e", "for", "e", "in", "model", ".", "Entry", "if", "e", ".", "category", "==", "test_path", ")", ".", "exists", "(", ")", "if", "record", ":", "return", "redirect", "(", "url_for", "(", "'category'", ",", "category", "=", "test_path", ",", "*", "*", "request", ".", "args", ")", ")", "# nope, we just don't know what this is", "raise", "http_error", ".", "NotFound", "(", "\"No such view\"", ")", "view_spec", "=", "view", ".", "parse_view_spec", "(", "request", ".", "args", ")", "view_spec", "[", "'category'", "]", "=", "category", "view_obj", "=", "view", ".", "View", "(", "view_spec", ")", "rendered", ",", "etag", "=", "render_publ_template", "(", "tmpl", ",", "_url_root", "=", "request", ".", "url_root", ",", "category", "=", "Category", "(", "category", ")", ",", "view", "=", "view_obj", ")", "if", "request", ".", "if_none_match", ".", "contains", "(", "etag", ")", ":", "return", "'Not modified'", ",", "304", "return", "rendered", ",", "{", "'Content-Type'", ":", "mime_type", "(", "tmpl", ")", ",", "'ETag'", ":", "etag", "}" ]
Prints round end information about rewards .
def _render_round_end ( self , rewards : np . array ) -> None : print ( "*********************************************************" ) print ( ">>> ROUND END" ) print ( "*********************************************************" ) total_reward = np . sum ( rewards ) print ( "==> Objective value = {}" . format ( total_reward ) ) print ( "==> rewards = {}" . format ( list ( rewards ) ) ) print ( )
12,385
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/generic_visualizer.py#L151-L159
[ "def", "combine_slices", "(", "slice_datasets", ",", "rescale", "=", "None", ")", ":", "if", "len", "(", "slice_datasets", ")", "==", "0", ":", "raise", "DicomImportException", "(", "\"Must provide at least one DICOM dataset\"", ")", "_validate_slices_form_uniform_grid", "(", "slice_datasets", ")", "voxels", "=", "_merge_slice_pixel_arrays", "(", "slice_datasets", ",", "rescale", ")", "transform", "=", "_ijk_to_patient_xyz_transform_matrix", "(", "slice_datasets", ")", "return", "voxels", ",", "transform" ]
Shorten data to fit in the specified model field .
def _truncate_to_field ( model , field_name , value ) : field = model . _meta . get_field ( field_name ) # pylint: disable=protected-access if len ( value ) > field . max_length : midpoint = field . max_length // 2 len_after_midpoint = field . max_length - midpoint first = value [ : midpoint ] sep = '...' last = value [ len ( value ) - len_after_midpoint + len ( sep ) : ] value = sep . join ( [ first , last ] ) return value
12,386
https://github.com/edx/edx-celeryutils/blob/d8745f5f0929ad154fad779a19fbefe7f51e9498/celery_utils/persist_on_failure.py#L45-L61
[ "def", "get_entity_info", "(", "pdb_id", ")", ":", "out", "=", "get_info", "(", "pdb_id", ",", "url_root", "=", "'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='", ")", "out", "=", "to_dict", "(", "out", ")", "return", "remove_at_sign", "(", "out", "[", "'entityInfo'", "]", "[", "'PDB'", "]", ")" ]
If the task fails persist a record of the task .
def on_failure ( self , exc , task_id , args , kwargs , einfo ) : if not FailedTask . objects . filter ( task_id = task_id , datetime_resolved = None ) . exists ( ) : FailedTask . objects . create ( task_name = _truncate_to_field ( FailedTask , 'task_name' , self . name ) , task_id = task_id , # Fixed length UUID: No need to truncate args = args , kwargs = kwargs , exc = _truncate_to_field ( FailedTask , 'exc' , repr ( exc ) ) , ) super ( PersistOnFailureTask , self ) . on_failure ( exc , task_id , args , kwargs , einfo )
12,387
https://github.com/edx/edx-celeryutils/blob/d8745f5f0929ad154fad779a19fbefe7f51e9498/celery_utils/persist_on_failure.py#L22-L34
[ "def", "is_registration_possible", "(", "self", ",", "user_info", ")", ":", "return", "self", ".", "get_accessibility", "(", ")", ".", "is_open", "(", ")", "and", "self", ".", "_registration", ".", "is_open", "(", ")", "and", "self", ".", "is_user_accepted_by_access_control", "(", "user_info", ")" ]
Renders the simulated trajectories for the given batch .
def render ( self , trajectories : Tuple [ NonFluents , Fluents , Fluents , Fluents , np . array ] , batch : Optional [ int ] = None ) -> None : raise NotImplementedError
12,388
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/viz/abstract_visualizer.py#L41-L50
[ "def", "set_editor", "(", "self", ",", "editor", ")", ":", "if", "self", ".", "_editor", "is", "not", "None", ":", "try", ":", "self", ".", "_editor", ".", "offset_calculator", ".", "pic_infos_available", ".", "disconnect", "(", "self", ".", "_update", ")", "except", "(", "AttributeError", ",", "RuntimeError", ",", "ReferenceError", ")", ":", "# see https://github.com/OpenCobolIDE/OpenCobolIDE/issues/89", "pass", "self", ".", "_editor", "=", "weakref", ".", "proxy", "(", "editor", ")", "if", "editor", "else", "editor", "try", ":", "self", ".", "_editor", ".", "offset_calculator", ".", "pic_infos_available", ".", "connect", "(", "self", ".", "_update", ")", "except", "AttributeError", ":", "pass" ]
Build the distribution of distinct values
def distribution ( self , limit = 1024 ) : res = self . _qexec ( "%s, count(*) as __cnt" % self . name ( ) , group = "%s" % self . name ( ) , order = "__cnt DESC LIMIT %d" % limit ) dist = [ ] cnt = self . _table . size ( ) for i , r in enumerate ( res ) : dist . append ( list ( r ) + [ i , r [ 1 ] / float ( cnt ) ] ) self . _distribution = pd . DataFrame ( dist , columns = [ "value" , "cnt" , "r" , "fraction" ] ) self . _distribution . index = self . _distribution . r return self . _distribution
12,389
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/types.py#L91-L105
[ "def", "save", "(", "self", ",", "segids", ",", "filepath", "=", "None", ",", "file_format", "=", "'ply'", ")", ":", "if", "type", "(", "segids", ")", "!=", "list", ":", "segids", "=", "[", "segids", "]", "meshdata", "=", "self", ".", "get", "(", "segids", ")", "if", "not", "filepath", ":", "filepath", "=", "str", "(", "segids", "[", "0", "]", ")", "+", "\".\"", "+", "file_format", "if", "len", "(", "segids", ")", ">", "1", ":", "filepath", "=", "\"{}_{}.{}\"", ".", "format", "(", "segids", "[", "0", "]", ",", "segids", "[", "-", "1", "]", ",", "file_format", ")", "if", "file_format", "==", "'obj'", ":", "objdata", "=", "mesh_to_obj", "(", "meshdata", ",", "progress", "=", "self", ".", "vol", ".", "progress", ")", "objdata", "=", "'\\n'", ".", "join", "(", "objdata", ")", "+", "'\\n'", "data", "=", "objdata", ".", "encode", "(", "'utf8'", ")", "elif", "file_format", "==", "'ply'", ":", "data", "=", "mesh_to_ply", "(", "meshdata", ")", "else", ":", "raise", "NotImplementedError", "(", "'Only .obj and .ply is currently supported.'", ")", "with", "open", "(", "filepath", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")" ]
Parse distribution string
def parse ( self , name ) : name = name . strip ( ) groups = self . _parseFedora ( name ) if groups : self . _signature = DistributionNameSignature ( "Fedora" , groups . group ( 1 ) ) return self raise ValueError ( "Distribution name '%s' not recognized" % name )
12,390
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/distribution/distributionnameparser.py#L52-L64
[ "def", "namer", "(", "cls", ",", "imageUrl", ",", "pageUrl", ")", ":", "start", "=", "''", "tsmatch", "=", "compile", "(", "r'/(\\d+)-'", ")", ".", "search", "(", "imageUrl", ")", "if", "tsmatch", ":", "start", "=", "datetime", ".", "utcfromtimestamp", "(", "int", "(", "tsmatch", ".", "group", "(", "1", ")", ")", ")", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "else", ":", "# There were only chapter 1, page 4 and 5 not matching when writing", "# this...", "start", "=", "'2015-04-11x'", "return", "start", "+", "\"-\"", "+", "pageUrl", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "-", "1", "]" ]
Get access token info .
def get_token ( url : str , scopes : str , credentials_dir : str ) -> dict : tokens . configure ( url = url , dir = credentials_dir ) tokens . manage ( 'lizzy' , [ scopes ] ) tokens . start ( ) return tokens . get ( 'lizzy' )
12,391
https://github.com/zalando-stups/lizzy-client/blob/0af9733ca5a25ebd0a9dc1453f2a7592efcee56a/lizzy_client/token.py#L4-L13
[ "def", "set_cdn_log_retention", "(", "self", ",", "container", ",", "enabled", ")", ":", "headers", "=", "{", "\"X-Log-Retention\"", ":", "\"%s\"", "%", "enabled", "}", "self", ".", "api", ".", "cdn_request", "(", "\"/%s\"", "%", "utils", ".", "get_name", "(", "container", ")", ",", "method", "=", "\"PUT\"", ",", "headers", "=", "headers", ")" ]
Setting various configuration options
def config ( config , fork_name = "" , origin_name = "" ) : state = read ( config . configfile ) any_set = False if fork_name : update ( config . configfile , { "FORK_NAME" : fork_name } ) success_out ( "fork-name set to: {}" . format ( fork_name ) ) any_set = True if origin_name : update ( config . configfile , { "ORIGIN_NAME" : origin_name } ) success_out ( "origin-name set to: {}" . format ( origin_name ) ) any_set = True if not any_set : info_out ( "Fork-name: {}" . format ( state [ "FORK_NAME" ] ) )
12,392
https://github.com/peterbe/gg/blob/2aace5bdb4a9b1cb65bea717784edf54c63b7bad/gg/builtins/config.py#L22-L35
[ "def", "start_transmit", "(", "self", ",", "blocking", "=", "False", ",", "start_packet_groups", "=", "True", ",", "*", "ports", ")", ":", "port_list", "=", "self", ".", "set_ports_list", "(", "*", "ports", ")", "if", "start_packet_groups", ":", "port_list_for_packet_groups", "=", "self", ".", "ports", ".", "values", "(", ")", "port_list_for_packet_groups", "=", "self", ".", "set_ports_list", "(", "*", "port_list_for_packet_groups", ")", "self", ".", "api", ".", "call_rc", "(", "'ixClearTimeStamp {}'", ".", "format", "(", "port_list_for_packet_groups", ")", ")", "self", ".", "api", ".", "call_rc", "(", "'ixStartPacketGroups {}'", ".", "format", "(", "port_list_for_packet_groups", ")", ")", "self", ".", "api", ".", "call_rc", "(", "'ixStartTransmit {}'", ".", "format", "(", "port_list", ")", ")", "time", ".", "sleep", "(", "0.2", ")", "if", "blocking", ":", "self", ".", "wait_transmit", "(", "*", "ports", ")" ]
Parameterize the eit instance by supplying one SIP spectrum and the area to apply to .
def set_area_to_sip_signature ( self , xmin , xmax , zmin , zmax , spectrum ) : assert isinstance ( spectrum , ( sip_response , sip_response2 ) ) assert np . all ( self . frequencies == spectrum . frequencies ) for frequency , rmag , rpha in zip ( self . frequencies , spectrum . rmag , spectrum . rpha ) : td = self . tds [ frequency ] pidm , pidp = td . a [ 'forward_model' ] td . parman . modify_area ( pidm , xmin , xmax , zmin , zmax , rmag ) td . parman . modify_area ( pidp , xmin , xmax , zmin , zmax , rpha )
12,393
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L163-L188
[ "def", "num_workers", "(", "self", ")", ":", "size", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXKVStoreGetGroupSize", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "size", ")", ")", ")", "return", "size", ".", "value" ]
Add homogeneous models to one or all tomodirs . Register those as forward models
def add_homogeneous_model ( self , magnitude , phase = 0 , frequency = None ) : if frequency is None : frequencies = self . frequencies else : assert isinstance ( frequency , Number ) frequencies = [ frequency , ] for freq in frequencies : pidm , pidp = self . tds [ freq ] . add_homogeneous_model ( magnitude , phase ) self . a [ 'forward_rmag' ] [ freq ] = pidm self . a [ 'forward_rpha' ] [ freq ] = pidp
12,394
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L195-L218
[ "def", "point_line_distance", "(", "point", ",", "start", ",", "end", ")", ":", "if", "start", "==", "end", ":", "return", "distance", "(", "point", ",", "start", ")", "else", ":", "un_dist", "=", "abs", "(", "(", "end", ".", "lat", "-", "start", ".", "lat", ")", "*", "(", "start", ".", "lon", "-", "point", ".", "lon", ")", "-", "(", "start", ".", "lat", "-", "point", ".", "lat", ")", "*", "(", "end", ".", "lon", "-", "start", ".", "lon", ")", ")", "n_dist", "=", "sqrt", "(", "(", "end", ".", "lat", "-", "start", ".", "lat", ")", "**", "2", "+", "(", "end", ".", "lon", "-", "start", ".", "lon", ")", "**", "2", ")", "if", "n_dist", "==", "0", ":", "return", "0", "else", ":", "return", "un_dist", "/", "n_dist" ]
Set the global crtomo_cfg for all frequencies
def apply_crtomo_cfg ( self ) : for key in sorted ( self . tds . keys ( ) ) : self . tds [ key ] . crtomo_cfg = self . crtomo_cfg . copy ( )
12,395
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L273-L277
[ "def", "message", "(", "self", ",", "assistant_id", ",", "session_id", ",", "input", "=", "None", ",", "context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "assistant_id", "is", "None", ":", "raise", "ValueError", "(", "'assistant_id must be provided'", ")", "if", "session_id", "is", "None", ":", "raise", "ValueError", "(", "'session_id must be provided'", ")", "if", "input", "is", "not", "None", ":", "input", "=", "self", ".", "_convert_model", "(", "input", ",", "MessageInput", ")", "if", "context", "is", "not", "None", ":", "context", "=", "self", ".", "_convert_model", "(", "context", ",", "MessageContext", ")", "headers", "=", "{", "}", "if", "'headers'", "in", "kwargs", ":", "headers", ".", "update", "(", "kwargs", ".", "get", "(", "'headers'", ")", ")", "sdk_headers", "=", "get_sdk_headers", "(", "'conversation'", ",", "'V2'", ",", "'message'", ")", "headers", ".", "update", "(", "sdk_headers", ")", "params", "=", "{", "'version'", ":", "self", ".", "version", "}", "data", "=", "{", "'input'", ":", "input", ",", "'context'", ":", "context", "}", "url", "=", "'/v2/assistants/{0}/sessions/{1}/message'", ".", "format", "(", "*", "self", ".", "_encode_path_vars", "(", "assistant_id", ",", "session_id", ")", ")", "response", "=", "self", ".", "request", "(", "method", "=", "'POST'", ",", "url", "=", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "json", "=", "data", ",", "accept_json", "=", "True", ")", "return", "response" ]
Set the global noise_model for all frequencies
def apply_noise_models ( self ) : for key in sorted ( self . tds . keys ( ) ) : self . tds [ key ] . noise_model = self . noise_model
12,396
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L279-L283
[ "def", "get_container_instance_logs", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "container_group_name", ",", "container_name", "=", "None", ")", ":", "if", "container_name", "is", "None", ":", "container_name", "=", "container_group_name", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourcegroups/'", ",", "resource_group", ",", "'/providers/Microsoft.ContainerInstance/ContainerGroups/'", ",", "container_group_name", ",", "'/containers/'", ",", "container_name", ",", "'/logs?api-version='", ",", "CONTAINER_API", "]", ")", "return", "do_get", "(", "endpoint", ",", "access_token", ")" ]
Given an sEIT inversion directory load inversion results and store the corresponding parameter ids in self . assignments
def load_inversion_results ( self , sipdir ) : # load frequencies and initialize tomodir objects for all frequencies frequency_file = sipdir + os . sep + 'frequencies.dat' frequencies = np . loadtxt ( frequency_file ) self . _init_frequencies ( frequencies ) # cycle through all tomodirs on disc and load the data for nr , ( frequency_key , item ) in enumerate ( sorted ( self . tds . items ( ) ) ) : for label in ( 'rmag' , 'rpha' , 'cre' , 'cim' ) : if label not in self . assigments : self . a [ label ] = { } tdir = sipdir + os . sep + 'invmod' + os . sep + '{:02}_{:.6f}' . format ( nr , frequency_key ) + os . sep rmag_file = sorted ( glob ( tdir + 'inv/*.mag' ) ) [ - 1 ] rmag_data = np . loadtxt ( rmag_file , skiprows = 1 ) [ : , 2 ] pid_rmag = item . parman . add_data ( rmag_data ) self . a [ 'rmag' ] [ frequency_key ] = pid_rmag rpha_file = sorted ( glob ( tdir + 'inv/*.pha' ) ) [ - 1 ] rpha_data = np . loadtxt ( rpha_file , skiprows = 1 ) [ : , 2 ] pid_rpha = item . parman . add_data ( rpha_data ) self . a [ 'rpha' ] [ frequency_key ] = pid_rpha sigma_file = sorted ( glob ( tdir + 'inv/*.sig' ) ) [ - 1 ] sigma_data = np . loadtxt ( sigma_file , skiprows = 1 ) pid_cre = item . parman . add_data ( sigma_data [ : , 0 ] ) pid_cim = item . parman . add_data ( sigma_data [ : , 1 ] ) self . a [ 'cre' ] [ frequency_key ] = pid_cre self . a [ 'cim' ] [ frequency_key ] = pid_cim
12,397
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L305-L341
[ "def", "unquote", "(", "str", ")", ":", "if", "len", "(", "str", ")", ">", "1", ":", "if", "str", ".", "startswith", "(", "'\"'", ")", "and", "str", ".", "endswith", "(", "'\"'", ")", ":", "return", "str", "[", "1", ":", "-", "1", "]", ".", "replace", "(", "'\\\\\\\\'", ",", "'\\\\'", ")", ".", "replace", "(", "'\\\\\"'", ",", "'\"'", ")", "if", "str", ".", "startswith", "(", "'<'", ")", "and", "str", ".", "endswith", "(", "'>'", ")", ":", "return", "str", "[", "1", ":", "-", "1", "]", "return", "str" ]
Create plots of the forward models
def plot_forward_models ( self , maglim = None , phalim = None , * * kwargs ) : return_dict = { } N = len ( self . frequencies ) nrx = min ( N , 4 ) nrz = int ( np . ceil ( N / nrx ) ) for index , key , limits in zip ( ( 0 , 1 ) , ( 'rmag' , 'rpha' ) , ( maglim , phalim ) ) : if limits is None : cbmin = None cbmax = None else : cbmin = limits [ 0 ] cbmax = limits [ 1 ] fig , axes = plt . subplots ( nrz , nrx , figsize = ( 16 / 2.54 , nrz * 3 / 2.54 ) , sharex = True , sharey = True , ) for ax in axes . flat : ax . set_visible ( False ) for ax , frequency in zip ( axes . flat , self . frequencies ) : ax . set_visible ( True ) td = self . tds [ frequency ] pids = td . a [ 'forward_model' ] td . plot . plot_elements_to_ax ( pids [ index ] , ax = ax , plot_colorbar = True , cbposition = 'horizontal' , cbmin = cbmin , cbmax = cbmax , * * kwargs ) for ax in axes [ 0 : - 1 , : ] . flat : ax . set_xlabel ( '' ) for ax in axes [ : , 1 : ] . flat : ax . set_ylabel ( '' ) fig . tight_layout ( ) return_dict [ key ] = { 'fig' : fig , 'axes' : axes , } return return_dict
12,398
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L402-L460
[ "def", "_ParseAccountsData", "(", "self", ",", "account_data", ")", ":", "if", "not", "account_data", ":", "return", "{", "}", "lines", "=", "[", "line", "for", "line", "in", "account_data", ".", "splitlines", "(", ")", "if", "line", "]", "user_map", "=", "{", "}", "for", "line", "in", "lines", ":", "if", "not", "all", "(", "ord", "(", "c", ")", "<", "128", "for", "c", "in", "line", ")", ":", "self", ".", "logger", ".", "info", "(", "'SSH key contains non-ascii character: %s.'", ",", "line", ")", "continue", "split_line", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "split_line", ")", "!=", "2", ":", "self", ".", "logger", ".", "info", "(", "'SSH key is not a complete entry: %s.'", ",", "split_line", ")", "continue", "user", ",", "key", "=", "split_line", "if", "self", ".", "_HasExpired", "(", "key", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Expired SSH key for user %s: %s.'", ",", "user", ",", "key", ")", "continue", "if", "user", "not", "in", "user_map", ":", "user_map", "[", "user", "]", "=", "[", "]", "user_map", "[", "user", "]", ".", "append", "(", "key", ")", "logging", ".", "debug", "(", "'User accounts: %s.'", ",", "user_map", ")", "return", "user_map" ]
Add configurations to all tomodirs
def add_to_configs ( self , configs ) : for f , td in self . tds . items ( ) : td . configs . add_to_configs ( configs )
12,399
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/eitManager.py#L462-L472
[ "def", "fit", "(", "self", ",", "x", ")", ":", "assert", "x", ".", "ndim", ">", "1", "self", ".", "data_min_", "=", "np", ".", "min", "(", "x", ",", "axis", "=", "tuple", "(", "range", "(", "x", ".", "ndim", "-", "1", ")", ")", ")", "self", ".", "data_max_", "=", "np", ".", "max", "(", "x", ",", "axis", "=", "tuple", "(", "range", "(", "x", ".", "ndim", "-", "1", ")", ")", ")", "if", "self", ".", "share_knots", ":", "self", ".", "data_min_", "[", ":", "]", "=", "np", ".", "min", "(", "self", ".", "data_min_", ")", "self", ".", "data_max_", "[", ":", "]", "=", "np", ".", "max", "(", "self", ".", "data_max_", ")" ]