query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Fork a child process attached to a pty .
def forkexec_pty ( argv , env = None , size = None ) : child_pid , child_fd = pty . fork ( ) if child_pid == 0 : os . closerange ( 3 , MAXFD ) environ = os . environ . copy ( ) if env is not None : environ . update ( env ) os . execve ( argv [ 0 ] , argv , environ ) if size is None : try : size = get_terminal_size ( 1 ) except Exception : size = ( 80 , 24 ) set_terminal_size ( child_fd , size ) return child_pid , child_fd
4,000
https://github.com/rfk/playitagainsam/blob/897cc8e8ca920a4afb8597b4a345361065a3f108/playitagainsam/util.py#L87-L102
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "base_path", ")", "admin_metadata_fpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\".dtool\"", ",", "\"dtool\"", ")", "with", "open", "(", "admin_metadata_fpath", ")", "as", "fh", ":", "admin_metadata", "=", "json", ".", "load", "(", "fh", ")", "http_manifest", "=", "{", "\"admin_metadata\"", ":", "admin_metadata", ",", "\"manifest_url\"", ":", "self", ".", "generate_url", "(", "\".dtool/manifest.json\"", ")", ",", "\"readme_url\"", ":", "self", ".", "generate_url", "(", "\"README.yml\"", ")", ",", "\"overlays\"", ":", "self", ".", "generate_overlay_urls", "(", ")", ",", "\"item_urls\"", ":", "self", ".", "generate_item_urls", "(", ")", "}", "return", "bytes", "(", "json", ".", "dumps", "(", "http_manifest", ")", ",", "\"utf-8\"", ")" ]
Get a list of the executables of all ancestor processes .
def get_ancestor_processes ( ) : if not _ANCESTOR_PROCESSES and psutil is not None : proc = psutil . Process ( os . getpid ( ) ) while proc . parent ( ) is not None : try : _ANCESTOR_PROCESSES . append ( proc . parent ( ) . exe ( ) ) proc = proc . parent ( ) except psutil . Error : break return _ANCESTOR_PROCESSES
4,001
https://github.com/rfk/playitagainsam/blob/897cc8e8ca920a4afb8597b4a345361065a3f108/playitagainsam/util.py#L121-L131
[ "def", "create_index", "(", "self", ")", ":", "es", "=", "self", ".", "_init_connection", "(", ")", "if", "not", "es", ".", "indices", ".", "exists", "(", "index", "=", "self", ".", "index", ")", ":", "es", ".", "indices", ".", "create", "(", "index", "=", "self", ".", "index", ",", "body", "=", "self", ".", "settings", ")" ]
Get the user s default shell program .
def get_default_shell ( environ = None , fallback = _UNSPECIFIED ) : if environ is None : environ = os . environ # If the option is specified in the environment, respect it. if "PIAS_OPT_SHELL" in environ : return environ [ "PIAS_OPT_SHELL" ] # Find all candiate shell programs. shells = [ ] for filename in ( environ . get ( "SHELL" ) , "bash" , "sh" ) : if filename is not None : filepath = find_executable ( filename , environ ) if filepath is not None : shells . append ( filepath ) # If one of them is an ancestor process, use that. for ancestor in get_ancestor_processes ( ) : if ancestor in shells : return ancestor # Otherwise use the first option that we found. for shell in shells : return shell # Use an explicit fallback option if given. if fallback is not _UNSPECIFIED : return fallback raise ValueError ( "Could not find a shell" )
4,002
https://github.com/rfk/playitagainsam/blob/897cc8e8ca920a4afb8597b4a345361065a3f108/playitagainsam/util.py#L134-L158
[ "def", "_create_download_failed_message", "(", "exception", ",", "url", ")", ":", "message", "=", "'Failed to download from:\\n{}\\nwith {}:\\n{}'", ".", "format", "(", "url", ",", "exception", ".", "__class__", ".", "__name__", ",", "exception", ")", "if", "_is_temporal_problem", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "requests", ".", "ConnectionError", ")", ":", "message", "+=", "'\\nPlease check your internet connection and try again.'", "else", ":", "message", "+=", "'\\nThere might be a problem in connection or the server failed to process '", "'your request. Please try again.'", "elif", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", ":", "try", ":", "server_message", "=", "''", "for", "elem", "in", "decode_data", "(", "exception", ".", "response", ".", "content", ",", "MimeType", ".", "XML", ")", ":", "if", "'ServiceException'", "in", "elem", ".", "tag", "or", "'Message'", "in", "elem", ".", "tag", ":", "server_message", "+=", "elem", ".", "text", ".", "strip", "(", "'\\n\\t '", ")", "except", "ElementTree", ".", "ParseError", ":", "server_message", "=", "exception", ".", "response", ".", "text", "message", "+=", "'\\nServer response: \"{}\"'", ".", "format", "(", "server_message", ")", "return", "message" ]
Get the user s default terminal program .
def get_default_terminal ( environ = None , fallback = _UNSPECIFIED ) : if environ is None : environ = os . environ # If the option is specified in the environment, respect it. if "PIAS_OPT_TERMINAL" in environ : return environ [ "PIAS_OPT_TERMINAL" ] # Find all candiate terminal programs. terminals = [ ] colorterm = environ . get ( "COLORTERM" ) for filename in ( colorterm , "gnome-terminal" , "konsole" , "xterm" ) : if filename is not None : filepath = find_executable ( filename , environ ) if filepath is not None : terminals . append ( filepath ) # If one of them is an ancestor process, use that. for ancestor in get_ancestor_processes ( ) : if ancestor in terminals : return ancestor # Otherwise use the first option that we found. for term in terminals : return term # Use an explicit fallback option if given. if fallback is not _UNSPECIFIED : return fallback raise ValueError ( "Could not find a terminal" )
4,003
https://github.com/rfk/playitagainsam/blob/897cc8e8ca920a4afb8597b4a345361065a3f108/playitagainsam/util.py#L161-L186
[ "def", "remove_volume", "(", "self", ",", "volume_name", ")", ":", "logger", ".", "info", "(", "\"removing volume '%s'\"", ",", "volume_name", ")", "try", ":", "self", ".", "d", ".", "remove_volume", "(", "volume_name", ")", "except", "APIError", "as", "ex", ":", "if", "ex", ".", "response", ".", "status_code", "==", "requests", ".", "codes", ".", "CONFLICT", ":", "logger", ".", "debug", "(", "\"ignoring a conflict when removing volume %s\"", ",", "volume_name", ")", "else", ":", "raise", "ex" ]
Get the path to the playitagainsam command - line script .
def get_pias_script ( environ = None ) : if os . path . basename ( sys . argv [ 0 ] ) == "pias" : return sys . argv [ 0 ] filepath = find_executable ( "pias" , environ ) if filepath is not None : return filepath filepath = os . path . join ( os . path . dirname ( __file__ ) , "__main__.py" ) # XXX TODO: check if executable if os . path . exists ( filepath ) : return filepath raise RuntimeError ( "Could not locate the pias script." )
4,004
https://github.com/rfk/playitagainsam/blob/897cc8e8ca920a4afb8597b4a345361065a3f108/playitagainsam/util.py#L189-L200
[ "def", "add_worksheet_progress_percentage", "(", "portal", ")", ":", "add_metadata", "(", "portal", ",", "CATALOG_WORKSHEET_LISTING", ",", "\"getProgressPercentage\"", ")", "logger", ".", "info", "(", "\"Reindexing Worksheets ...\"", ")", "query", "=", "dict", "(", "portal_type", "=", "\"Worksheet\"", ")", "brains", "=", "api", ".", "search", "(", "query", ",", "CATALOG_WORKSHEET_LISTING", ")", "total", "=", "len", "(", "brains", ")", "for", "num", ",", "brain", "in", "enumerate", "(", "brains", ")", ":", "if", "num", "%", "100", "==", "0", ":", "logger", ".", "info", "(", "\"Reindexing open Worksheets: {}/{}\"", ".", "format", "(", "num", ",", "total", ")", ")", "worksheet", "=", "api", ".", "get_object", "(", "brain", ")", "worksheet", ".", "reindexObject", "(", ")" ]
search for airwires in eagle board
def airwires ( board , showgui = 0 ) : board = Path ( board ) . expand ( ) . abspath ( ) file_out = tempfile . NamedTemporaryFile ( suffix = '.txt' , delete = 0 ) file_out . close ( ) ulp = ulp_templ . replace ( 'FILE_NAME' , file_out . name ) file_ulp = tempfile . NamedTemporaryFile ( suffix = '.ulp' , delete = 0 ) file_ulp . write ( ulp . encode ( 'utf-8' ) ) file_ulp . close ( ) commands = [ 'run ' + file_ulp . name , 'quit' , ] command_eagle ( board , commands = commands , showgui = showgui ) n = int ( Path ( file_out . name ) . text ( ) ) Path ( file_out . name ) . remove ( ) Path ( file_ulp . name ) . remove ( ) return n
4,005
https://github.com/ponty/eagexp/blob/1dd5108c1d8112cc87d1bda64fa6c2784ccf0ff2/eagexp/airwires.py#L27-L51
[ "def", "classify", "(", "self", ",", "txt", ")", ":", "ranks", "=", "[", "]", "for", "lang", ",", "score", "in", "langid", ".", "rank", "(", "txt", ")", ":", "if", "lang", "in", "self", ".", "preferred_languages", ":", "score", "+=", "self", ".", "preferred_factor", "ranks", ".", "append", "(", "(", "lang", ",", "score", ")", ")", "ranks", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "return", "ranks", "[", "0", "]", "[", "0", "]" ]
Set up tables in SQL
def _initialize ( self , con ) : if self . initialized : return SQLite3Database ( ) . _initialize ( con ) # ASE db initialization cur = con . execute ( 'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"' ) if cur . fetchone ( ) [ 0 ] == 0 : # no reaction table for init_command in init_commands : con . execute ( init_command ) # Create tables con . commit ( ) self . initialized = True
4,006
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cathubsqlite.py#L118-L133
[ "def", "low_rank_approximation", "(", "A", ",", "r", ")", ":", "try", ":", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "A", ",", "full_matrices", "=", "False", ")", "except", "np", ".", "linalg", ".", "LinAlgError", "as", "e", ":", "print", "(", "'Matrix:'", ",", "A", ")", "print", "(", "'Matrix rank:'", ",", "np", ".", "linalg", ".", "matrix_rank", "(", "A", ")", ")", "raise", "Ar", "=", "np", ".", "zeros", "(", "(", "len", "(", "u", ")", ",", "len", "(", "v", ")", ")", ",", "dtype", "=", "u", ".", "dtype", ")", "buf_", "=", "np", ".", "empty_like", "(", "Ar", ")", "sc_vec_", "=", "np", ".", "empty", "(", "(", "v", ".", "shape", "[", "1", "]", ",", ")", ",", "dtype", "=", "v", ".", "dtype", ")", "for", "i", "in", "range", "(", "r", ")", ":", "np", ".", "multiply", "(", "v", "[", "i", "]", ",", "s", "[", "i", "]", ",", "out", "=", "sc_vec_", ")", "np", ".", "outer", "(", "u", "[", ":", ",", "i", "]", ",", "sc_vec_", ",", "out", "=", "buf_", ")", "Ar", "+=", "buf_", "return", "Ar" ]
Write publication info to db
def write_publication ( self , values ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) values = ( values [ 'pub_id' ] , values [ 'title' ] , json . dumps ( values [ 'authors' ] ) , values [ 'journal' ] , values [ 'volume' ] , values [ 'number' ] , values [ 'pages' ] , values [ 'year' ] , values [ 'publisher' ] , values [ 'doi' ] , json . dumps ( values [ 'tags' ] ) ) q = self . default + ',' + ', ' . join ( '?' * len ( values ) ) cur . execute ( 'INSERT OR IGNORE INTO publication VALUES ({})' . format ( q ) , values ) pid = self . get_last_id ( cur , table = 'publication' ) if self . connection is None : con . commit ( ) con . close ( ) return pid
4,007
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cathubsqlite.py#L157-L201
[ "def", "makeEndOfPrdvPfuncCond", "(", "self", ")", ":", "# Get data to construct the end-of-period marginal value function (conditional on next state)", "self", ".", "aNrm_cond", "=", "self", ".", "prepareToCalcEndOfPrdvP", "(", ")", "self", ".", "EndOfPrdvP_cond", "=", "self", ".", "calcEndOfPrdvPcond", "(", ")", "EndOfPrdvPnvrs_cond", "=", "self", ".", "uPinv", "(", "self", ".", "EndOfPrdvP_cond", ")", "# \"decurved\" marginal value", "if", "self", ".", "CubicBool", ":", "EndOfPrdvPP_cond", "=", "self", ".", "calcEndOfPrdvPP", "(", ")", "EndOfPrdvPnvrsP_cond", "=", "EndOfPrdvPP_cond", "*", "self", ".", "uPinvP", "(", "self", ".", "EndOfPrdvP_cond", ")", "# \"decurved\" marginal marginal value", "# Construct the end-of-period marginal value function conditional on the next state.", "if", "self", ".", "CubicBool", ":", "EndOfPrdvPnvrsFunc_cond", "=", "CubicInterp", "(", "self", ".", "aNrm_cond", ",", "EndOfPrdvPnvrs_cond", ",", "EndOfPrdvPnvrsP_cond", ",", "lower_extrap", "=", "True", ")", "else", ":", "EndOfPrdvPnvrsFunc_cond", "=", "LinearInterp", "(", "self", ".", "aNrm_cond", ",", "EndOfPrdvPnvrs_cond", ",", "lower_extrap", "=", "True", ")", "EndofPrdvPfunc_cond", "=", "MargValueFunc", "(", "EndOfPrdvPnvrsFunc_cond", ",", "self", ".", "CRRA", ")", "# \"recurve\" the interpolated marginal value function", "return", "EndofPrdvPfunc_cond" ]
Write reaction info to db file
def write ( self , values , data = None ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) pub_id = values [ 'pub_id' ] ase_ids = values [ 'ase_ids' ] energy_corrections = values [ 'energy_corrections' ] if ase_ids is not None : check_ase_ids ( values , ase_ids ) else : ase_ids = { } values = ( values [ 'chemical_composition' ] , values [ 'surface_composition' ] , values [ 'facet' ] , json . dumps ( values [ 'sites' ] ) , json . dumps ( values [ 'coverages' ] ) , json . dumps ( values [ 'reactants' ] ) , json . dumps ( values [ 'products' ] ) , values [ 'reaction_energy' ] , values [ 'activation_energy' ] , values [ 'dft_code' ] , values [ 'dft_functional' ] , values [ 'username' ] , values [ 'pub_id' ] ) """ Write to reaction table""" q = self . default + ',' + ', ' . join ( '?' * len ( values ) ) cur . execute ( 'INSERT INTO reaction VALUES ({})' . format ( q ) , values ) id = self . get_last_id ( cur ) reaction_structure_values = [ ] """ Write to publication_system and reaction_system tables""" for name , ase_id in ase_ids . items ( ) : if name in energy_corrections : energy_correction = energy_corrections [ name ] else : energy_correction = 0 reaction_structure_values . append ( [ name , energy_correction , ase_id , id ] ) insert_statement = """INSERT OR IGNORE INTO publication_system(ase_id, pub_id) VALUES (?, ?)""" cur . execute ( insert_statement , [ ase_id , pub_id ] ) cur . executemany ( 'INSERT INTO reaction_system VALUES (?, ?, ?, ?)' , reaction_structure_values ) if self . connection is None : con . commit ( ) con . close ( ) return id
4,008
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cathubsqlite.py#L203-L291
[ "def", "Nu_vertical_cylinder", "(", "Pr", ",", "Gr", ",", "L", "=", "None", ",", "D", "=", "None", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "for", "key", ",", "values", "in", "vertical_cylinder_correlations", ".", "items", "(", ")", ":", "if", "values", "[", "4", "]", "or", "all", "(", "(", "L", ",", "D", ")", ")", ":", "methods", ".", "append", "(", "key", ")", "if", "'Popiel & Churchill'", "in", "methods", ":", "methods", ".", "remove", "(", "'Popiel & Churchill'", ")", "methods", ".", "insert", "(", "0", ",", "'Popiel & Churchill'", ")", "elif", "'McAdams, Weiss & Saunders'", "in", "methods", ":", "methods", ".", "remove", "(", "'McAdams, Weiss & Saunders'", ")", "methods", ".", "insert", "(", "0", ",", "'McAdams, Weiss & Saunders'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "in", "vertical_cylinder_correlations", ":", "if", "vertical_cylinder_correlations", "[", "Method", "]", "[", "4", "]", ":", "return", "vertical_cylinder_correlations", "[", "Method", "]", "[", "0", "]", "(", "Pr", "=", "Pr", ",", "Gr", "=", "Gr", ")", "else", ":", "return", "vertical_cylinder_correlations", "[", "Method", "]", "[", "0", "]", "(", "Pr", "=", "Pr", ",", "Gr", "=", "Gr", ",", "L", "=", "L", ",", "D", "=", "D", ")", "else", ":", "raise", "Exception", "(", "\"Correlation name not recognized; see the \"", "\"documentation for the available options.\"", ")" ]
Update reaction info for a selected row
def update ( self , id , values , key_names = 'all' ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) pub_id = values [ 'pub_id' ] ase_ids = values [ 'ase_ids' ] energy_corrections = values [ 'energy_corrections' ] if ase_ids is not None : check_ase_ids ( values , ase_ids ) else : ase_ids = { } key_list , value_list = get_key_value_list ( key_names , values ) N_keys = len ( key_list ) value_strlist = get_value_strlist ( value_list ) execute_str = ', ' . join ( '{}={}' . format ( key_list [ i ] , value_strlist [ i ] ) for i in range ( N_keys ) ) update_command = 'UPDATE reaction SET {} WHERE id = {};' . format ( execute_str , id ) cur . execute ( update_command ) delete_command = 'DELETE from reaction_system WHERE id = {}' . format ( id ) cur . execute ( delete_command ) reaction_structure_values = [ ] for name , ase_id in ase_ids . items ( ) : reaction_structure_values . append ( [ name , energy_corrections . get ( name ) , ase_id , id ] ) insert_statement = """INSERT OR IGNORE INTO publication_system(ase_id, pub_id) VALUES (?, ?)""" cur . execute ( insert_statement , [ ase_id , pub_id ] ) cur . executemany ( 'INSERT INTO reaction_system VALUES (?, ?, ?, ?)' , reaction_structure_values ) if self . connection is None : con . commit ( ) con . close ( ) return id
4,009
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cathubsqlite.py#L293-L351
[ "def", "start_vm", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "vm_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourceGroups/'", ",", "resource_group", ",", "'/providers/Microsoft.Compute/virtualMachines/'", ",", "vm_name", ",", "'/start'", ",", "'?api-version='", ",", "COMP_API", "]", ")", "return", "do_post", "(", "endpoint", ",", "''", ",", "access_token", ")" ]
Get the id of the last written row in table
def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( "SELECT seq FROM sqlite_sequence WHERE name='{0}'" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id
4,010
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cathubsqlite.py#L353-L372
[ "def", "vec_angle", "(", "vec1", ",", "vec2", ")", ":", "# Imports", "import", "numpy", "as", "np", "from", "scipy", "import", "linalg", "as", "spla", "from", ".", ".", "const", "import", "PRM", "# Check shape and equal length", "if", "len", "(", "vec1", ".", "shape", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"'vec1' is not a vector\"", ")", "## end if", "if", "len", "(", "vec2", ".", "shape", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"'vec2' is not a vector\"", ")", "## end if", "if", "vec1", ".", "shape", "[", "0", "]", "!=", "vec2", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Vector lengths are not equal\"", ")", "## end if", "# Check magnitudes", "if", "spla", ".", "norm", "(", "vec1", ")", "<", "PRM", ".", "ZERO_VEC_TOL", ":", "raise", "ValueError", "(", "\"'vec1' norm is too small\"", ")", "## end if", "if", "spla", ".", "norm", "(", "vec2", ")", "<", "PRM", ".", "ZERO_VEC_TOL", ":", "raise", "ValueError", "(", "\"'vec2' norm is too small\"", ")", "## end if", "# Calculate the angle and return. Do in multiple steps to test for", "# possible >1 or <-1 values from numerical precision errors.", "dotp", "=", "np", ".", "dot", "(", "vec1", ",", "vec2", ")", "/", "spla", ".", "norm", "(", "vec1", ")", "/", "spla", ".", "norm", "(", "vec2", ")", "if", "dotp", ">", "1", ":", "angle", "=", "0.", "# pragma: no cover", "elif", "dotp", "<", "-", "1", ":", "angle", "=", "180.", "# pragma: no cover", "else", ":", "angle", "=", "np", ".", "degrees", "(", "np", ".", "arccos", "(", "dotp", ")", ")", "## end if", "return", "angle" ]
read arc line wavelengths from numpy array
def read_wv_master_from_array ( master_table , lines = 'brightest' , debugplot = 0 ) : # protection if lines not in [ 'brightest' , 'all' ] : raise ValueError ( 'Unexpected lines=' + str ( lines ) ) # determine wavelengths according to the number of columns if master_table . ndim == 1 : wv_master = master_table else : wv_master_all = master_table [ : , 0 ] if master_table . shape [ 1 ] == 2 : # assume old format wv_master = np . copy ( wv_master_all ) elif master_table . shape [ 1 ] == 3 : # assume new format if lines == 'brightest' : wv_flag = master_table [ : , 1 ] wv_master = wv_master_all [ np . where ( wv_flag == 1 ) ] else : wv_master = np . copy ( wv_master_all ) else : raise ValueError ( 'Lines_catalog file does not have the ' 'expected number of columns' ) if abs ( debugplot ) >= 10 : print ( "Reading master table from numpy array" ) print ( "wv_master:\n" , wv_master ) return wv_master
4,011
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/__main__.py#L114-L164
[ "def", "_init_rabit", "(", ")", ":", "if", "_LIB", "is", "not", "None", ":", "_LIB", ".", "RabitGetRank", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitGetWorldSize", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitIsDistributed", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitVersionNumber", ".", "restype", "=", "ctypes", ".", "c_int" ]
read arc line wavelengths from external file .
def read_wv_master_file ( wv_master_file , lines = 'brightest' , debugplot = 0 ) : # protection if lines not in [ 'brightest' , 'all' ] : raise ValueError ( 'Unexpected lines=' + str ( lines ) ) # read table from txt file master_table = np . genfromtxt ( wv_master_file ) wv_master = read_wv_master_from_array ( master_table , lines ) if abs ( debugplot ) >= 10 : print ( "Reading master table: " + wv_master_file ) print ( "wv_master:\n" , wv_master ) return wv_master
4,012
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/__main__.py#L167-L205
[ "def", "_init_rabit", "(", ")", ":", "if", "_LIB", "is", "not", "None", ":", "_LIB", ".", "RabitGetRank", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitGetWorldSize", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitIsDistributed", ".", "restype", "=", "ctypes", ".", "c_int", "_LIB", ".", "RabitVersionNumber", ".", "restype", "=", "ctypes", ".", "c_int" ]
Execute wavelength calibration of a spectrum using fixed line peaks .
def wvcal_spectrum ( sp , fxpeaks , poly_degree_wfit , wv_master , wv_ini_search = None , wv_end_search = None , wvmin_useful = None , wvmax_useful = None , geometry = None , debugplot = 0 ) : # check there are enough lines for fit if len ( fxpeaks ) <= poly_degree_wfit : print ( ">>> Warning: not enough lines to fit spectrum" ) return None # spectrum dimension naxis1 = sp . shape [ 0 ] wv_master_range = wv_master [ - 1 ] - wv_master [ 0 ] delta_wv_master_range = 0.20 * wv_master_range if wv_ini_search is None : wv_ini_search = wv_master [ 0 ] - delta_wv_master_range if wv_end_search is None : wv_end_search = wv_master [ - 1 ] + delta_wv_master_range # use channels (pixels from 1 to naxis1) xchannel = fxpeaks + 1.0 # wavelength calibration list_of_wvfeatures = arccalibration ( wv_master = wv_master , xpos_arc = xchannel , naxis1_arc = naxis1 , crpix1 = 1.0 , wv_ini_search = wv_ini_search , wv_end_search = wv_end_search , wvmin_useful = wvmin_useful , wvmax_useful = wvmax_useful , error_xpos_arc = 3 , times_sigma_r = 3.0 , frac_triplets_for_sum = 0.50 , times_sigma_theil_sen = 10.0 , poly_degree_wfit = poly_degree_wfit , times_sigma_polfilt = 10.0 , times_sigma_cook = 10.0 , times_sigma_inclusion = 10.0 , geometry = geometry , debugplot = debugplot ) title = "Wavelength calibration" solution_wv = fit_list_of_wvfeatures ( list_of_wvfeatures = list_of_wvfeatures , naxis1_arc = naxis1 , crpix1 = 1.0 , poly_degree_wfit = poly_degree_wfit , weighted = False , plot_title = title , geometry = geometry , debugplot = debugplot ) if abs ( debugplot ) % 10 != 0 : # final plot with identified lines xplot = np . arange ( 1 , naxis1 + 1 , dtype = float ) ax = ximplotxy ( xplot , sp , title = title , show = False , xlabel = 'pixel (from 1 to NAXIS1)' , ylabel = 'number of counts' , geometry = geometry ) ymin = sp . min ( ) ymax = sp . max ( ) dy = ymax - ymin ymin -= dy / 20. ymax += dy / 20. ax . set_ylim ( [ ymin , ymax ] ) # plot wavelength of each identified line for feature in solution_wv . features : xpos = feature . xpos reference = feature . reference ax . text ( xpos , sp [ int ( xpos + 0.5 ) - 1 ] , str ( reference ) , fontsize = 8 , horizontalalignment = 'center' ) # show plot print ( 'Plot with identified lines' ) pause_debugplot ( 12 , pltshow = True ) # return the wavelength calibration solution return solution_wv
4,013
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/__main__.py#L382-L499
[ "def", "restore_simulation", "(", "directory", ",", "tax_benefit_system", ",", "*", "*", "kwargs", ")", ":", "simulation", "=", "Simulation", "(", "tax_benefit_system", ",", "tax_benefit_system", ".", "instantiate_entities", "(", ")", ")", "entities_dump_dir", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "\"__entities__\"", ")", "for", "population", "in", "simulation", ".", "populations", ".", "values", "(", ")", ":", "if", "population", ".", "entity", ".", "is_person", ":", "continue", "person_count", "=", "_restore_entity", "(", "population", ",", "entities_dump_dir", ")", "for", "population", "in", "simulation", ".", "populations", ".", "values", "(", ")", ":", "if", "not", "population", ".", "entity", ".", "is_person", ":", "continue", "_restore_entity", "(", "population", ",", "entities_dump_dir", ")", "population", ".", "count", "=", "person_count", "variables_to_restore", "=", "(", "variable", "for", "variable", "in", "os", ".", "listdir", "(", "directory", ")", "if", "variable", "!=", "\"__entities__\"", ")", "for", "variable", "in", "variables_to_restore", ":", "_restore_holder", "(", "simulation", ",", "variable", ",", "directory", ")", "return", "simulation" ]
get_thumbnail version that uses aliasses defined in THUMBNAIL_OPTIONS_DICT
def get_thumbnail ( file_ , name ) : options = settings . OPTIONS_DICT [ name ] opt = copy ( options ) geometry = opt . pop ( 'geometry' ) return original_get_thumbnail ( file_ , geometry , * * opt )
4,014
https://github.com/chhantyal/sorl-thumbnail-async/blob/023d20aac79090a691d563dc26f558bb87239811/thumbnail/__init__.py#L9-L17
[ "def", "mod", "(", "self", ")", ":", "return", "math", ".", "sqrt", "(", "self", ".", "x", "**", "2", "+", "self", ".", "y", "**", "2", "+", "self", ".", "z", "**", "2", ")" ]
Return a new bitset class with given name and members .
def bitset ( name , members , base = bases . BitSet , list = False , tuple = False ) : if not name : raise ValueError ( 'empty bitset name: %r' % name ) if not hasattr ( members , '__getitem__' ) or not hasattr ( members , '__len__' ) : raise ValueError ( 'non-sequence bitset members: %r' % members ) if not len ( members ) : raise ValueError ( 'less than one bitset member: %r' % ( members , ) ) if len ( set ( members ) ) != len ( members ) : raise ValueError ( 'bitset members contains duplicates: %r' % ( members , ) ) if not issubclass ( base . __class__ , meta . MemberBitsMeta ) : raise ValueError ( 'base does not subclass bitset.bases: %r' % base ) list = { False : None , True : series . List } . get ( list , list ) tuple = { False : None , True : series . Tuple } . get ( tuple , tuple ) return base . _make_subclass ( name , members , listcls = list , tuplecls = tuple )
4,015
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/__init__.py#L16-L51
[ "def", "spawn", "(", "opts", ",", "conf", ")", ":", "if", "opts", ".", "config", "is", "not", "None", ":", "os", ".", "environ", "[", "\"CALLSIGN_CONFIG_FILE\"", "]", "=", "opts", ".", "config", "sys", ".", "argv", "[", "1", ":", "]", "=", "[", "\"-noy\"", ",", "sibpath", "(", "__file__", ",", "\"callsign.tac\"", ")", ",", "\"--pidfile\"", ",", "conf", "[", "'pidfile'", "]", ",", "\"--logfile\"", ",", "conf", "[", "'logfile'", "]", ",", "]", "twistd", ".", "run", "(", ")" ]
Check permited values of extrapolation .
def _extrapolation ( self , extrapolate ) : modes = [ 'extrapolate' , 'raise' , 'const' , 'border' ] if extrapolate not in modes : msg = 'invalid extrapolation mode {}' . format ( extrapolate ) raise ValueError ( msg ) if extrapolate == 'raise' : self . bounds_error = True self . extrapolate = False else : self . extrapolate = True self . bounds_error = False self . extrapolate_mode = extrapolate
4,016
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/interpolation.py#L104-L120
[ "def", "list", "(", "self", ",", "path", "=", "None", ",", "with_metadata", "=", "False", ",", "include_partitions", "=", "False", ")", ":", "import", "json", "sub_path", "=", "self", ".", "prefix", "+", "'/'", "+", "path", ".", "strip", "(", "'/'", ")", "if", "path", "else", "self", ".", "prefix", "l", "=", "{", "}", "for", "e", "in", "self", ".", "bucket", ".", "list", "(", "sub_path", ")", ":", "path", "=", "e", ".", "name", ".", "replace", "(", "self", ".", "prefix", ",", "''", ",", "1", ")", ".", "strip", "(", "'/'", ")", "if", "path", ".", "startswith", "(", "'_'", ")", "or", "path", ".", "startswith", "(", "'meta'", ")", ":", "continue", "# TODO 'include_partitions' doesn't make any sense outside of ambry", "if", "not", "include_partitions", "and", "path", ".", "count", "(", "'/'", ")", ">", "1", ":", "continue", "# partition files", "if", "with_metadata", ":", "d", "=", "self", ".", "metadata", "(", "path", ")", "if", "d", "and", "'identity'", "in", "d", ":", "d", "[", "'identity'", "]", "=", "json", ".", "loads", "(", "d", "[", "'identity'", "]", ")", "else", ":", "d", "=", "{", "}", "d", "[", "'caches'", "]", "=", "[", "self", ".", "repo_id", "]", "if", "path", ":", "l", "[", "path", "]", "=", "d", "return", "l" ]
increase between samples
def _create_h ( x ) : h = np . zeros_like ( x ) h [ : - 1 ] = x [ 1 : ] - x [ : - 1 ] # border h [ - 1 ] = h [ - 2 ] return h
4,017
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/interpolation.py#L131-L137
[ "def", "list_tables", "(", ")", ":", "tables", "=", "[", "]", "try", ":", "table_list", "=", "DYNAMODB_CONNECTION", ".", "list_tables", "(", ")", "while", "True", ":", "for", "table_name", "in", "table_list", "[", "u'TableNames'", "]", ":", "tables", ".", "append", "(", "get_table", "(", "table_name", ")", ")", "if", "u'LastEvaluatedTableName'", "in", "table_list", ":", "table_list", "=", "DYNAMODB_CONNECTION", ".", "list_tables", "(", "table_list", "[", "u'LastEvaluatedTableName'", "]", ")", "else", ":", "break", "except", "DynamoDBResponseError", "as", "error", ":", "dynamodb_error", "=", "error", ".", "body", "[", "'__type'", "]", ".", "rsplit", "(", "'#'", ",", "1", ")", "[", "1", "]", "if", "dynamodb_error", "==", "'ResourceNotFoundException'", ":", "logger", ".", "error", "(", "'No tables found'", ")", "elif", "dynamodb_error", "==", "'AccessDeniedException'", ":", "logger", ".", "debug", "(", "'Your AWS API keys lack access to listing tables. '", "'That is an issue if you are trying to use regular '", "'expressions in your table configuration.'", ")", "elif", "dynamodb_error", "==", "'UnrecognizedClientException'", ":", "logger", ".", "error", "(", "'Invalid security token. Are your AWS API keys correct?'", ")", "else", ":", "logger", ".", "error", "(", "(", "'Unhandled exception: {0}: {1}. '", "'Please file a bug report at '", "'https://github.com/sebdah/dynamic-dynamodb/issues'", ")", ".", "format", "(", "dynamodb_error", ",", "error", ".", "body", "[", "'message'", "]", ")", ")", "except", "JSONResponseError", "as", "error", ":", "logger", ".", "error", "(", "'Communication error: {0}'", ".", "format", "(", "error", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "tables" ]
Eval polynomial inside bounds .
def _eval ( self , v , in_bounds , der ) : result = np . zeros_like ( v , dtype = 'float' ) x_indices = np . searchsorted ( self . _x , v , side = 'rigth' ) ids = x_indices [ in_bounds ] - 1 u = v [ in_bounds ] - self . _x [ ids ] result [ in_bounds ] = self . _poly_eval ( u , ids , der ) return result
4,018
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/interpolation.py#L146-L153
[ "def", "read_avro", "(", "file_path_or_buffer", ",", "schema", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "file_path_or_buffer", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "file_path_or_buffer", ",", "'rb'", ")", "as", "f", ":", "return", "__file_to_dataframe", "(", "f", ",", "schema", ",", "*", "*", "kwargs", ")", "else", ":", "return", "__file_to_dataframe", "(", "file_path_or_buffer", ",", "schema", ",", "*", "*", "kwargs", ")" ]
Extrapolate result based on extrapolation mode .
def _extrapolate ( self , result , v , below_bounds , above_bounds , der ) : if self . extrapolate_mode == 'const' : fill_b = fill_a = self . fill_value elif self . extrapolate_mode == 'border' : fill_b = self . _poly_eval ( 0 , 0 , der ) fill_a = self . _poly_eval ( 0 , - 1 , der ) elif self . extrapolate_mode == 'extrapolate' : u = v [ above_bounds ] - self . _x [ - 2 ] fill_a = self . _poly_eval ( u , - 2 , der ) u = v [ below_bounds ] - self . _x [ 0 ] fill_b = self . _poly_eval ( u , 0 , der ) else : raise ValueError ( "extrapolation method doesn't exist" ) result [ below_bounds ] = fill_b result [ above_bounds ] = fill_a
4,019
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/interpolation.py#L155-L171
[ "def", "GET", "(", "self", ",", "token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Pulling the session token from an URL param is a workaround for", "# browsers not supporting CORS in the EventSource API.", "if", "token", ":", "orig_session", ",", "_", "=", "cherrypy", ".", "session", ".", "cache", ".", "get", "(", "token", ",", "(", "{", "}", ",", "None", ")", ")", "salt_token", "=", "orig_session", ".", "get", "(", "'token'", ")", "else", ":", "salt_token", "=", "cherrypy", ".", "session", ".", "get", "(", "'token'", ")", "# Manually verify the token", "if", "not", "salt_token", "or", "not", "self", ".", "auth", ".", "get_tok", "(", "salt_token", ")", ":", "raise", "cherrypy", ".", "HTTPError", "(", "401", ")", "# Release the session lock before starting the long-running response", "cherrypy", ".", "session", ".", "release_lock", "(", ")", "# A handler is the server side end of the websocket connection. Each", "# request spawns a new instance of this handler", "handler", "=", "cherrypy", ".", "request", ".", "ws_handler", "def", "event_stream", "(", "handler", ",", "pipe", ")", ":", "'''\n An iterator to return Salt events (and optionally format them)\n '''", "# blocks until send is called on the parent end of this pipe.", "pipe", ".", "recv", "(", ")", "event", "=", "salt", ".", "utils", ".", "event", ".", "get_event", "(", "'master'", ",", "sock_dir", "=", "self", ".", "opts", "[", "'sock_dir'", "]", ",", "transport", "=", "self", ".", "opts", "[", "'transport'", "]", ",", "opts", "=", "self", ".", "opts", ",", "listen", "=", "True", ")", "stream", "=", "event", ".", "iter_events", "(", "full", "=", "True", ",", "auto_reconnect", "=", "True", ")", "SaltInfo", "=", "event_processor", ".", "SaltInfo", "(", "handler", ")", "def", "signal_handler", "(", "signal", ",", "frame", ")", ":", "os", ".", "_exit", "(", "0", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal_handler", ")", "while", "True", ":", "data", "=", "next", "(", "stream", ")", "if", "data", ":", "try", ":", "# work around try to decode catch unicode errors", "if", "'format_events'", "in", "kwargs", ":", "SaltInfo", ".", "process", "(", "data", ",", "salt_token", ",", "self", ".", "opts", ")", "else", ":", "handler", ".", "send", "(", "str", "(", "'data: {0}\\n\\n'", ")", ".", "format", "(", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "data", ")", ")", ",", "# future lint: disable=blacklisted-function", "False", ")", "except", "UnicodeDecodeError", ":", "logger", ".", "error", "(", "\"Error: Salt event has non UTF-8 data:\\n%s\"", ",", "data", ")", "parent_pipe", ",", "child_pipe", "=", "Pipe", "(", ")", "handler", ".", "pipe", "=", "parent_pipe", "handler", ".", "opts", "=", "self", ".", "opts", "# Process to handle asynchronous push to a client.", "# Each GET request causes a process to be kicked off.", "proc", "=", "Process", "(", "target", "=", "event_stream", ",", "args", "=", "(", "handler", ",", "child_pipe", ")", ")", "proc", ".", "start", "(", ")" ]
Check which values are out of bounds .
def _check_bounds ( self , v ) : below_bounds = v < self . _x [ 0 ] above_bounds = v > self . _x [ - 1 ] if self . bounds_error and below_bounds . any ( ) : raise ValueError ( "A value in x_new is below the interpolation " "range." ) if self . bounds_error and above_bounds . any ( ) : raise ValueError ( "A value in x_new is above the interpolation " "range." ) return below_bounds , above_bounds
4,020
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/interpolation.py#L238-L256
[ "def", "augustus", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "augustus", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--species\"", ",", "default", "=", "\"maize\"", ",", "help", "=", "\"Use species model for prediction\"", ")", "p", ".", "add_option", "(", "\"--hintsfile\"", ",", "help", "=", "\"Hint-guided AUGUSTUS\"", ")", "p", ".", "add_option", "(", "\"--nogff3\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Turn --gff3=off\"", ")", "p", ".", "set_home", "(", "\"augustus\"", ")", "p", ".", "set_cpus", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not", "p", ".", "print_help", "(", ")", ")", "fastafile", ",", "=", "args", "cpus", "=", "opts", ".", "cpus", "mhome", "=", "opts", ".", "augustus_home", "gff3", "=", "not", "opts", ".", "nogff3", "suffix", "=", "\".gff3\"", "if", "gff3", "else", "\".out\"", "cfgfile", "=", "op", ".", "join", "(", "mhome", ",", "\"config/extrinsic/extrinsic.M.RM.E.W.cfg\"", ")", "outdir", "=", "mkdtemp", "(", "dir", "=", "\".\"", ")", "fs", "=", "split", "(", "[", "fastafile", ",", "outdir", ",", "str", "(", "cpus", ")", "]", ")", "augustuswrap_params", "=", "partial", "(", "augustuswrap", ",", "species", "=", "opts", ".", "species", ",", "gff3", "=", "gff3", ",", "cfgfile", "=", "cfgfile", ",", "hintsfile", "=", "opts", ".", "hintsfile", ")", "g", "=", "Jobs", "(", "augustuswrap_params", ",", "fs", ".", "names", ")", "g", ".", "run", "(", ")", "gff3files", "=", "[", "x", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "+", "suffix", "for", "x", "in", "fs", ".", "names", "]", "outfile", "=", "fastafile", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "+", "suffix", "FileMerger", "(", "gff3files", ",", "outfile", "=", "outfile", ")", ".", "merge", "(", ")", "shutil", ".", "rmtree", "(", "outdir", ")", "if", "gff3", ":", "from", "jcvi", ".", "annotation", ".", "reformat", "import", "augustus", "as", "reformat_augustus", "reformat_outfile", "=", "outfile", ".", "replace", "(", "\".gff3\"", ",", "\".reformat.gff3\"", ")", "reformat_augustus", "(", "[", "outfile", ",", "\"--outfile={0}\"", ".", "format", "(", "reformat_outfile", ")", "]", ")" ]
Filter spectrum in Fourier space and apply cosine bell .
def filtmask ( sp , fmin = 0.02 , fmax = 0.15 , debugplot = 0 ) : # Fourier filtering xf = np . fft . fftfreq ( sp . size ) yf = np . fft . fft ( sp ) if abs ( debugplot ) in ( 21 , 22 ) : iok = np . where ( xf > 0 ) ximplotxy ( xf [ iok ] , yf [ iok ] . real , plottype = 'loglog' , xlabel = 'frequency' , ylabel = 'power' , title = 'before masking' , debugplot = debugplot ) cut = ( np . abs ( xf ) > fmax ) yf [ cut ] = 0.0 cut = ( np . abs ( xf ) < fmin ) yf [ cut ] = 0.0 if abs ( debugplot ) in ( 21 , 22 ) : iok = np . where ( xf > 0 ) ximplotxy ( xf [ iok ] , yf [ iok ] . real , plottype = 'loglog' , xlabel = 'frequency' , ylabel = 'power' , title = 'after masking' , debugplot = debugplot ) sp_filt = np . fft . ifft ( yf ) . real if abs ( debugplot ) in ( 21 , 22 ) : xdum = np . arange ( 1 , sp_filt . size + 1 ) ximplotxy ( xdum , sp_filt , title = "filtered median spectrum" , debugplot = debugplot ) sp_filtmask = sp_filt * cosinebell ( sp_filt . size , 0.1 ) if abs ( debugplot ) in ( 21 , 22 ) : xdum = np . arange ( 1 , sp_filt . size + 1 ) ximplotxy ( xdum , sp_filtmask , title = "filtered and masked median spectrum" , debugplot = debugplot ) return sp_filtmask
4,021
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/crosscorrelation.py#L24-L80
[ "def", "get_file_location", "(", "self", ",", "volume_id", ")", ":", "url", "=", "(", "\"http://{master_addr}:{master_port}/\"", "\"dir/lookup?volumeId={volume_id}\"", ")", ".", "format", "(", "master_addr", "=", "self", ".", "master_addr", ",", "master_port", "=", "self", ".", "master_port", ",", "volume_id", "=", "volume_id", ")", "data", "=", "json", ".", "loads", "(", "self", ".", "conn", ".", "get_data", "(", "url", ")", ")", "_file_location", "=", "random", ".", "choice", "(", "data", "[", "'locations'", "]", ")", "FileLocation", "=", "namedtuple", "(", "'FileLocation'", ",", "\"public_url url\"", ")", "return", "FileLocation", "(", "_file_location", "[", "'publicUrl'", "]", ",", "_file_location", "[", "'url'", "]", ")" ]
Return a cosine bell spanning n pixels masking a fraction of pixels
def cosinebell ( n , fraction ) : mask = np . ones ( n ) nmasked = int ( fraction * n ) for i in range ( nmasked ) : yval = 0.5 * ( 1 - np . cos ( np . pi * float ( i ) / float ( nmasked ) ) ) mask [ i ] = yval mask [ n - i - 1 ] = yval return mask
4,022
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/crosscorrelation.py#L83-L102
[ "def", "replace_urls", "(", "status", ")", ":", "text", "=", "status", ".", "text", "if", "not", "has_url", "(", "status", ")", ":", "return", "text", "urls", "=", "[", "(", "e", "[", "'indices'", "]", ",", "e", "[", "'expanded_url'", "]", ")", "for", "e", "in", "status", ".", "entities", "[", "'urls'", "]", "]", "urls", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", "[", "0", "]", ",", "reverse", "=", "True", ")", "for", "(", "start", ",", "end", ")", ",", "url", "in", "urls", ":", "text", "=", "text", "[", ":", "start", "]", "+", "url", "+", "text", "[", "end", ":", "]", "return", "text" ]
Convolve a set of lines of known wavelengths and flux .
def convolve_comb_lines ( lines_wave , lines_flux , sigma , crpix1 , crval1 , cdelt1 , naxis1 ) : # generate wavelengths for output spectrum xwave = crval1 + ( np . arange ( naxis1 ) + 1 - crpix1 ) * cdelt1 # initialize output spectrum spectrum = np . zeros ( naxis1 ) # convolve each line for wave , flux in zip ( lines_wave , lines_flux ) : sp_tmp = gauss_box_model ( x = xwave , amplitude = flux , mean = wave , stddev = sigma ) spectrum += sp_tmp return xwave , spectrum
4,023
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/crosscorrelation.py#L105-L147
[ "def", "permutation_entropy", "(", "x", ",", "n", ",", "tau", ")", ":", "PeSeq", "=", "[", "]", "Em", "=", "embed_seq", "(", "x", ",", "tau", ",", "n", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "Em", ")", ")", ":", "r", "=", "[", "]", "z", "=", "[", "]", "for", "j", "in", "range", "(", "0", ",", "len", "(", "Em", "[", "i", "]", ")", ")", ":", "z", ".", "append", "(", "Em", "[", "i", "]", "[", "j", "]", ")", "for", "j", "in", "range", "(", "0", ",", "len", "(", "Em", "[", "i", "]", ")", ")", ":", "z", ".", "sort", "(", ")", "r", ".", "append", "(", "z", ".", "index", "(", "Em", "[", "i", "]", "[", "j", "]", ")", ")", "z", "[", "z", ".", "index", "(", "Em", "[", "i", "]", "[", "j", "]", ")", "]", "=", "-", "1", "PeSeq", ".", "append", "(", "r", ")", "RankMat", "=", "[", "]", "while", "len", "(", "PeSeq", ")", ">", "0", ":", "RankMat", ".", "append", "(", "PeSeq", ".", "count", "(", "PeSeq", "[", "0", "]", ")", ")", "x", "=", "PeSeq", "[", "0", "]", "for", "j", "in", "range", "(", "0", ",", "PeSeq", ".", "count", "(", "PeSeq", "[", "0", "]", ")", ")", ":", "PeSeq", ".", "pop", "(", "PeSeq", ".", "index", "(", "x", ")", ")", "RankMat", "=", "numpy", ".", "array", "(", "RankMat", ")", "RankMat", "=", "numpy", ".", "true_divide", "(", "RankMat", ",", "RankMat", ".", "sum", "(", ")", ")", "EntropyMat", "=", "numpy", ".", "multiply", "(", "numpy", ".", "log2", "(", "RankMat", ")", ",", "RankMat", ")", "PE", "=", "-", "1", "*", "EntropyMat", ".", "sum", "(", ")", "return", "PE" ]
Extract author names out of refextract authors output .
def _split_refextract_authors_str ( authors_str ) : author_seq = ( x . strip ( ) for x in RE_SPLIT_AUTH . split ( authors_str ) if x ) res = [ ] current = '' for author in author_seq : if not isinstance ( author , six . text_type ) : author = six . text_type ( author . decode ( 'utf8' , 'ignore' ) ) # First clean the token. author = re . sub ( r'\(|\)' , '' , author , re . U ) # Names usually start with characters. author = re . sub ( r'^[\W\d]+' , '' , author , re . U ) # Names should end with characters or dot. author = re . sub ( r'[^.\w]+$' , '' , author , re . U ) # If we have initials join them with the previous token. if RE_INITIALS_ONLY . match ( author ) : current += ', ' + author . strip ( ) . replace ( '. ' , '.' ) else : if current : res . append ( current ) current = author # Add last element. if current : res . append ( current ) # Manual filterings that we don't want to add in regular expressions since # it would make them more complex. # * ed might sneak in # * many legacy refs look like 'X. and Somebody E.' # * might miss lowercase initials filters = [ lambda a : a == 'ed' , lambda a : a . startswith ( ',' ) , lambda a : len ( a ) == 1 ] res = [ r for r in res if all ( not f ( r ) for f in filters ) ] return res
4,024
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/references.py#L57-L97
[ "def", "_is_enlargement", "(", "locator", ",", "global_index", ")", ":", "if", "(", "is_list_like", "(", "locator", ")", "and", "not", "is_slice", "(", "locator", ")", "and", "len", "(", "locator", ")", ">", "0", "and", "not", "is_boolean_array", "(", "locator", ")", "and", "(", "isinstance", "(", "locator", ",", "type", "(", "global_index", "[", "0", "]", ")", ")", "and", "locator", "not", "in", "global_index", ")", ")", ":", "n_diff_elems", "=", "len", "(", "pandas", ".", "Index", "(", "locator", ")", ".", "difference", "(", "global_index", ")", ")", "is_enlargement_boolean", "=", "n_diff_elems", ">", "0", "return", "is_enlargement_boolean", "return", "False" ]
Put a value in the publication info of the reference .
def _set_publication_info_field ( self , field_name , value ) : self . _ensure_reference_field ( 'publication_info' , { } ) self . obj [ 'reference' ] [ 'publication_info' ] [ field_name ] = value
4,025
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/references.py#L148-L151
[ "def", "override_env_variables", "(", ")", ":", "env_vars", "=", "(", "\"LOGNAME\"", ",", "\"USER\"", ",", "\"LNAME\"", ",", "\"USERNAME\"", ")", "old", "=", "[", "os", ".", "environ", "[", "v", "]", "if", "v", "in", "os", ".", "environ", "else", "None", "for", "v", "in", "env_vars", "]", "for", "v", "in", "env_vars", ":", "os", ".", "environ", "[", "v", "]", "=", "\"test\"", "yield", "for", "i", ",", "v", "in", "enumerate", "(", "env_vars", ")", ":", "if", "old", "[", "i", "]", ":", "os", ".", "environ", "[", "v", "]", "=", "old", "[", "i", "]" ]
Parse pubnote and populate correct fields .
def set_pubnote ( self , pubnote ) : if 'publication_info' in self . obj . get ( 'reference' , { } ) : self . add_misc ( u'Additional pubnote: {}' . format ( pubnote ) ) return if self . RE_VALID_PUBNOTE . match ( pubnote ) : pubnote = split_pubnote ( pubnote ) pubnote = convert_old_publication_info_to_new ( [ pubnote ] ) [ 0 ] self . _ensure_reference_field ( 'publication_info' , pubnote ) else : self . add_misc ( pubnote )
4,026
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/references.py#L228-L239
[ "def", "delete", "(", "table", ",", "session", ",", "conds", ")", ":", "with", "session", ".", "begin_nested", "(", ")", ":", "archive_conds_list", "=", "_get_conditions_list", "(", "table", ",", "conds", ")", "session", ".", "execute", "(", "sa", ".", "delete", "(", "table", ".", "ArchiveTable", ",", "whereclause", "=", "_get_conditions", "(", "archive_conds_list", ")", ")", ")", "conds_list", "=", "_get_conditions_list", "(", "table", ",", "conds", ",", "archive", "=", "False", ")", "session", ".", "execute", "(", "sa", ".", "delete", "(", "table", ",", "whereclause", "=", "_get_conditions", "(", "conds_list", ")", ")", ")" ]
Add unique identifier in correct field .
def _add_uid ( self , uid , skip_handle = False ) : # We might add None values from wherever. Kill them here. uid = uid or '' if is_arxiv ( uid ) : self . _ensure_reference_field ( 'arxiv_eprint' , normalize_arxiv ( uid ) ) elif idutils . is_doi ( uid ) : self . _ensure_reference_field ( 'dois' , [ ] ) self . obj [ 'reference' ] [ 'dois' ] . append ( idutils . normalize_doi ( uid ) ) elif idutils . is_handle ( uid ) and not skip_handle : self . _ensure_reference_field ( 'persistent_identifiers' , [ ] ) self . obj [ 'reference' ] [ 'persistent_identifiers' ] . append ( { 'schema' : 'HDL' , 'value' : idutils . normalize_handle ( uid ) , } ) elif idutils . is_urn ( uid ) : self . _ensure_reference_field ( 'persistent_identifiers' , [ ] ) self . obj [ 'reference' ] [ 'persistent_identifiers' ] . append ( { 'schema' : 'URN' , 'value' : uid , } ) elif self . RE_VALID_CNUM . match ( uid ) : self . _ensure_reference_field ( 'publication_info' , { } ) self . obj [ 'reference' ] [ 'publication_info' ] [ 'cnum' ] = uid elif is_cds_url ( uid ) : self . _ensure_reference_field ( 'external_system_identifiers' , [ ] ) self . obj [ 'reference' ] [ 'external_system_identifiers' ] . append ( { 'schema' : 'CDS' , 'value' : extract_cds_id ( uid ) , } ) elif is_ads_url ( uid ) : self . _ensure_reference_field ( 'external_system_identifiers' , [ ] ) self . obj [ 'reference' ] [ 'external_system_identifiers' ] . append ( { 'schema' : 'ADS' , 'value' : extract_ads_id ( uid ) , } ) else : # ``idutils.is_isbn`` is too strict in what it accepts. try : isbn = str ( ISBN ( uid ) ) self . _ensure_reference_field ( 'isbn' , { } ) self . obj [ 'reference' ] [ 'isbn' ] = isbn except Exception : raise ValueError ( 'Unrecognized uid type' )
4,027
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/references.py#L271-L318
[ "def", "_merge_pool_kwargs", "(", "self", ",", "override", ")", ":", "base_pool_kwargs", "=", "self", ".", "connection_pool_kw", ".", "copy", "(", ")", "if", "override", ":", "for", "key", ",", "value", "in", "override", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "try", ":", "del", "base_pool_kwargs", "[", "key", "]", "except", "KeyError", ":", "pass", "else", ":", "base_pool_kwargs", "[", "key", "]", "=", "value", "return", "base_pool_kwargs" ]
Add artid start end pages to publication info of a reference .
def set_page_artid ( self , page_start = None , page_end = None , artid = None ) : if page_end and not page_start : raise ValueError ( 'End_page provided without start_page' ) self . _ensure_reference_field ( 'publication_info' , { } ) publication_info = self . obj [ 'reference' ] [ 'publication_info' ] if page_start : publication_info [ 'page_start' ] = page_start if page_end : publication_info [ 'page_end' ] = page_end if artid : publication_info [ 'artid' ] = artid
4,028
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/references.py#L336-L357
[ "def", "deleteAllProfiles", "(", "self", ")", ":", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "for", "profGroupName", "in", "QtCore", ".", "QSettings", "(", ")", ".", "childGroups", "(", ")", ":", "settings", ".", "remove", "(", "profGroupName", ")" ]
Separate include and exclude globs .
def separate_globs ( globs ) : exclude = [ ] include = [ ] for path in globs : if path . startswith ( "!" ) : exclude . append ( path [ 1 : ] ) else : include . append ( path ) return ( exclude , include )
4,029
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/glob.py#L15-L26
[ "def", "shape", "(", "self", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "nmb_place", "=", "len", "(", "self", ".", "sequences", ")", "nmb_time", "=", "len", "(", "hydpy", ".", "pub", ".", "timegrids", ".", "init", ")", "nmb_others", "=", "collections", ".", "deque", "(", ")", "for", "sequence", "in", "self", ".", "sequences", ".", "values", "(", ")", ":", "nmb_others", ".", "append", "(", "sequence", ".", "shape", ")", "nmb_others_max", "=", "tuple", "(", "numpy", ".", "max", "(", "nmb_others", ",", "axis", "=", "0", ")", ")", "return", "self", ".", "sort_timeplaceentries", "(", "nmb_time", ",", "nmb_place", ")", "+", "nmb_others_max" ]
Parse a glob .
def parse_glob ( path , included ) : files = glob . glob ( path , recursive = True ) array = [ ] for file in files : file = os . path . abspath ( file ) if file not in included : array . append ( file ) included += array return array
4,030
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/glob.py#L30-L42
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", ".", "_project", ")", "self", ".", "_aux", "=", "None", "if", "aux", "is", "not", "None", ":", "self", ".", "_aux", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "aux", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: aux port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "aux", ")", ")" ]
Find the base of a glob .
def find_base ( path ) : result = _pattern . match ( path ) if result : base = result . group ( 0 ) else : base = "./" if base . endswith ( '/' ) or base . endswith ( '\\' ) : return os . path . abspath ( base ) else : return os . path . dirname ( os . path . abspath ( base ) )
4,031
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/glob.py#L49-L61
[ "def", "add_content_ratings", "(", "self", ",", "app_id", ",", "submission_id", ",", "security_code", ")", ":", "url", "=", "self", ".", "url", "(", "'content_ratings'", ")", "%", "app_id", "return", "self", ".", "conn", ".", "fetch", "(", "'POST'", ",", "url", ",", "{", "'submission_id'", ":", "'%s'", "%", "submission_id", ",", "'security_code'", ":", "'%s'", "%", "security_code", "}", ")" ]
Compute wavelengths from channels .
def fun_wv ( xchannel , crpix1 , crval1 , cdelt1 ) : wv = crval1 + ( xchannel - crpix1 ) * cdelt1 return wv
4,032
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/check_wlcalib.py#L109-L133
[ "def", "make_response", "(", "self", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "default_mediatype", "=", "kwargs", ".", "pop", "(", "'fallback_mediatype'", ",", "None", ")", "or", "self", ".", "default_mediatype", "mediatype", "=", "request", ".", "accept_mimetypes", ".", "best_match", "(", "self", ".", "representations", ",", "default", "=", "default_mediatype", ",", ")", "if", "mediatype", "is", "None", ":", "raise", "NotAcceptable", "(", ")", "if", "mediatype", "in", "self", ".", "representations", ":", "resp", "=", "self", ".", "representations", "[", "mediatype", "]", "(", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", "resp", ".", "headers", "[", "'Content-Type'", "]", "=", "mediatype", "return", "resp", "elif", "mediatype", "==", "'text/plain'", ":", "resp", "=", "original_flask_make_response", "(", "str", "(", "data", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", "resp", ".", "headers", "[", "'Content-Type'", "]", "=", "'text/plain'", "return", "resp", "else", ":", "raise", "InternalServerError", "(", ")" ]
Update wavelength calibration polynomial using the residuals fit .
def update_poly_wlcalib ( coeff_ini , coeff_residuals , naxis1_ini , debugplot ) : # define initial wavelength calibration polynomial (use generic # code valid for lists of numpy.arrays) coeff = [ ] for fdum in coeff_ini : coeff . append ( fdum ) poly_ini = np . polynomial . Polynomial ( coeff ) poldeg_wlcalib = len ( coeff ) - 1 # return initial polynomial when there is no need to compute an # updated version if len ( coeff_residuals ) == 0 : return poly_ini . coef else : if np . count_nonzero ( poly_ini . coef ) == 0 : return poly_ini . coef # define polynomial corresponding to the residuals fit carried # out by check_wlcalib_sp() coeff = [ ] for fdum in coeff_residuals : coeff . append ( fdum ) poly_residuals = np . polynomial . Polynomial ( coeff ) # define new points to be fitted xfit = np . zeros ( naxis1_ini ) yfit = np . zeros ( naxis1_ini ) for i in range ( naxis1_ini ) : xfit [ i ] = float ( i + 1 ) wv_tmp = poly_ini ( xfit [ i ] ) yfit [ i ] = wv_tmp + poly_residuals ( wv_tmp ) # fit to get the updated polynomial if len ( xfit ) > poldeg_wlcalib : poldeg_effective = poldeg_wlcalib else : poldeg_effective = len ( xfit ) - 1 poly_updated , ydum = polfit_residuals ( x = xfit , y = yfit , deg = poldeg_effective , debugplot = debugplot ) # return coefficients of updated polynomial return poly_updated . coef
4,033
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/check_wlcalib.py#L620-L693
[ "def", "list", "(", "self", ",", "path", "=", "None", ",", "with_metadata", "=", "False", ",", "include_partitions", "=", "False", ")", ":", "import", "json", "sub_path", "=", "self", ".", "prefix", "+", "'/'", "+", "path", ".", "strip", "(", "'/'", ")", "if", "path", "else", "self", ".", "prefix", "l", "=", "{", "}", "for", "e", "in", "self", ".", "bucket", ".", "list", "(", "sub_path", ")", ":", "path", "=", "e", ".", "name", ".", "replace", "(", "self", ".", "prefix", ",", "''", ",", "1", ")", ".", "strip", "(", "'/'", ")", "if", "path", ".", "startswith", "(", "'_'", ")", "or", "path", ".", "startswith", "(", "'meta'", ")", ":", "continue", "# TODO 'include_partitions' doesn't make any sense outside of ambry", "if", "not", "include_partitions", "and", "path", ".", "count", "(", "'/'", ")", ">", "1", ":", "continue", "# partition files", "if", "with_metadata", ":", "d", "=", "self", ".", "metadata", "(", "path", ")", "if", "d", "and", "'identity'", "in", "d", ":", "d", "[", "'identity'", "]", "=", "json", ".", "loads", "(", "d", "[", "'identity'", "]", ")", "else", ":", "d", "=", "{", "}", "d", "[", "'caches'", "]", "=", "[", "self", ".", "repo_id", "]", "if", "path", ":", "l", "[", "path", "]", "=", "d", "return", "l" ]
Add documentation to generated classes
def generate_docs ( klass ) : import numina . types . datatype attrh = ( 'Attributes\n' '----------\n' ) doc = getattr ( klass , '__doc__' , None ) if doc is None or doc == '' : doc = "%s documentation." % klass . __name__ if len ( klass . stored ( ) ) : doc = doc + '\n\n' + attrh skeys = sorted ( klass . stored ( ) . keys ( ) ) for key in skeys : y = klass . stored ( ) [ key ] if isinstance ( y , Requirement ) : modo = 'requirement' elif isinstance ( y , Result ) : modo = 'product' else : modo = "" if y . type . isproduct ( ) : tipo = y . type . __class__ . __name__ elif isinstance ( y . type , numina . types . datatype . PlainPythonType ) : tipo = y . type . internal_type . __name__ else : tipo = y . type . __class__ . __name__ if y . optional : if y . default_value ( ) : modo = "%s, optional, default=%s" % ( modo , y . default ) else : modo = "%s, optional" % ( modo , ) descript = y . description if descript : field = "%s : %s, %s\n %s\n" % ( key , tipo , modo , descript ) else : field = "%s : %s, %s\n" % ( key , tipo , modo ) doc = doc + field klass . __doc__ = doc return klass
4,034
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/metarecipes.py#L83-L129
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Integer with reversed and inverted bits of n assuming bit length r .
def reinverted ( n , r ) : result = 0 r = 1 << ( r - 1 ) while n : if not n & 1 : result |= r r >>= 1 n >>= 1 if r : result |= ( r << 1 ) - 1 return result
4,035
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/integers.py#L35-L53
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Rank items from sequence in colexicographical order .
def rank ( items , sequence = string . ascii_lowercase ) : items = set ( items ) return sum ( 1 << i for i , s in enumerate ( sequence ) if s in items )
4,036
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/integers.py#L56-L66
[ "def", "_UpdateCampaignDSASetting", "(", "client", ",", "campaign_id", ",", "feed_id", ")", ":", "# Get the CampaignService.", "campaign_service", "=", "client", ".", "GetService", "(", "'CampaignService'", ",", "version", "=", "'v201809'", ")", "selector", "=", "{", "'fields'", ":", "[", "'Id'", ",", "'Settings'", "]", ",", "'predicates'", ":", "[", "{", "'field'", ":", "'Id'", ",", "'operator'", ":", "'EQUALS'", ",", "'values'", ":", "[", "campaign_id", "]", "}", "]", "}", "response", "=", "campaign_service", ".", "get", "(", "selector", ")", "if", "response", "[", "'totalNumEntries'", "]", ":", "campaign", "=", "response", "[", "'entries'", "]", "[", "0", "]", "else", ":", "raise", "ValueError", "(", "'No campaign with ID \"%d\" exists.'", "%", "campaign_id", ")", "if", "not", "campaign", "[", "'settings'", "]", ":", "raise", "ValueError", "(", "'This is not a DSA campaign.'", ")", "dsa_setting", "=", "None", "campaign_settings", "=", "campaign", "[", "'settings'", "]", "for", "setting", "in", "campaign_settings", ":", "if", "setting", "[", "'Setting.Type'", "]", "==", "'DynamicSearchAdsSetting'", ":", "dsa_setting", "=", "setting", "break", "if", "dsa_setting", "is", "None", ":", "raise", "ValueError", "(", "'This is not a DSA campaign.'", ")", "dsa_setting", "[", "'pageFeed'", "]", "=", "{", "'feedIds'", ":", "[", "feed_id", "]", "}", "# Optional: Specify whether only the supplied URLs should be used with your", "# Dynamic Search Ads.", "dsa_setting", "[", "'useSuppliedUrlsOnly'", "]", "=", "True", "operation", "=", "{", "'operand'", ":", "{", "'id'", ":", "campaign_id", ",", "'settings'", ":", "campaign_settings", "}", ",", "'operator'", ":", "'SET'", "}", "campaign_service", ".", "mutate", "(", "[", "operation", "]", ")", "print", "'DSA page feed for campaign ID \"%d\" was updated with feed ID \"%d\".'", "%", "(", "campaign_id", ",", "feed_id", ")" ]
Unrank n from sequence in colexicographical order .
def unrank ( n , sequence = string . ascii_lowercase ) : return list ( map ( sequence . __getitem__ , indexes ( n ) ) )
4,037
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/integers.py#L69-L78
[ "def", "wrap", "(", "vtkdataset", ")", ":", "wrappers", "=", "{", "'vtkUnstructuredGrid'", ":", "vtki", ".", "UnstructuredGrid", ",", "'vtkRectilinearGrid'", ":", "vtki", ".", "RectilinearGrid", ",", "'vtkStructuredGrid'", ":", "vtki", ".", "StructuredGrid", ",", "'vtkPolyData'", ":", "vtki", ".", "PolyData", ",", "'vtkImageData'", ":", "vtki", ".", "UniformGrid", ",", "'vtkStructuredPoints'", ":", "vtki", ".", "UniformGrid", ",", "'vtkMultiBlockDataSet'", ":", "vtki", ".", "MultiBlock", ",", "}", "key", "=", "vtkdataset", ".", "GetClassName", "(", ")", "try", ":", "wrapped", "=", "wrappers", "[", "key", "]", "(", "vtkdataset", ")", "except", ":", "logging", ".", "warning", "(", "'VTK data type ({}) is not currently supported by vtki.'", ".", "format", "(", "key", ")", ")", "return", "vtkdataset", "# if not supported just passes the VTK data object", "return", "wrapped" ]
Estimate the background in a 2D array
def background_estimator ( bdata ) : crowded = False std = numpy . std ( bdata ) std0 = std mean = bdata . mean ( ) while True : prep = len ( bdata ) numpy . clip ( bdata , mean - 3 * std , mean + 3 * std , out = bdata ) if prep == len ( bdata ) : if std < 0.8 * std0 : crowded = True break std = numpy . std ( bdata ) mean = bdata . mean ( ) if crowded : median = numpy . median ( bdata ) mean = bdata . mean ( ) std = bdata . std ( ) return 2.5 * median - 1.5 * mean , std return bdata . mean ( ) , bdata . std ( )
4,038
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/background.py#L37-L61
[ "def", "start", "(", "self", ")", ":", "super", "(", "Syndic", ",", "self", ")", ".", "start", "(", ")", "if", "check_user", "(", "self", ".", "config", "[", "'user'", "]", ")", ":", "self", ".", "action_log_info", "(", "'Starting up'", ")", "self", ".", "verify_hash_type", "(", ")", "try", ":", "self", ".", "syndic", ".", "tune_in", "(", ")", "except", "KeyboardInterrupt", ":", "self", ".", "action_log_info", "(", "'Stopping'", ")", "self", ".", "shutdown", "(", ")" ]
Create a background map with a given mesh size
def create_background_map ( data , bsx , bsy ) : sx , sy = data . shape mx = sx // bsx my = sy // bsy comp = [ ] rms = [ ] # Rows sp = numpy . split ( data , numpy . arange ( bsx , sx , bsx ) , axis = 0 ) for s in sp : # Columns rp = numpy . split ( s , numpy . arange ( bsy , sy , bsy ) , axis = 1 ) for r in rp : b , r = background_estimator ( r ) comp . append ( b ) rms . append ( r ) # Reconstructed image z = numpy . array ( comp ) z . shape = ( mx , my ) # median filter ndfilter . median_filter ( z , size = ( 3 , 3 ) , output = z ) # Interpolate to the original size new = _interpolation ( z , sx , sy , mx , my ) # Interpolate the rms z = numpy . array ( rms ) z . shape = ( mx , my ) nrms = _interpolation ( z , sx , sy , mx , my ) return new , nrms
4,039
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/background.py#L64-L95
[ "def", "readAnnotations", "(", "self", ")", ":", "annot", "=", "self", ".", "read_annotation", "(", ")", "annot", "=", "np", ".", "array", "(", "annot", ")", "if", "(", "annot", ".", "shape", "[", "0", "]", "==", "0", ")", ":", "return", "np", ".", "array", "(", "[", "]", ")", ",", "np", ".", "array", "(", "[", "]", ")", ",", "np", ".", "array", "(", "[", "]", ")", "ann_time", "=", "self", ".", "_get_float", "(", "annot", "[", ":", ",", "0", "]", ")", "ann_text", "=", "annot", "[", ":", ",", "2", "]", "ann_text_out", "=", "[", "\"\"", "for", "x", "in", "range", "(", "len", "(", "annot", "[", ":", ",", "1", "]", ")", ")", "]", "for", "i", "in", "np", ".", "arange", "(", "len", "(", "annot", "[", ":", ",", "1", "]", ")", ")", ":", "ann_text_out", "[", "i", "]", "=", "self", ".", "_convert_string", "(", "ann_text", "[", "i", "]", ")", "if", "annot", "[", "i", ",", "1", "]", "==", "''", ":", "annot", "[", "i", ",", "1", "]", "=", "'-1'", "ann_duration", "=", "self", ".", "_get_float", "(", "annot", "[", ":", ",", "1", "]", ")", "return", "ann_time", "/", "10000000", ",", "ann_duration", ",", "np", ".", "array", "(", "ann_text_out", ")" ]
Return the list of column queries read from the given JSON file .
def _read_columns_file ( f ) : try : columns = json . loads ( open ( f , 'r' ) . read ( ) , object_pairs_hook = collections . OrderedDict ) except Exception as err : raise InvalidColumnsFileError ( "There was an error while reading {0}: {1}" . format ( f , err ) ) # Options are not supported yet: if '__options' in columns : del columns [ '__options' ] return columns
4,040
https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/losser.py#L23-L43
[ "def", "cudaMemcpy_htod", "(", "dst", ",", "src", ",", "count", ")", ":", "status", "=", "_libcudart", ".", "cudaMemcpy", "(", "dst", ",", "src", ",", "ctypes", ".", "c_size_t", "(", "count", ")", ",", "cudaMemcpyHostToDevice", ")", "cudaCheckStatus", "(", "status", ")" ]
Return the given table converted to a CSV string .
def _table_to_csv ( table_ ) : f = cStringIO . StringIO ( ) try : _write_csv ( f , table_ ) return f . getvalue ( ) finally : f . close ( )
4,041
https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/losser.py#L76-L91
[ "def", "save_and_validate_logo", "(", "logo_stream", ",", "logo_filename", ",", "community_id", ")", ":", "cfg", "=", "current_app", ".", "config", "logos_bucket_id", "=", "cfg", "[", "'COMMUNITIES_BUCKET_UUID'", "]", "logo_max_size", "=", "cfg", "[", "'COMMUNITIES_LOGO_MAX_SIZE'", "]", "logos_bucket", "=", "Bucket", ".", "query", ".", "get", "(", "logos_bucket_id", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "logo_filename", ")", "[", "1", "]", "ext", "=", "ext", "[", "1", ":", "]", "if", "ext", ".", "startswith", "(", "'.'", ")", "else", "ext", "logo_stream", ".", "seek", "(", "SEEK_SET", ",", "SEEK_END", ")", "# Seek from beginning to end", "logo_size", "=", "logo_stream", ".", "tell", "(", ")", "if", "logo_size", ">", "logo_max_size", ":", "return", "None", "if", "ext", "in", "cfg", "[", "'COMMUNITIES_LOGO_EXTENSIONS'", "]", ":", "key", "=", "\"{0}/logo.{1}\"", ".", "format", "(", "community_id", ",", "ext", ")", "logo_stream", ".", "seek", "(", "0", ")", "# Rewind the stream to the beginning", "ObjectVersion", ".", "create", "(", "logos_bucket", ",", "key", ",", "stream", "=", "logo_stream", ",", "size", "=", "logo_size", ")", "return", "ext", "else", ":", "return", "None" ]
Query a list of dicts with a list of queries and return a table .
def table ( dicts , columns , csv = False , pretty = False ) : # Optionally read columns from file. if isinstance ( columns , basestring ) : columns = _read_columns_file ( columns ) # Either "pattern" or "pattern_path" (but not both) is allowed in the # columns.json file, but "pattern" gets normalised to "pattern_path" here. for column in columns . values ( ) : if "pattern" in column : assert "pattern_path" not in column , ( 'A column must have either a "pattern" or a "pattern_path"' "but not both" ) column [ "pattern_path" ] = column [ "pattern" ] del column [ "pattern" ] table_ = [ ] for d in dicts : row = collections . OrderedDict ( ) # The row we'll return in the table. for column_title , column_spec in columns . items ( ) : if not column_spec . get ( 'return_multiple_columns' , False ) : row [ column_title ] = query ( dict_ = d , * * column_spec ) else : multiple_columns = query ( dict_ = d , * * column_spec ) for k , v in multiple_columns . items ( ) : row [ k ] = v table_ . append ( row ) if pretty : # Return a pretty-printed string (looks like a nice table when printed # to stdout). return tabulate . tabulate ( table_ , tablefmt = "grid" , headers = "keys" ) elif csv : # Return a string of CSV-formatted text. return _table_to_csv ( table_ ) else : # Return a list of dicts. return table_
4,042
https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/losser.py#L94-L151
[ "def", "new_regid_custom_field", "(", "uwregid", ")", ":", "return", "BridgeCustomField", "(", "field_id", "=", "get_regid_field_id", "(", ")", ",", "name", "=", "BridgeCustomField", ".", "REGID_NAME", ",", "value", "=", "uwregid", ")" ]
Query the given dict with the given pattern path and return the result .
def query ( pattern_path , dict_ , max_length = None , strip = False , case_sensitive = False , unique = False , deduplicate = False , string_transformations = None , hyperlink = False , return_multiple_columns = False ) : if string_transformations is None : string_transformations = [ ] if max_length : string_transformations . append ( lambda x : x [ : max_length ] ) if hyperlink : string_transformations . append ( lambda x : '=HYPERLINK("{0}")' . format ( x ) ) if isinstance ( pattern_path , basestring ) : pattern_path = [ pattern_path ] # Copy the pattern_path because we're going to modify it which can be # unexpected and confusing to user code. original_pattern_path = pattern_path pattern_path = pattern_path [ : ] # We're going to be popping strings off the end of the pattern path # (because Python lists don't come with a convenient pop-from-front method) # so we need the list in reverse order. pattern_path . reverse ( ) result = _process_object ( pattern_path , dict_ , string_transformations = string_transformations , strip = strip , case_sensitive = case_sensitive , return_multiple_columns = return_multiple_columns ) if not result : return None # Empty lists finally get turned into None. elif isinstance ( result , dict ) : return _flatten ( result ) elif len ( result ) == 1 : return result [ 0 ] # One-item lists just get turned into the item. else : if unique : msg = "pattern_path: {0}\n\n" . format ( original_pattern_path ) msg = msg + pprint . pformat ( dict_ ) raise UniqueError ( msg ) if deduplicate : # Deduplicate the list while maintaining order. new_result = [ ] for item in result : if item not in new_result : new_result . append ( item ) result = new_result return result
4,043
https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/losser.py#L154-L218
[ "def", "_SetHeader", "(", "self", ",", "new_values", ")", ":", "row", "=", "self", ".", "row_class", "(", ")", "row", ".", "row", "=", "0", "for", "v", "in", "new_values", ":", "row", "[", "v", "]", "=", "v", "self", ".", "_table", "[", "0", "]", "=", "row" ]
Get reactions from server
def get_reactions ( columns = 'all' , n_results = 20 , write_db = False , * * kwargs ) : if write_db or columns == 'all' : columns = all_columns [ 'reactions' ] queries = { } for key , value in kwargs . items ( ) : key = map_column_names ( key ) if key == 'distinct' : if value in [ True , 'True' , 'true' ] : queries . update ( { key : True } ) continue if isinstance ( value , int ) or isinstance ( value , float ) : queries . update ( { key : value } ) else : queries . update ( { key : '{0}' . format ( value ) } ) subtables = [ ] if write_db : subtables = [ 'reactionSystems' , 'publication' ] else : subtables = [ ] data = query ( table = 'reactions' , subtables = subtables , columns = columns , n_results = n_results , queries = queries ) if not write_db : return data print ( 'Writing result to Reactions.db' ) unique_ids = [ ] for row in data [ 'reactions' ] [ 'edges' ] : with CathubSQLite ( 'Reactions.db' ) as db : row = row [ 'node' ] key_values = { } for key in all_columns [ 'reactions' ] : v = row [ key ] # if isinstance(v, unicode): # v = v.encode('utf-8') try : v = json . loads ( v ) except BaseException : pass key_values [ convert ( key ) ] = v ase_ids = { } energy_corrections = { } for row_rs in row [ 'reactionSystems' ] : if row_rs [ 'name' ] == 'N/A' : continue ase_ids [ row_rs [ 'name' ] ] = row_rs [ 'aseId' ] energy_corrections [ row_rs [ 'name' ] ] = row_rs [ 'energyCorrection' ] if not ase_ids : ase_ids = None energy_corrections = None else : unique_ids += ase_ids . values ( ) key_values [ 'ase_ids' ] = ase_ids key_values [ 'energy_corrections' ] = ase_ids # publications pub_key_values = { } row_p = row [ 'publication' ] for key in all_columns [ 'publications' ] : pub_key_values [ convert ( key ) ] = row_p [ key ] db . write_publication ( pub_key_values ) # reactions and reaction_systems id = db . check ( key_values [ 'chemical_composition' ] , key_values [ 'reaction_energy' ] ) if id is None : id = db . write ( key_values ) else : db . update ( id , key_values ) if ase_ids is not None : # Ase structures with ase . db . connect ( 'Reactions.db' ) as ase_db : con = ase_db . connection cur = con . cursor ( ) cur . execute ( 'SELECT unique_id from systems;' ) unique_ids0 = cur . fetchall ( ) unique_ids0 = [ un [ 0 ] for un in unique_ids0 ] unique_ids = [ un for un in unique_ids if un not in unique_ids0 ] for unique_id in list ( set ( unique_ids ) ) : # if ase_db.count('unique_id={}'.format(unique_id)) == 0: atomsrow = get_atomsrow_by_id ( unique_id ) ase_db . write ( atomsrow ) print ( 'Writing complete!' ) return data
4,044
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/query.py#L136-L231
[ "def", "from_soup_tag", "(", "tag", ")", ":", "sections", "=", "[", "Section", ".", "from_soup_tag", "(", "s", ")", "for", "s", "in", "tag", ".", "findAll", "(", "'section'", ")", "]", "return", "Course", "(", "tag", "[", "'name'", "]", ",", "tag", "[", "'dept'", "]", ",", "int", "(", "tag", "[", "'num'", "]", ")", ",", "tag", "[", "'credmin'", "]", ",", "tag", "[", "'credmax'", "]", ",", "tag", "[", "'gradetype'", "]", ",", "[", "s", "for", "s", "in", "sections", "if", "s", ".", "is_valid", "]", ")" ]
Redirect Recipe log messages to a file .
def create_recipe_file_logger ( logger , logfile , logformat ) : recipe_formatter = logging . Formatter ( logformat ) fh = logging . FileHandler ( logfile , mode = 'w' ) fh . setLevel ( logging . DEBUG ) fh . setFormatter ( recipe_formatter ) return fh
4,045
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/baserun.py#L145-L151
[ "def", "min_mean_cycle", "(", "graph", ",", "weight", ",", "start", "=", "0", ")", ":", "INF", "=", "float", "(", "'inf'", ")", "n", "=", "len", "(", "graph", ")", "# compute distances", "dist", "=", "[", "[", "INF", "]", "*", "n", "]", "prec", "=", "[", "[", "None", "]", "*", "n", "]", "dist", "[", "0", "]", "[", "start", "]", "=", "0", "for", "ell", "in", "range", "(", "1", ",", "n", "+", "1", ")", ":", "dist", ".", "append", "(", "[", "INF", "]", "*", "n", ")", "prec", ".", "append", "(", "[", "None", "]", "*", "n", ")", "for", "node", "in", "range", "(", "n", ")", ":", "for", "neighbor", "in", "graph", "[", "node", "]", ":", "alt", "=", "dist", "[", "ell", "-", "1", "]", "[", "node", "]", "+", "weight", "[", "node", "]", "[", "neighbor", "]", "if", "alt", "<", "dist", "[", "ell", "]", "[", "neighbor", "]", ":", "dist", "[", "ell", "]", "[", "neighbor", "]", "=", "alt", "prec", "[", "ell", "]", "[", "neighbor", "]", "=", "node", "# -- find the optimal value", "valmin", "=", "INF", "argmin", "=", "None", "for", "node", "in", "range", "(", "n", ")", ":", "valmax", "=", "-", "INF", "argmax", "=", "None", "for", "k", "in", "range", "(", "n", ")", ":", "alt", "=", "(", "dist", "[", "n", "]", "[", "node", "]", "-", "dist", "[", "k", "]", "[", "node", "]", ")", "/", "float", "(", "n", "-", "k", ")", "# do not divide by float(n-k) => cycle of minimal total weight", "if", "alt", ">=", "valmax", ":", "# with >= we get simple cycles", "valmax", "=", "alt", "argmax", "=", "k", "if", "argmax", "is", "not", "None", "and", "valmax", "<", "valmin", ":", "valmin", "=", "valmax", "argmin", "=", "(", "node", ",", "argmax", ")", "# -- extract cycle", "if", "valmin", "==", "INF", ":", "# -- there is no cycle", "return", "None", "C", "=", "[", "]", "node", ",", "k", "=", "argmin", "for", "l", "in", "range", "(", "n", ",", "k", ",", "-", "1", ")", ":", "C", ".", "append", "(", "node", ")", "node", "=", "prec", "[", "l", "]", "[", "node", "]", "return", "C", "[", ":", ":", "-", "1", "]", ",", "valmin" ]
Recipe execution mode of numina .
def run_recipe ( recipe , task , rinput , workenv , logger_control ) : # Creating custom logger file recipe_logger = logging . getLogger ( logger_control [ 'default' ] ) if logger_control [ 'enabled' ] : logfile = os . path . join ( workenv . resultsdir , logger_control [ 'logfile' ] ) logformat = logger_control [ 'format' ] _logger . debug ( 'creating file logger %r from Recipe logger' , logfile ) fh = create_recipe_file_logger ( recipe_logger , logfile , logformat ) else : fh = logging . NullHandler ( ) recipe_logger . addHandler ( fh ) with working_directory ( workenv . workdir ) : try : run_recipe_timed ( task , recipe , rinput ) return task finally : recipe_logger . removeHandler ( fh )
4,046
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/baserun.py#L154-L175
[ "def", "get_log_events", "(", "awsclient", ",", "log_group_name", ",", "log_stream_name", ",", "start_ts", "=", "None", ")", ":", "client_logs", "=", "awsclient", ".", "get_client", "(", "'logs'", ")", "request", "=", "{", "'logGroupName'", ":", "log_group_name", ",", "'logStreamName'", ":", "log_stream_name", "}", "if", "start_ts", ":", "request", "[", "'startTime'", "]", "=", "start_ts", "# TODO exhaust the events!", "# TODO use all_pages !", "response", "=", "client_logs", ".", "get_log_events", "(", "*", "*", "request", ")", "if", "'events'", "in", "response", "and", "response", "[", "'events'", "]", ":", "return", "[", "{", "'timestamp'", ":", "e", "[", "'timestamp'", "]", ",", "'message'", ":", "e", "[", "'message'", "]", "}", "for", "e", "in", "response", "[", "'events'", "]", "]" ]
Run the recipe and count the time it takes .
def run_recipe_timed ( task , recipe , rinput ) : _logger . info ( 'running recipe' ) now1 = datetime . datetime . now ( ) task . state = 1 task . time_start = now1 # result = recipe ( rinput ) _logger . info ( 'result: %r' , result ) task . result = result # now2 = datetime . datetime . now ( ) task . state = 2 task . time_end = now2 return task
4,047
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/baserun.py#L178-L192
[ "def", "start_publishing", "(", "mysql_settings", ",", "*", "*", "kwargs", ")", ":", "_logger", ".", "info", "(", "'Start publishing from %s with:\\n%s'", "%", "(", "mysql_settings", ",", "kwargs", ")", ")", "kwargs", ".", "setdefault", "(", "'server_id'", ",", "random", ".", "randint", "(", "1000000000", ",", "4294967295", ")", ")", "kwargs", ".", "setdefault", "(", "'freeze_schema'", ",", "True", ")", "# connect to binlog stream", "stream", "=", "pymysqlreplication", ".", "BinLogStreamReader", "(", "mysql_settings", ",", "only_events", "=", "[", "row_event", ".", "DeleteRowsEvent", ",", "row_event", ".", "UpdateRowsEvent", ",", "row_event", ".", "WriteRowsEvent", "]", ",", "*", "*", "kwargs", ")", "\"\"\":type list[RowsEvent]\"\"\"", "for", "event", "in", "stream", ":", "# ignore non row events", "if", "not", "isinstance", "(", "event", ",", "row_event", ".", "RowsEvent", ")", ":", "continue", "_logger", ".", "debug", "(", "'Send binlog signal \"%s@%s.%s\"'", "%", "(", "event", ".", "__class__", ".", "__name__", ",", "event", ".", "schema", ",", "event", ".", "table", ")", ")", "signals", ".", "binlog_signal", ".", "send", "(", "event", ",", "stream", "=", "stream", ")", "signals", ".", "binlog_position_signal", ".", "send", "(", "(", "stream", ".", "log_file", ",", "stream", ".", "log_pos", ")", ")" ]
Stops the last db_session
def stop_db_session ( exc = None ) : # print('==> Stop session', type(exc)) if has_db_session ( ) : exc_type = None tb = None if exc : exc_type , exc , tb = get_exc_info ( exc ) db_session . __exit__ ( exc_type , exc , tb )
4,048
https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/__init__.py#L47-L58
[ "def", "reqScannerData", "(", "self", ",", "subscription", ":", "ScannerSubscription", ",", "scannerSubscriptionOptions", ":", "List", "[", "TagValue", "]", "=", "None", ",", "scannerSubscriptionFilterOptions", ":", "List", "[", "TagValue", "]", "=", "None", ")", "->", "ScanDataList", ":", "return", "self", ".", "_run", "(", "self", ".", "reqScannerDataAsync", "(", "subscription", ",", "scannerSubscriptionOptions", ",", "scannerSubscriptionFilterOptions", ")", ")" ]
Get the writing path of a file .
def get_path ( dest , file , cwd = None ) : if callable ( dest ) : return dest ( file ) if not cwd : cwd = file . cwd if not os . path . isabs ( dest ) : dest = os . path . join ( cwd , dest ) relative = os . path . relpath ( file . path , file . base ) return os . path . join ( dest , relative )
4,049
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/dest.py#L23-L34
[ "def", "get_correlation_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Correlations\"", ",", "label", "=", "\"tab:parameter_correlations\"", ")", ":", "parameters", ",", "cor", "=", "self", ".", "get_correlations", "(", "chain", "=", "chain", ",", "parameters", "=", "parameters", ")", "return", "self", ".", "_get_2d_latex_table", "(", "parameters", ",", "cor", ",", "caption", ",", "label", ")" ]
Write contents to a local file .
def write_file ( path , contents ) : os . makedirs ( os . path . dirname ( path ) , exist_ok = True ) with open ( path , "w" ) as file : file . write ( contents )
4,050
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/dest.py#L37-L41
[ "def", "AND", "(", "queryArr", ",", "exclude", "=", "None", ")", ":", "assert", "isinstance", "(", "queryArr", ",", "list", ")", ",", "\"provided argument as not a list\"", "assert", "len", "(", "queryArr", ")", ">", "0", ",", "\"queryArr had an empty list\"", "q", "=", "CombinedQuery", "(", ")", "q", ".", "setQueryParam", "(", "\"$and\"", ",", "[", "]", ")", "for", "item", "in", "queryArr", ":", "assert", "isinstance", "(", "item", ",", "(", "CombinedQuery", ",", "BaseQuery", ")", ")", ",", "\"item in the list was not a CombinedQuery or BaseQuery instance\"", "q", ".", "getQuery", "(", ")", "[", "\"$and\"", "]", ".", "append", "(", "item", ".", "getQuery", "(", ")", ")", "if", "exclude", "!=", "None", ":", "assert", "isinstance", "(", "exclude", ",", "(", "CombinedQuery", ",", "BaseQuery", ")", ")", ",", "\"exclude parameter was not a CombinedQuery or BaseQuery instance\"", "q", ".", "setQueryParam", "(", "\"$not\"", ",", "exclude", ".", "getQuery", "(", ")", ")", "return", "q" ]
construct publication id
def get_pub_id ( title , authors , year ) : if len ( title . split ( ' ' ) ) > 1 and title . split ( ' ' ) [ 0 ] . lower ( ) in [ 'the' , 'a' ] : _first_word = title . split ( ' ' ) [ 1 ] . split ( '_' ) [ 0 ] else : _first_word = title . split ( ' ' ) [ 0 ] . split ( '_' ) [ 0 ] pub_id = authors [ 0 ] . split ( ',' ) [ 0 ] . split ( ' ' ) [ 0 ] + _first_word + str ( year ) return pub_id
4,051
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/tools.py#L4-L15
[ "def", "_validate", "(", "self", ")", ":", "for", "key", "in", "self", ":", "if", "key", "not", "in", "DEFAULTS", ":", "raise", "exceptions", ".", "ConfigurationException", "(", "'Unknown configuration key \"{}\"! Valid configuration keys are'", "\" {}\"", ".", "format", "(", "key", ",", "list", "(", "DEFAULTS", ".", "keys", "(", ")", ")", ")", ")", "validate_queues", "(", "self", "[", "\"queues\"", "]", ")", "validate_bindings", "(", "self", "[", "\"bindings\"", "]", ")", "validate_client_properties", "(", "self", "[", "\"client_properties\"", "]", ")" ]
Return a string with all atoms in molecule
def extract_atoms ( molecule ) : if molecule == '' : return molecule try : return float ( molecule ) except BaseException : pass atoms = '' if not molecule [ 0 ] . isalpha ( ) : i = 0 while not molecule [ i ] . isalpha ( ) : i += 1 prefactor = float ( molecule [ : i ] ) if prefactor < 0 : prefactor = abs ( prefactor ) sign = '-' else : sign = '' molecule = molecule [ i : ] else : prefactor = 1 sign = '' for k in range ( len ( molecule ) ) : if molecule [ k ] . isdigit ( ) : for j in range ( int ( molecule [ k ] ) - 1 ) : atoms += molecule [ k - 1 ] else : atoms += molecule [ k ] if prefactor % 1 == 0 : atoms *= int ( prefactor ) elif prefactor % 1 == 0.5 : atoms_sort = sorted ( atoms ) N = len ( atoms ) atoms = '' for n in range ( N ) : for m in range ( int ( prefactor - 0.5 ) ) : atoms += atoms_sort [ n ] if n % 2 == 0 : atoms += atoms_sort [ n ] return sign + '' . join ( sorted ( atoms ) )
4,052
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/tools.py#L18-L59
[ "def", "_read_para_reg_failed", "(", "self", ",", "code", ",", "cbit", ",", "clen", ",", "*", ",", "desc", ",", "length", ",", "version", ")", ":", "_life", "=", "collections", ".", "namedtuple", "(", "'Lifetime'", ",", "(", "'min'", ",", "'max'", ")", ")", "_mint", "=", "self", ".", "_read_unpack", "(", "1", ")", "_maxt", "=", "self", ".", "_read_unpack", "(", "1", ")", "_type", "=", "list", "(", ")", "for", "_", "in", "range", "(", "clen", "-", "2", ")", ":", "_code", "=", "self", ".", "_read_unpack", "(", "1", ")", "_kind", "=", "_REG_FAILURE_TYPE", ".", "get", "(", "_code", ")", "if", "_kind", "is", "None", ":", "if", "0", "<=", "_code", "<=", "200", ":", "_kind", "=", "'Unassigned (IETF Review)'", "elif", "201", "<=", "_code", "<=", "255", ":", "_kind", "=", "'Unassigned (Reserved for Private Use)'", "else", ":", "raise", "ProtocolError", "(", "f'HIPv{version}: [Parano {code}] invalid format'", ")", "_type", ".", "append", "(", "_kind", ")", "reg_failed", "=", "dict", "(", "type", "=", "desc", ",", "critical", "=", "cbit", ",", "length", "=", "clen", ",", "lifetime", "=", "_life", "(", "_mint", ",", "_maxt", ")", ",", "reg_type", "=", "tuple", "(", "_type", ")", ",", ")", "_plen", "=", "length", "-", "clen", "if", "_plen", ":", "self", ".", "_read_fileng", "(", "_plen", ")", "return", "reg_failed" ]
Check the stoichiometry and format of chemical reaction used for folder structure . list of reactants - > list of products
def check_reaction ( reactants , products ) : reactant_list = [ reactant . split ( '@' ) [ 0 ] . strip ( 'star' ) . strip ( 'gas' ) for reactant in reactants ] product_list = [ product . split ( '@' ) [ 0 ] . strip ( 'star' ) . strip ( 'gas' ) for product in products ] reactant_atoms = [ extract_atoms ( reactant ) for reactant in reactant_list ] product_atoms = [ extract_atoms ( product ) for product in product_list ] reactants = add_atoms ( reactant_atoms ) products = add_atoms ( product_atoms ) r_stars = 0 p_stars = 0 for i , a in enumerate ( reactant_atoms ) : if a == '' or 'star' in reactant_list [ i ] : r_stars += 1 elif isinstance ( a , float ) : r_stars += a for a in product_atoms : if a == '' : p_stars += 1 elif isinstance ( a , float ) : p_stars += a assert '' . join ( sorted ( reactants ) ) == '' . join ( sorted ( products ) )
4,053
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/tools.py#L75-L104
[ "def", "result", "(", "self", ",", "raise_exception", "=", "True", ")", ":", "_status", "=", "None", "_exception", "=", "None", "self", ".", "_done_event", ".", "wait", "(", "MAXINT", ")", "# first wait for session global", "if", "self", ".", "is_failed", "(", ")", ":", "# global exception set", "_exception", "=", "self", ".", "_exception", "_status", "=", "enumAsperaControllerStatus", ".", "FAILED", "else", ":", "for", "_session", "in", "self", ".", "_sessions", ".", "values", "(", ")", ":", "_status_tmp", ",", "_exception_tmp", "=", "_session", ".", "wait", "(", ")", "if", "_exception_tmp", "and", "not", "_exception", ":", "_exception", "=", "_exception_tmp", "_status", "=", "_status_tmp", "# Once done waiting, raise an exception if present or return the final status", "if", "_exception", "and", "raise_exception", ":", "raise", "_exception", "return", "_status" ]
Validate keys in a section
def check_section ( node , section , keys = None ) : if keys : for key in keys : if key not in node : raise ValueError ( 'Missing key %r inside %r node' % ( key , section ) )
4,054
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L29-L34
[ "def", "get_free_gpus", "(", "max_procs", "=", "0", ")", ":", "# Try connect with NVIDIA drivers", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "py3nvml", ".", "nvmlInit", "(", ")", "except", ":", "str_", "=", "\"\"\"Couldn't connect to nvml drivers. Check they are installed correctly.\"\"\"", "warnings", ".", "warn", "(", "str_", ",", "RuntimeWarning", ")", "logger", ".", "warn", "(", "str_", ")", "return", "[", "]", "num_gpus", "=", "py3nvml", ".", "nvmlDeviceGetCount", "(", ")", "gpu_free", "=", "[", "False", "]", "*", "num_gpus", "for", "i", "in", "range", "(", "num_gpus", ")", ":", "try", ":", "h", "=", "py3nvml", ".", "nvmlDeviceGetHandleByIndex", "(", "i", ")", "except", ":", "continue", "procs", "=", "try_get_info", "(", "py3nvml", ".", "nvmlDeviceGetComputeRunningProcesses", ",", "h", ",", "[", "'something'", "]", ")", "if", "len", "(", "procs", ")", "<=", "max_procs", ":", "gpu_free", "[", "i", "]", "=", "True", "py3nvml", ".", "nvmlShutdown", "(", ")", "return", "gpu_free" ]
Load the DRPS from a resource file .
def drp_load ( package , resource , confclass = None ) : data = pkgutil . get_data ( package , resource ) return drp_load_data ( package , data , confclass = confclass )
4,055
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L37-L40
[ "def", "add_timeout_callback", "(", "self", ",", "callback", ",", "timeout_milliseconds", ",", "callback_id", "=", "None", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "remove_timeout_callback", "(", "callback_id", ")", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "handle", "=", "None", "def", "remover", "(", ")", ":", "if", "handle", "is", "not", "None", ":", "self", ".", "_loop", ".", "remove_timeout", "(", "handle", ")", "callback_id", "=", "self", ".", "_assign_remover", "(", "callback", ",", "callback_id", ",", "self", ".", "_timeout_callback_removers", ",", "remover", ")", "handle", "=", "self", ".", "_loop", ".", "call_later", "(", "timeout_milliseconds", "/", "1000.0", ",", "wrapper", ")", "return", "callback_id" ]
Load the DRPS from data .
def drp_load_data ( package , data , confclass = None ) : drpdict = yaml . safe_load ( data ) ins = load_instrument ( package , drpdict , confclass = confclass ) if ins . version == 'undefined' : pkg = importlib . import_module ( package ) ins . version = getattr ( pkg , '__version__' , 'undefined' ) return ins
4,056
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L43-L50
[ "def", "_lambda_add_s3_event_source", "(", "awsclient", ",", "arn", ",", "event", ",", "bucket", ",", "prefix", ",", "suffix", ")", ":", "json_data", "=", "{", "'LambdaFunctionConfigurations'", ":", "[", "{", "'LambdaFunctionArn'", ":", "arn", ",", "'Id'", ":", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", ",", "'Events'", ":", "[", "event", "]", "}", "]", "}", "filter_rules", "=", "build_filter_rules", "(", "prefix", ",", "suffix", ")", "json_data", "[", "'LambdaFunctionConfigurations'", "]", "[", "0", "]", ".", "update", "(", "{", "'Filter'", ":", "{", "'Key'", ":", "{", "'FilterRules'", ":", "filter_rules", "}", "}", "}", ")", "# http://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-notification-configuration.html", "# http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html", "client_s3", "=", "awsclient", ".", "get_client", "(", "'s3'", ")", "bucket_configurations", "=", "client_s3", ".", "get_bucket_notification_configuration", "(", "Bucket", "=", "bucket", ")", "bucket_configurations", ".", "pop", "(", "'ResponseMetadata'", ")", "if", "'LambdaFunctionConfigurations'", "in", "bucket_configurations", ":", "bucket_configurations", "[", "'LambdaFunctionConfigurations'", "]", ".", "append", "(", "json_data", "[", "'LambdaFunctionConfigurations'", "]", "[", "0", "]", ")", "else", ":", "bucket_configurations", "[", "'LambdaFunctionConfigurations'", "]", "=", "json_data", "[", "'LambdaFunctionConfigurations'", "]", "response", "=", "client_s3", ".", "put_bucket_notification_configuration", "(", "Bucket", "=", "bucket", ",", "NotificationConfiguration", "=", "bucket_configurations", ")", "# TODO don't return a table, but success state", "return", "json2table", "(", "response", ")" ]
Load all observing modes
def load_modes ( node ) : if isinstance ( node , list ) : values = [ load_mode ( child ) for child in node ] keys = [ mode . key for mode in values ] return dict ( zip ( keys , values ) ) elif isinstance ( node , dict ) : values = { key : load_mode ( child ) for key , child in node } return values else : raise NotImplementedError
4,057
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L53-L63
[ "def", "csrf_protect", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "token", "=", "session", ".", "get", "(", "\"csrf_token\"", ",", "None", ")", "if", "token", "is", "None", "or", "token", "!=", "request", ".", "environ", ".", "get", "(", "\"HTTP_X_CSRFTOKEN\"", ")", ":", "logger", ".", "warning", "(", "\"Received invalid csrf token. Aborting\"", ")", "abort", "(", "403", ")", "# call original request handler", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Load one observing mdode
def load_mode ( node ) : obs_mode = ObservingMode ( ) obs_mode . __dict__ . update ( node ) # handle validator load_mode_validator ( obs_mode , node ) # handle builder load_mode_builder ( obs_mode , node ) # handle tagger: load_mode_tagger ( obs_mode , node ) return obs_mode
4,058
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L65-L79
[ "def", "similarity", "(", "self", ",", "other", ")", ":", "sim", "=", "self", ".", "Similarity", "(", ")", "total", "=", "0.0", "# Calculate similarity ratio for each attribute", "cname", "=", "self", ".", "__class__", ".", "__name__", "for", "aname", ",", "weight", "in", "self", ".", "attributes", ".", "items", "(", ")", ":", "attr1", "=", "getattr", "(", "self", ",", "aname", ",", "None", ")", "attr2", "=", "getattr", "(", "other", ",", "aname", ",", "None", ")", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ")", "# Similarity is ignored if None on both objects", "if", "attr1", "is", "None", "and", "attr2", "is", "None", ":", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "\"attributes are both None\"", ")", "continue", "# Similarity is 0 if either attribute is non-Comparable", "if", "not", "all", "(", "(", "isinstance", "(", "attr1", ",", "Comparable", ")", ",", "isinstance", "(", "attr2", ",", "Comparable", ")", ")", ")", ":", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "\"attributes not Comparable\"", ")", "total", "+=", "weight", "continue", "# Calculate similarity between the attributes", "attr_sim", "=", "(", "attr1", "%", "attr2", ")", "self", ".", "log", "(", "attr1", ",", "attr2", ",", "'%'", ",", "cname", "=", "cname", ",", "aname", "=", "aname", ",", "result", "=", "attr_sim", ")", "# Add the similarity to the total", "sim", "+=", "attr_sim", "*", "weight", "total", "+=", "weight", "# Scale the similarity so the total is 1.0", "if", "total", ":", "sim", "*=", "(", "1.0", "/", "total", ")", "return", "sim" ]
Load observing mode OB tagger
def load_mode_tagger ( obs_mode , node ) : # handle tagger: ntagger = node . get ( 'tagger' ) if ntagger is None : pass elif isinstance ( ntagger , list ) : def full_tagger ( obsres ) : return get_tags_from_full_ob ( obsres , reqtags = ntagger ) obs_mode . tagger = full_tagger elif isinstance ( ntagger , six . string_types ) : # load function obs_mode . tagger = import_object ( ntagger ) else : raise TypeError ( 'tagger must be None, a list or a string' ) return obs_mode
4,059
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L82-L102
[ "def", "getid", "(", "self", ",", "idtype", ")", ":", "memorable_id", "=", "None", "while", "memorable_id", "in", "self", ".", "_ids", ":", "l", "=", "[", "]", "for", "_", "in", "range", "(", "4", ")", ":", "l", ".", "append", "(", "str", "(", "randint", "(", "0", ",", "19", ")", ")", ")", "memorable_id", "=", "''", ".", "join", "(", "l", ")", "self", ".", "_ids", ".", "append", "(", "memorable_id", ")", "return", "idtype", "+", "'-'", "+", "memorable_id" ]
Load observing mode OB builder
def load_mode_builder ( obs_mode , node ) : # Check 'builder' and 'builder_options' nval1 = node . get ( 'builder' ) if nval1 is not None : if isinstance ( nval1 , str ) : # override method newmethod = import_object ( nval1 ) obs_mode . build_ob = newmethod . __get__ ( obs_mode ) else : raise TypeError ( 'builder must be None or a string' ) else : nval2 = node . get ( 'builder_options' ) if nval2 is not None : if isinstance ( nval2 , list ) : for opt_dict in nval2 : if 'result_of' in opt_dict : fields = opt_dict [ 'result_of' ] obs_mode . build_ob_options = ResultOf ( * * fields ) break else : raise TypeError ( 'builder_options must be None or a list' ) return obs_mode
4,060
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L105-L132
[ "def", "jks_pkey_encrypt", "(", "key", ",", "password_str", ")", ":", "password_bytes", "=", "password_str", ".", "encode", "(", "'utf-16be'", ")", "# Java chars are UTF-16BE code units", "iv", "=", "os", ".", "urandom", "(", "20", ")", "key", "=", "bytearray", "(", "key", ")", "xoring", "=", "zip", "(", "key", ",", "_jks_keystream", "(", "iv", ",", "password_bytes", ")", ")", "data", "=", "bytearray", "(", "[", "d", "^", "k", "for", "d", ",", "k", "in", "xoring", "]", ")", "check", "=", "hashlib", ".", "sha1", "(", "bytes", "(", "password_bytes", "+", "key", ")", ")", ".", "digest", "(", ")", "return", "bytes", "(", "iv", "+", "data", "+", "check", ")" ]
Load observing mode validator
def load_mode_validator ( obs_mode , node ) : nval = node . get ( 'validator' ) if nval is None : pass elif isinstance ( nval , str ) : # load function obs_mode . validator = import_object ( nval ) else : raise TypeError ( 'validator must be None or a string' ) return obs_mode
4,061
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L135-L148
[ "def", "pattern", "(", "token", ")", ":", "token", "=", "''", ".", "join", "(", "[", "c", "for", "c", "in", "token", "if", "c", "==", "'?'", "or", "c", ".", "isalnum", "(", ")", "]", ")", "if", "len", "(", "token", ")", "%", "2", "!=", "0", ":", "raise", "ValueError", "(", "\"Missing characters in hex data\"", ")", "regexp", "=", "''", "for", "i", "in", "compat", ".", "xrange", "(", "0", ",", "len", "(", "token", ")", ",", "2", ")", ":", "x", "=", "token", "[", "i", ":", "i", "+", "2", "]", "if", "x", "==", "'??'", ":", "regexp", "+=", "'.'", "elif", "x", "[", "0", "]", "==", "'?'", ":", "f", "=", "'\\\\x%%.1x%s'", "%", "x", "[", "1", "]", "x", "=", "''", ".", "join", "(", "[", "f", "%", "c", "for", "c", "in", "compat", ".", "xrange", "(", "0", ",", "0x10", ")", "]", ")", "regexp", "=", "'%s[%s]'", "%", "(", "regexp", ",", "x", ")", "elif", "x", "[", "1", "]", "==", "'?'", ":", "f", "=", "'\\\\x%s%%.1x'", "%", "x", "[", "0", "]", "x", "=", "''", ".", "join", "(", "[", "f", "%", "c", "for", "c", "in", "compat", ".", "xrange", "(", "0", ",", "0x10", ")", "]", ")", "regexp", "=", "'%s[%s]'", "%", "(", "regexp", ",", "x", ")", "else", ":", "regexp", "=", "'%s\\\\x%s'", "%", "(", "regexp", ",", "x", ")", "return", "regexp" ]
Series from iterable of member iterables .
def frommembers ( cls , members ) : return cls . frombitsets ( map ( cls . BitSet . frommembers , members ) )
4,062
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/series.py#L18-L20
[ "def", "_mmUpdateDutyCycles", "(", "self", ")", ":", "period", "=", "self", ".", "getDutyCyclePeriod", "(", ")", "unionSDRArray", "=", "numpy", ".", "zeros", "(", "self", ".", "getNumColumns", "(", ")", ")", "unionSDRArray", "[", "list", "(", "self", ".", "_mmTraces", "[", "\"unionSDR\"", "]", ".", "data", "[", "-", "1", "]", ")", "]", "=", "1", "self", ".", "_mmData", "[", "\"unionSDRDutyCycle\"", "]", "=", "UnionTemporalPoolerMonitorMixin", ".", "_mmUpdateDutyCyclesHelper", "(", "self", ".", "_mmData", "[", "\"unionSDRDutyCycle\"", "]", ",", "unionSDRArray", ",", "period", ")", "self", ".", "_mmData", "[", "\"persistenceDutyCycle\"", "]", "=", "UnionTemporalPoolerMonitorMixin", ".", "_mmUpdateDutyCyclesHelper", "(", "self", ".", "_mmData", "[", "\"persistenceDutyCycle\"", "]", ",", "self", ".", "_poolingActivation", ",", "period", ")" ]
Series from iterable of boolean evaluable iterables .
def frombools ( cls , bools ) : return cls . frombitsets ( map ( cls . BitSet . frombools , bools ) )
4,063
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/series.py#L23-L25
[ "def", "sfiles_to_event", "(", "sfile_list", ")", ":", "event_list", "=", "[", "]", "sort_list", "=", "[", "(", "readheader", "(", "sfile", ")", ".", "origins", "[", "0", "]", ".", "time", ",", "sfile", ")", "for", "sfile", "in", "sfile_list", "]", "sort_list", ".", "sort", "(", "key", "=", "lambda", "tup", ":", "tup", "[", "0", "]", ")", "sfile_list", "=", "[", "sfile", "[", "1", "]", "for", "sfile", "in", "sort_list", "]", "catalog", "=", "Catalog", "(", ")", "for", "i", ",", "sfile", "in", "enumerate", "(", "sfile_list", ")", ":", "event_list", ".", "append", "(", "(", "i", ",", "sfile", ")", ")", "catalog", ".", "append", "(", "readheader", "(", "sfile", ")", ")", "# Hand off to sister function", "write_event", "(", "catalog", ")", "return", "event_list" ]
Series from binary string arguments .
def frombits ( cls , bits ) : return cls . frombitsets ( map ( cls . BitSet . frombits , bits ) )
4,064
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/series.py#L28-L30
[ "def", "authors_titles_validator", "(", "record", ",", "result", ")", ":", "record_authors", "=", "get_value", "(", "record", ",", "'authors'", ",", "[", "]", ")", "result_authors", "=", "get_value", "(", "result", ",", "'_source.authors'", ",", "[", "]", ")", "author_score", "=", "compute_author_match_score", "(", "record_authors", ",", "result_authors", ")", "title_max_score", "=", "0.0", "record_titles", "=", "get_value", "(", "record", ",", "'titles.title'", ",", "[", "]", ")", "result_titles", "=", "get_value", "(", "result", ",", "'_source.titles.title'", ",", "[", "]", ")", "for", "cartesian_pair", "in", "product", "(", "record_titles", ",", "result_titles", ")", ":", "record_title_tokens", "=", "get_tokenized_title", "(", "cartesian_pair", "[", "0", "]", ")", "result_title_tokens", "=", "get_tokenized_title", "(", "cartesian_pair", "[", "1", "]", ")", "current_title_jaccard", "=", "compute_jaccard_index", "(", "record_title_tokens", ",", "result_title_tokens", ")", "if", "current_title_jaccard", ">", "title_max_score", "and", "current_title_jaccard", ">=", "0.5", ":", "title_max_score", "=", "current_title_jaccard", "return", "(", "author_score", "+", "title_max_score", ")", "/", "2", ">", "0.5" ]
Series from integer rank arguments .
def fromints ( cls , ints ) : return cls . frombitsets ( map ( cls . BitSet . fromint , ints ) )
4,065
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/series.py#L33-L35
[ "def", "hydrate_bundles", "(", "bundles_field", ",", "glob_match_error_behavior", ")", ":", "path_globs_with_match_errors", "=", "[", "pg", ".", "copy", "(", "glob_match_error_behavior", "=", "glob_match_error_behavior", ")", "for", "pg", "in", "bundles_field", ".", "path_globs_list", "]", "snapshot_list", "=", "yield", "[", "Get", "(", "Snapshot", ",", "PathGlobs", ",", "pg", ")", "for", "pg", "in", "path_globs_with_match_errors", "]", "spec_path", "=", "bundles_field", ".", "address", ".", "spec_path", "bundles", "=", "[", "]", "zipped", "=", "zip", "(", "bundles_field", ".", "bundles", ",", "bundles_field", ".", "filespecs_list", ",", "snapshot_list", ")", "for", "bundle", ",", "filespecs", ",", "snapshot", "in", "zipped", ":", "rel_spec_path", "=", "getattr", "(", "bundle", ",", "'rel_path'", ",", "spec_path", ")", "kwargs", "=", "bundle", ".", "kwargs", "(", ")", "# NB: We `include_dirs=True` because bundle filesets frequently specify directories in order", "# to trigger a (deprecated) default inclusion of their recursive contents. See the related", "# deprecation in `pants.backend.jvm.tasks.bundle_create`.", "kwargs", "[", "'fileset'", "]", "=", "_eager_fileset_with_spec", "(", "rel_spec_path", ",", "filespecs", ",", "snapshot", ",", "include_dirs", "=", "True", ")", "bundles", ".", "append", "(", "BundleAdaptor", "(", "*", "*", "kwargs", ")", ")", "yield", "HydratedField", "(", "'bundles'", ",", "bundles", ")" ]
Return the series as list of index set tuples .
def index_sets ( self , as_set = False ) : indexes = frozenset if as_set else tuple return [ indexes ( b . iter_set ( ) ) for b in self ]
4,066
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/series.py#L57-L60
[ "def", "config_managed_object", "(", "p_dn", ",", "p_class_id", ",", "class_id", ",", "mo_config", ",", "mo_dn", ",", "handle", "=", "None", ",", "delete", "=", "True", ")", ":", "if", "handle", "is", "None", ":", "handle", "=", "self", ".", "handle", "try", ":", "result", "=", "handle", ".", "AddManagedObject", "(", "None", ",", "classId", "=", "class_id", ",", "params", "=", "mo_config", ",", "modifyPresent", "=", "True", ",", "dumpXml", "=", "YesOrNo", ".", "FALSE", ")", "return", "result", "except", "UcsException", "as", "ex", ":", "print", "(", "_", "(", "\"Cisco client exception: %(msg)s\"", ")", ",", "{", "'msg'", ":", "ex", "}", ")", "raise", "exception", ".", "UcsOperationError", "(", "'config_managed_object'", ",", "error", "=", "ex", ")" ]
Append an array to another padding with NaNs for constant length .
def append_arrays ( many , single ) : assert np . ndim ( single ) == 1 # Check if the values need to be padded to for equal length diff = single . shape [ 0 ] - many . shape [ 0 ] if diff < 0 : single = np . pad ( single , ( 0 , - diff ) , 'constant' , constant_values = np . nan ) elif diff > 0 : many = np . pad ( many , ( ( 0 , diff ) , ) , 'constant' , constant_values = np . nan ) else : # No padding needed pass return np . c_ [ many , single ]
4,067
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/output.py#L46-L74
[ "def", "on_close", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"> Calling '{0}' Component Framework 'on_close' method.\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "map", "(", "self", ".", "unregister_file", ",", "self", ".", "list_files", "(", ")", ")", "if", "self", ".", "store_session", "(", ")", "and", "self", ".", "close_all_files", "(", "leave_first_editor", "=", "False", ")", ":", "return", "True" ]
Locate locations within the profile .
def _get_locations ( self , calc ) : return ( self . _location_in ( calc . profile ) , self . _location_out ( calc . profile ) )
4,068
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/output.py#L363-L366
[ "def", "seed_args", "(", "subparsers", ")", ":", "seed_parser", "=", "subparsers", ".", "add_parser", "(", "'seed'", ")", "secretfile_args", "(", "seed_parser", ")", "vars_args", "(", "seed_parser", ")", "seed_parser", ".", "add_argument", "(", "'--mount-only'", ",", "dest", "=", "'mount_only'", ",", "help", "=", "'Only mount paths if needed'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ")", "thaw_from_args", "(", "seed_parser", ")", "seed_parser", ".", "add_argument", "(", "'--remove-unknown'", ",", "dest", "=", "'remove_unknown'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Remove mountpoints that are not '", "'defined in the Secretfile'", ")", "base_args", "(", "seed_parser", ")" ]
Find useful region of a given spectrum
def find_pix_borders ( sp , sought_value ) : if sp . ndim != 1 : raise ValueError ( 'Unexpected number of dimensions:' , sp . ndim ) naxis1 = len ( sp ) jborder_min = - 1 jborder_max = naxis1 # only spectra with values different from 'sought_value' if not np . alltrue ( sp == sought_value ) : # left border while True : jborder_min += 1 if sp [ jborder_min ] != sought_value : break # right border while True : jborder_max -= 1 if sp [ jborder_max ] != sought_value : break return jborder_min , jborder_max
4,069
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/fix_pix_borders.py#L16-L59
[ "def", "delete_entity", "(", "self", ",", "entity_id", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "api_path", "=", "'/v1/{mount_point}/entity/id/{id}'", ".", "format", "(", "mount_point", "=", "mount_point", ",", "id", "=", "entity_id", ",", ")", "return", "self", ".", "_adapter", ".", "delete", "(", "url", "=", "api_path", ",", ")" ]
Replace a few pixels at the borders of each spectrum .
def fix_pix_borders ( image2d , nreplace , sought_value , replacement_value ) : # input image size naxis2 , naxis1 = image2d . shape for i in range ( naxis2 ) : # only spectra with values different from 'sought_value' jborder_min , jborder_max = find_pix_borders ( image2d [ i , : ] , sought_value = sought_value ) # left border if jborder_min != - 1 : j1 = jborder_min j2 = min ( j1 + nreplace , naxis1 ) image2d [ i , j1 : j2 ] = replacement_value # right border if jborder_max != naxis1 : j2 = jborder_max + 1 j1 = max ( j2 - nreplace , 0 ) image2d [ i , j1 : j2 ] = replacement_value return image2d
4,070
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/fix_pix_borders.py#L62-L108
[ "def", "update_entity_alias", "(", "self", ",", "alias_id", ",", "name", ",", "canonical_id", ",", "mount_accessor", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'name'", ":", "name", ",", "'canonical_id'", ":", "canonical_id", ",", "'mount_accessor'", ":", "mount_accessor", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity-alias/id/{id}'", ".", "format", "(", "mount_point", "=", "mount_point", ",", "id", "=", "alias_id", ",", ")", "response", "=", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")", "if", "response", ".", "status_code", "==", "204", ":", "return", "response", "else", ":", "return", "response", ".", "json", "(", ")" ]
Generate mask avoiding undesired values at the borders .
def define_mask_borders ( image2d , sought_value , nadditional = 0 ) : # input image size naxis2 , naxis1 = image2d . shape # initialize mask mask2d = np . zeros ( ( naxis2 , naxis1 ) , dtype = bool ) # initialize list to store borders borders = [ ] for i in range ( naxis2 ) : # only spectra with values different from 'sought_value' jborder_min , jborder_max = find_pix_borders ( image2d [ i , : ] , sought_value = sought_value ) borders . append ( ( jborder_min , jborder_max ) ) if ( jborder_min , jborder_max ) != ( - 1 , naxis1 ) : if jborder_min != - 1 : j1 = 0 j2 = jborder_min + nadditional + 1 mask2d [ i , j1 : j2 ] = True if jborder_max != naxis1 : j1 = jborder_max - nadditional j2 = naxis1 mask2d [ i , j1 : j2 ] = True return mask2d , borders
4,071
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/fix_pix_borders.py#L111-L161
[ "def", "sync_auth", "(", "self", ",", "vault_client", ",", "resources", ")", ":", "for", "auth", "in", "self", ".", "auths", "(", ")", ":", "auth", ".", "sync", "(", "vault_client", ")", "auth_resources", "=", "[", "x", "for", "x", "in", "resources", "if", "isinstance", "(", "x", ",", "(", "LDAP", ",", "UserPass", ")", ")", "]", "for", "resource", "in", "auth_resources", ":", "resource", ".", "sync", "(", "vault_client", ")", "return", "[", "x", "for", "x", "in", "resources", "if", "not", "isinstance", "(", "x", ",", "(", "LDAP", ",", "UserPass", ",", "AuditLog", ")", ")", "]" ]
Evaluate wavelength at xpos using the provided polynomial .
def update_features ( self , poly ) : for feature in self . features : feature . wavelength = poly ( feature . xpos )
4,072
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/solutionarc.py#L203-L207
[ "def", "handle_memory", "(", "self", ",", "obj", ")", ":", "if", "obj", ".", "subject", "is", "not", "None", ":", "with", "self", ".", "con", "as", "db", ":", "SchemaBase", ".", "note", "(", "db", ",", "obj", ".", "subject", ",", "obj", ".", "state", ",", "obj", ".", "object", ",", "text", "=", "obj", ".", "text", ",", "html", "=", "obj", ".", "html", ",", ")", "return", "obj" ]
Build a DataFrame object from a list .
def dataframe_from_list ( values ) : if ( isinstance ( values , six . string_types ) ) : return DataFrame ( filename = values ) elif ( isinstance ( values , fits . HDUList ) ) : return DataFrame ( frame = values ) else : return None
4,073
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/oresult.py#L86-L93
[ "def", "OnAdjustVolume", "(", "self", ",", "event", ")", ":", "self", ".", "volume", "=", "self", ".", "player", ".", "audio_get_volume", "(", ")", "if", "event", ".", "GetWheelRotation", "(", ")", "<", "0", ":", "self", ".", "volume", "=", "max", "(", "0", ",", "self", ".", "volume", "-", "10", ")", "elif", "event", ".", "GetWheelRotation", "(", ")", ">", "0", ":", "self", ".", "volume", "=", "min", "(", "200", ",", "self", ".", "volume", "+", "10", ")", "self", ".", "player", ".", "audio_set_volume", "(", "self", ".", "volume", ")" ]
Build a ObservationResult object from a dictionary .
def obsres_from_dict ( values ) : obsres = ObservationResult ( ) ikey = 'frames' # Workaround if 'images' in values : ikey = 'images' obsres . id = values . get ( 'id' , 1 ) obsres . mode = values [ 'mode' ] obsres . instrument = values [ 'instrument' ] obsres . configuration = values . get ( 'configuration' , 'default' ) obsres . pipeline = values . get ( 'pipeline' , 'default' ) obsres . children = values . get ( 'children' , [ ] ) obsres . parent = values . get ( 'parent' , None ) obsres . results = values . get ( 'results' , { } ) obsres . requirements = values . get ( 'requirements' , { } ) try : obsres . frames = [ dataframe_from_list ( val ) for val in values [ ikey ] ] except Exception : obsres . frames = [ ] return obsres
4,074
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/oresult.py#L96-L120
[ "def", "ensure_compatible_admin", "(", "view", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_roles", "=", "request", ".", "user", ".", "user_data", ".", "get", "(", "'roles'", ",", "[", "]", ")", "if", "len", "(", "user_roles", ")", "!=", "1", ":", "context", "=", "{", "'message'", ":", "'I need to be able to manage user accounts. '", "'My username is %s'", "%", "request", ".", "user", ".", "username", "}", "return", "render", "(", "request", ",", "'mtp_common/user_admin/incompatible-admin.html'", ",", "context", "=", "context", ")", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Return first available image in observation result
def get_sample_frame ( self ) : for frame in self . frames : return frame . open ( ) for res in self . results . values ( ) : return res . open ( ) return None
4,075
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/oresult.py#L75-L83
[ "def", "close_connection", "(", "self", ")", ":", "# pylint: disable=C0103", "if", "self", ".", "port", ":", "self", ".", "stop", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"Close port '%s'\"", "%", "self", ".", "comport", ",", "extra", "=", "{", "'type'", ":", "'<->'", "}", ")", "self", ".", "port", ".", "close", "(", ")", "self", ".", "port", "=", "False" ]
Loop over the first axis applying Fowler processing .
def fowler_array ( fowlerdata , ti = 0.0 , ts = 0.0 , gain = 1.0 , ron = 1.0 , badpixels = None , dtype = 'float64' , saturation = 65631 , blank = 0 , normalize = False ) : import numina . array . _nirproc as _nirproc if gain <= 0 : raise ValueError ( "invalid parameter, gain <= 0.0" ) if ron <= 0 : raise ValueError ( "invalid parameter, ron < 0.0" ) if ti < 0 : raise ValueError ( "invalid parameter, ti < 0.0" ) if ts < 0 : raise ValueError ( "invalid parameter, ts < 0.0" ) if saturation <= 0 : raise ValueError ( "invalid parameter, saturation <= 0" ) fowlerdata = numpy . asarray ( fowlerdata ) if fowlerdata . ndim != 3 : raise ValueError ( 'fowlerdata must be 3D' ) npairs = fowlerdata . shape [ 0 ] // 2 if 2 * npairs != fowlerdata . shape [ 0 ] : raise ValueError ( 'axis-0 in fowlerdata must be even' ) # change byteorder ndtype = fowlerdata . dtype . newbyteorder ( '=' ) fowlerdata = numpy . asarray ( fowlerdata , dtype = ndtype ) # type of the output fdtype = numpy . result_type ( fowlerdata . dtype , dtype ) # Type of the mask mdtype = numpy . dtype ( 'uint8' ) fshape = ( fowlerdata . shape [ 1 ] , fowlerdata . shape [ 2 ] ) if badpixels is None : badpixels = numpy . zeros ( fshape , dtype = mdtype ) else : if badpixels . shape != fshape : raise ValueError ( 'shape of badpixels is not ' 'compatible with shape of fowlerdata' ) if badpixels . dtype != mdtype : raise ValueError ( 'dtype of badpixels must be uint8' ) result = numpy . empty ( fshape , dtype = fdtype ) var = numpy . empty_like ( result ) npix = numpy . empty ( fshape , dtype = mdtype ) mask = badpixels . copy ( ) _nirproc . _process_fowler_intl ( fowlerdata , ti , ts , gain , ron , badpixels , saturation , blank , result , var , npix , mask ) return result , var , npix , mask
4,076
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/nirproc.py#L18-L132
[ "def", "sync_experiments_from_spec", "(", "filename", ")", ":", "redis", "=", "oz", ".", "redis", ".", "create_connection", "(", ")", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "schema", "=", "escape", ".", "json_decode", "(", "f", ".", "read", "(", ")", ")", "oz", ".", "bandit", ".", "sync_from_spec", "(", "redis", ",", "schema", ")" ]
Loop over the first axis applying ramp processing .
def ramp_array ( rampdata , ti , gain = 1.0 , ron = 1.0 , badpixels = None , dtype = 'float64' , saturation = 65631 , blank = 0 , nsig = None , normalize = False ) : import numina . array . _nirproc as _nirproc if ti <= 0 : raise ValueError ( "invalid parameter, ti <= 0.0" ) if gain <= 0 : raise ValueError ( "invalid parameter, gain <= 0.0" ) if ron <= 0 : raise ValueError ( "invalid parameter, ron < 0.0" ) if saturation <= 0 : raise ValueError ( "invalid parameter, saturation <= 0" ) rampdata = numpy . asarray ( rampdata ) if rampdata . ndim != 3 : raise ValueError ( 'rampdata must be 3D' ) # change byteorder ndtype = rampdata . dtype . newbyteorder ( '=' ) rampdata = numpy . asarray ( rampdata , dtype = ndtype ) # type of the output fdtype = numpy . result_type ( rampdata . dtype , dtype ) # Type of the mask mdtype = numpy . dtype ( 'uint8' ) fshape = ( rampdata . shape [ 1 ] , rampdata . shape [ 2 ] ) if badpixels is None : badpixels = numpy . zeros ( fshape , dtype = mdtype ) else : if badpixels . shape != fshape : msg = 'shape of badpixels is not compatible with shape of rampdata' raise ValueError ( msg ) if badpixels . dtype != mdtype : raise ValueError ( 'dtype of badpixels must be uint8' ) result = numpy . empty ( fshape , dtype = fdtype ) var = numpy . empty_like ( result ) npix = numpy . empty ( fshape , dtype = mdtype ) mask = badpixels . copy ( ) _nirproc . _process_ramp_intl ( rampdata , ti , gain , ron , badpixels , saturation , blank , result , var , npix , mask ) return result , var , npix , mask
4,077
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/nirproc.py#L135-L202
[ "def", "_zfs_image_create", "(", "vm_name", ",", "pool", ",", "disk_name", ",", "hostname_property_name", ",", "sparse_volume", ",", "disk_size", ",", "disk_image_name", ")", ":", "if", "not", "disk_image_name", "and", "not", "disk_size", ":", "raise", "CommandExecutionError", "(", "'Unable to create new disk {0}, please specify'", "' the disk image name or disk size argument'", ".", "format", "(", "disk_name", ")", ")", "if", "not", "pool", ":", "raise", "CommandExecutionError", "(", "'Unable to create new disk {0}, please specify'", "' the disk pool name'", ".", "format", "(", "disk_name", ")", ")", "destination_fs", "=", "os", ".", "path", ".", "join", "(", "pool", ",", "'{0}.{1}'", ".", "format", "(", "vm_name", ",", "disk_name", ")", ")", "log", ".", "debug", "(", "'Image destination will be %s'", ",", "destination_fs", ")", "existing_disk", "=", "__salt__", "[", "'zfs.list'", "]", "(", "name", "=", "pool", ")", "if", "'error'", "in", "existing_disk", ":", "raise", "CommandExecutionError", "(", "'Unable to create new disk {0}. {1}'", ".", "format", "(", "destination_fs", ",", "existing_disk", "[", "'error'", "]", ")", ")", "elif", "destination_fs", "in", "existing_disk", ":", "log", ".", "info", "(", "'ZFS filesystem %s already exists. Skipping creation'", ",", "destination_fs", ")", "blockdevice_path", "=", "os", ".", "path", ".", "join", "(", "'/dev/zvol'", ",", "pool", ",", "vm_name", ")", "return", "blockdevice_path", "properties", "=", "{", "}", "if", "hostname_property_name", ":", "properties", "[", "hostname_property_name", "]", "=", "vm_name", "if", "disk_image_name", ":", "__salt__", "[", "'zfs.clone'", "]", "(", "name_a", "=", "disk_image_name", ",", "name_b", "=", "destination_fs", ",", "properties", "=", "properties", ")", "elif", "disk_size", ":", "__salt__", "[", "'zfs.create'", "]", "(", "name", "=", "destination_fs", ",", "properties", "=", "properties", ",", "volume_size", "=", "disk_size", ",", "sparse", "=", "sparse_volume", ")", "blockdevice_path", "=", "os", ".", "path", ".", "join", "(", "'/dev/zvol'", ",", "pool", ",", "'{0}.{1}'", ".", "format", "(", "vm_name", ",", "disk_name", ")", ")", "log", ".", "debug", "(", "'Image path will be %s'", ",", "blockdevice_path", ")", "return", "blockdevice_path" ]
different Eagle versions need differnt TAB count . 6 . 5 - > 2 6 . 6 - > 3 7 . 4 - > 2
def accept_freeware_license ( ) : ntab = 3 if version ( ) . startswith ( '6.6.' ) else 2 for _ in range ( ntab ) : EasyProcess ( 'xdotool key KP_Tab' ) . call ( ) time . sleep ( 0.5 ) EasyProcess ( 'xdotool key KP_Space' ) . call ( ) time . sleep ( 0.5 ) # say OK to any more question EasyProcess ( 'xdotool key KP_Space' ) . call ( )
4,078
https://github.com/ponty/eagexp/blob/1dd5108c1d8112cc87d1bda64fa6c2784ccf0ff2/eagexp/cmd.py#L20-L35
[ "def", "renew_compose", "(", "self", ",", "compose_id", ")", ":", "logger", ".", "info", "(", "\"Renewing compose %d\"", ",", "compose_id", ")", "response", "=", "self", ".", "session", ".", "patch", "(", "'{}composes/{}'", ".", "format", "(", "self", ".", "url", ",", "compose_id", ")", ")", "response", ".", "raise_for_status", "(", ")", "response_json", "=", "response", ".", "json", "(", ")", "compose_id", "=", "response_json", "[", "'id'", "]", "logger", ".", "info", "(", "\"Renewed compose is %d\"", ",", "compose_id", ")", "return", "response_json" ]
Return fully qualified name from object
def fully_qualified_name ( obj , sep = '.' ) : if inspect . isclass ( obj ) : return obj . __module__ + sep + obj . __name__ else : return obj . __module__ + sep + obj . __class__ . __name__
4,079
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/util/fqn.py#L16-L21
[ "def", "render", "(", "self", ",", "data", ",", "accepted_media_type", "=", "None", ",", "renderer_context", "=", "None", ")", ":", "if", "'SWAGGER_JSON_PATH'", "in", "os", ".", "environ", ":", "with", "io", ".", "open", "(", "os", ".", "environ", "[", "'SWAGGER_JSON_PATH'", "]", ",", "'rb'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "else", ":", "return", "super", "(", "ConditionalOpenAPIRenderer", ",", "self", ")", ".", "render", "(", "data", ",", "accepted_media_type", ",", "renderer_context", ")" ]
Compute fit residuals
def fun_residuals ( params , xnor , ynor , w , bbox , k , ext ) : spl = LSQUnivariateSpline ( x = xnor , y = ynor , t = [ item . value for item in params . values ( ) ] , w = w , bbox = bbox , k = k , ext = ext , check_finite = False ) return spl . get_residual ( )
4,080
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/numsplines.py#L17-L30
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Parse a dictionary of strings as if yaml reads it
def parse_as_yaml ( strdict ) : interm = "" for key , val in strdict . items ( ) : interm = "%s: %s, %s" % ( key , val , interm ) fin = '{%s}' % interm return yaml . load ( fin )
4,081
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/clirundal.py#L245-L252
[ "def", "aggregate", "(", "self", ",", "val1", ",", "val2", ")", ":", "assert", "val1", "is", "not", "None", "assert", "val2", "is", "not", "None", "return", "self", ".", "_aggregator", "(", "val1", ",", "val2", ")" ]
Read folder and collect data in local sqlite3 database
def folder2db ( folder_name , debug , energy_limit , skip_folders , goto_reaction ) : folder_name = folder_name . rstrip ( '/' ) skip = [ ] for s in skip_folders . split ( ', ' ) : for sk in s . split ( ',' ) : skip . append ( sk ) pub_id = _folder2db . main ( folder_name , debug , energy_limit , skip , goto_reaction ) if pub_id : print ( '' ) print ( '' ) print ( 'Ready to release the data?' ) print ( " Send it to the Catalysis-Hub server with 'cathub db2server {folder_name}/{pub_id}.db'." . format ( * * locals ( ) ) ) print ( " Then log in at www.catalysis-hub.org/upload/ to verify and release. " )
4,082
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L82-L99
[ "def", "exclude", "(", "requestContext", ",", "seriesList", ",", "pattern", ")", ":", "regex", "=", "re", ".", "compile", "(", "pattern", ")", "return", "[", "s", "for", "s", "in", "seriesList", "if", "not", "regex", ".", "search", "(", "s", ".", "name", ")", "]" ]
Transfer data from local database to Catalysis Hub server
def db2server ( dbfile , block_size , dbuser , dbpassword ) : _db2server . main ( dbfile , write_reaction = True , write_ase = True , write_publication = True , write_reaction_system = True , block_size = block_size , start_block = 0 , user = dbuser , password = dbpassword )
4,083
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L109-L120
[ "def", "overwrite_file_check", "(", "args", ",", "filename", ")", ":", "if", "not", "args", "[", "'overwrite'", "]", "and", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "# Confirm overwriting of the file, or modify filename", "if", "args", "[", "'no_overwrite'", "]", ":", "overwrite", "=", "False", "else", ":", "try", ":", "overwrite", "=", "confirm_input", "(", "input", "(", "'Overwrite {0}? (yes/no): '", ".", "format", "(", "filename", ")", ")", ")", "except", "(", "KeyboardInterrupt", ",", "EOFError", ")", ":", "sys", ".", "exit", "(", ")", "if", "not", "overwrite", ":", "new_filename", "=", "modify_filename_id", "(", "filename", ")", "while", "os", ".", "path", ".", "exists", "(", "new_filename", ")", ":", "new_filename", "=", "modify_filename_id", "(", "new_filename", ")", "return", "new_filename", "return", "filename" ]
Search for reactions
def reactions ( columns , n_results , write_db , queries ) : if not isinstance ( queries , dict ) : query_dict = { } for q in queries : key , value = q . split ( '=' ) if key == 'distinct' : if value in [ 'True' , 'true' ] : query_dict . update ( { key : True } ) continue try : value = int ( value ) query_dict . update ( { key : value } ) except BaseException : query_dict . update ( { key : '{0}' . format ( value ) } ) # Keep {0} in string.format for python2.6 compatibility if write_db and n_results > 1000 : print ( """Warning: You're attempting to write more than a 1000 rows with geometries. This could take some time""" ) data = query . get_reactions ( columns = columns , n_results = n_results , write_db = write_db , * * query_dict ) if write_db : return table = [ ] headers = [ ] for row in data [ 'reactions' ] [ 'edges' ] : table += [ list ( row [ 'node' ] . values ( ) ) ] headers = list ( row [ 'node' ] . keys ( ) ) print ( tabulate ( table , headers ) + '\n' )
4,084
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L171-L204
[ "def", "creds", "(", "provider", ")", ":", "# Declare globals", "global", "__AccessKeyId__", ",", "__SecretAccessKey__", ",", "__Token__", ",", "__Expiration__", "ret_credentials", "=", "(", ")", "# if id or key is 'use-instance-role-credentials', pull them from meta-data", "## if needed", "if", "provider", "[", "'id'", "]", "==", "IROLE_CODE", "or", "provider", "[", "'key'", "]", "==", "IROLE_CODE", ":", "# Check to see if we have cache credentials that are still good", "if", "__Expiration__", "!=", "''", ":", "timenow", "=", "datetime", ".", "utcnow", "(", ")", "timestamp", "=", "timenow", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "if", "timestamp", "<", "__Expiration__", ":", "# Current timestamp less than expiration fo cached credentials", "return", "__AccessKeyId__", ",", "__SecretAccessKey__", ",", "__Token__", "# We don't have any cached credentials, or they are expired, get them", "# Connections to instance meta-data must fail fast and never be proxied", "try", ":", "result", "=", "requests", ".", "get", "(", "\"http://169.254.169.254/latest/meta-data/iam/security-credentials/\"", ",", "proxies", "=", "{", "'http'", ":", "''", "}", ",", "timeout", "=", "AWS_METADATA_TIMEOUT", ",", ")", "result", ".", "raise_for_status", "(", ")", "role", "=", "result", ".", "text", "except", "(", "requests", ".", "exceptions", ".", "HTTPError", ",", "requests", ".", "exceptions", ".", "ConnectionError", ")", ":", "return", "provider", "[", "'id'", "]", ",", "provider", "[", "'key'", "]", ",", "''", "try", ":", "result", "=", "requests", ".", "get", "(", "\"http://169.254.169.254/latest/meta-data/iam/security-credentials/{0}\"", ".", "format", "(", "role", ")", ",", "proxies", "=", "{", "'http'", ":", "''", "}", ",", "timeout", "=", "AWS_METADATA_TIMEOUT", ",", ")", "result", ".", "raise_for_status", "(", ")", "except", "(", "requests", ".", "exceptions", ".", "HTTPError", ",", "requests", ".", "exceptions", ".", "ConnectionError", ")", ":", "return", "provider", "[", "'id'", "]", ",", "provider", "[", "'key'", "]", ",", "''", "data", "=", "result", ".", "json", "(", ")", "__AccessKeyId__", "=", "data", "[", "'AccessKeyId'", "]", "__SecretAccessKey__", "=", "data", "[", "'SecretAccessKey'", "]", "__Token__", "=", "data", "[", "'Token'", "]", "__Expiration__", "=", "data", "[", "'Expiration'", "]", "ret_credentials", "=", "__AccessKeyId__", ",", "__SecretAccessKey__", ",", "__Token__", "else", ":", "ret_credentials", "=", "provider", "[", "'id'", "]", ",", "provider", "[", "'key'", "]", ",", "''", "if", "provider", ".", "get", "(", "'role_arn'", ")", "is", "not", "None", ":", "provider_shadow", "=", "provider", ".", "copy", "(", ")", "provider_shadow", ".", "pop", "(", "\"role_arn\"", ",", "None", ")", "log", ".", "info", "(", "\"Assuming the role: %s\"", ",", "provider", ".", "get", "(", "'role_arn'", ")", ")", "ret_credentials", "=", "assumed_creds", "(", "provider_shadow", ",", "role_arn", "=", "provider", ".", "get", "(", "'role_arn'", ")", ",", "location", "=", "'us-east-1'", ")", "return", "ret_credentials" ]
Search for publications
def publications ( columns , n_results , queries ) : if not isinstance ( queries , dict ) : query_dict = { } for q in queries : key , value = q . split ( '=' ) if key == 'distinct' : if value in [ 'True' , 'true' ] : query_dict . update ( { key : True } ) continue try : value = int ( value ) query_dict . update ( { key : value } ) except BaseException : query_dict . update ( { key : '{0}' . format ( value ) } ) if 'sort' not in query_dict : query_dict . update ( { 'order' : '-year' } ) data = query . query ( table = 'publications' , columns = columns , n_results = n_results , queries = query_dict ) table = [ ] headers = [ ] for row in data [ 'publications' ] [ 'edges' ] : value = list ( row [ 'node' ] . values ( ) ) for n , v in enumerate ( value ) : if isinstance ( v , str ) and len ( v ) > 20 : splited = v . split ( ' ' ) size = 0 sentence = '' for word in splited : if size < 20 : size += len ( word ) sentence += ' ' + word else : sentence += '\n' + word size = 0 sentence += '\n' value [ n ] = sentence table += [ value ] headers = list ( row [ 'node' ] . keys ( ) ) print ( tabulate ( table , headers , tablefmt = "grid" ) + '\n' )
4,085
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L223-L266
[ "def", "_writeOptionalXsecCards", "(", "self", ",", "fileObject", ",", "xSec", ",", "replaceParamFile", ")", ":", "if", "xSec", ".", "erode", ":", "fileObject", ".", "write", "(", "'ERODE\\n'", ")", "if", "xSec", ".", "maxErosion", "!=", "None", ":", "fileObject", ".", "write", "(", "'MAX_EROSION %.6f\\n'", "%", "xSec", ".", "maxErosion", ")", "if", "xSec", ".", "subsurface", ":", "fileObject", ".", "write", "(", "'SUBSURFACE\\n'", ")", "if", "xSec", ".", "mRiver", "!=", "None", ":", "mRiver", "=", "vwp", "(", "xSec", ".", "mRiver", ",", "replaceParamFile", ")", "try", ":", "fileObject", ".", "write", "(", "'M_RIVER %.6f\\n'", "%", "mRiver", ")", "except", ":", "fileObject", ".", "write", "(", "'M_RIVER %s\\n'", "%", "mRiver", ")", "if", "xSec", ".", "kRiver", "!=", "None", ":", "kRiver", "=", "vwp", "(", "xSec", ".", "kRiver", ",", "replaceParamFile", ")", "try", ":", "fileObject", ".", "write", "(", "'K_RIVER %.6f\\n'", "%", "kRiver", ")", "except", ":", "fileObject", ".", "write", "(", "'K_RIVER %s\\n'", "%", "kRiver", ")" ]
Create a basic folder tree for dumping DFT calculcations for reaction energies .
def make_folders ( template , custom_base ) : def dict_representer ( dumper , data ) : return dumper . represent_dict ( data . items ( ) ) Dumper . add_representer ( collections . OrderedDict , dict_representer ) if custom_base is None : custom_base = os . path . abspath ( os . path . curdir ) template = custom_base + '/' + template template_data = ase_tools . REACTION_TEMPLATE if not os . path . exists ( template ) : with open ( template , 'w' ) as outfile : outfile . write ( yaml . dump ( template_data , indent = 4 , Dumper = Dumper ) + '\n' ) print ( "Created template file: {template}\n" . format ( * * locals ( ) ) + ' Please edit it and run the script again to create your folderstructure.\n' + ' Run cathub make_folders --help for instructions' ) return with open ( template ) as infile : template_data = yaml . load ( infile ) title = template_data [ 'title' ] authors = template_data [ 'authors' ] journal = template_data [ 'journal' ] volume = template_data [ 'volume' ] number = template_data [ 'number' ] pages = template_data [ 'pages' ] year = template_data [ 'year' ] email = template_data [ 'email' ] publisher = template_data [ 'publisher' ] doi = template_data [ 'doi' ] dft_code = template_data [ 'DFT_code' ] dft_functionals = template_data [ 'DFT_functionals' ] reactions = template_data [ 'reactions' ] crystal_structures = template_data [ 'crystal_structures' ] bulk_compositions = template_data [ 'bulk_compositions' ] facets = template_data [ 'facets' ] energy_corrections = template_data [ 'energy_corrections' ] make_folders_template . main ( title = title , authors = eval ( authors ) if isinstance ( authors , six . string_types ) else authors , journal = journal , volume = volume , number = number , pages = pages , year = year , email = email , publisher = publisher , doi = doi , DFT_code = dft_code , DFT_functionals = dft_functionals , reactions = eval ( reactions ) if isinstance ( reactions , six . string_types ) else reactions , custom_base = custom_base , bulk_compositions = bulk_compositions , crystal_structures = crystal_structures , facets = facets , energy_corrections = energy_corrections ) pub_id = tools . get_pub_id ( title , authors , year ) print ( "Now dump your DFT output files into the folder, and run 'cathub folder2db {pub_id}'" . format ( * * locals ( ) ) )
4,086
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L274-L408
[ "def", "get_all_ids", "(", "idVendor", "=", "GrizzlyUSB", ".", "ID_VENDOR", ",", "idProduct", "=", "GrizzlyUSB", ".", "ID_PRODUCT", ")", ":", "all_dev", "=", "GrizzlyUSB", ".", "get_all_usb_devices", "(", "idVendor", ",", "idProduct", ")", "if", "len", "(", "all_dev", ")", "<=", "0", ":", "raise", "usb", ".", "USBError", "(", "\"Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)\"", "%", "(", "idVendor", ",", "idProduct", ")", ")", "else", ":", "all_addresses", "=", "[", "]", "# bound devices is a list of devices that are already busy.", "bound_devices", "=", "[", "]", "for", "device", "in", "all_dev", ":", "internal_addr", "=", "GrizzlyUSB", ".", "get_device_address", "(", "device", ")", "if", "internal_addr", "==", "GrizzlyUSB", ".", "USB_DEVICE_ERROR", ":", "# device bound", "bound_devices", ".", "append", "(", "device", ")", "else", ":", "all_addresses", ".", "append", "(", "internal_addr", ")", "# we release all devices that we aren't using and aren't bound.", "for", "device", "in", "all_dev", ":", "if", "device", "not", "in", "bound_devices", ":", "usb", ".", "util", ".", "dispose_resources", "(", "device", ")", "return", "map", "(", "addr_to_id", ",", "all_addresses", ")" ]
Read reactions from non - organized folder
def organize ( * * kwargs ) : # do argument wrangling before turning it into an obect # since namedtuples are immutable if len ( kwargs [ 'adsorbates' ] ) == 0 : print ( """Warning: no adsorbates specified, can't pick up reaction reaction energies.""" ) print ( " Enter adsorbates like so --adsorbates CO,O,CO2" ) print ( " [Comma-separated list without spaces.]" ) kwargs [ 'adsorbates' ] = list ( map ( lambda x : ( '' . join ( sorted ( string2symbols ( x ) ) ) ) , kwargs [ 'adsorbates' ] . split ( ',' ) , ) ) if kwargs [ 'energy_corrections' ] : e_c_dict = { } for e_c in kwargs [ 'energy_corrections' ] . split ( ',' ) : key , value = e_c . split ( '=' ) e_c_dict . update ( { key : float ( value ) } ) kwargs [ 'energy_corrections' ] = e_c_dict options = collections . namedtuple ( 'options' , kwargs . keys ( ) ) ( * * kwargs ) _organize . main ( options = options )
4,087
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/cli.py#L551-L576
[ "def", "get_free_gpus", "(", "max_procs", "=", "0", ")", ":", "# Try connect with NVIDIA drivers", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "py3nvml", ".", "nvmlInit", "(", ")", "except", ":", "str_", "=", "\"\"\"Couldn't connect to nvml drivers. Check they are installed correctly.\"\"\"", "warnings", ".", "warn", "(", "str_", ",", "RuntimeWarning", ")", "logger", ".", "warn", "(", "str_", ")", "return", "[", "]", "num_gpus", "=", "py3nvml", ".", "nvmlDeviceGetCount", "(", ")", "gpu_free", "=", "[", "False", "]", "*", "num_gpus", "for", "i", "in", "range", "(", "num_gpus", ")", ":", "try", ":", "h", "=", "py3nvml", ".", "nvmlDeviceGetHandleByIndex", "(", "i", ")", "except", ":", "continue", "procs", "=", "try_get_info", "(", "py3nvml", ".", "nvmlDeviceGetComputeRunningProcesses", ",", "h", ",", "[", "'something'", "]", ")", "if", "len", "(", "procs", ")", "<=", "max_procs", ":", "gpu_free", "[", "i", "]", "=", "True", "py3nvml", ".", "nvmlShutdown", "(", ")", "return", "gpu_free" ]
Set up screen properties
def initCurses ( self ) : curses . noecho ( ) curses . cbreak ( ) curses . curs_set ( 0 ) curses . start_color ( ) curses . use_default_colors ( ) curses . init_pair ( 1 , curses . COLOR_WHITE , - 1 ) curses . init_pair ( 2 , curses . COLOR_YELLOW , - 1 ) curses . init_pair ( 3 , curses . COLOR_MAGENTA , - 1 ) curses . init_pair ( 4 , curses . COLOR_CYAN , - 1 ) curses . init_pair ( 5 , curses . COLOR_GREEN , - 1 ) curses . init_pair ( 6 , curses . COLOR_BLUE , - 1 ) curses . init_pair ( 7 , curses . COLOR_RED , - 1 )
4,088
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L81-L96
[ "def", "fromtif", "(", "path", ",", "ext", "=", "'tif'", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "recursive", "=", "False", ",", "nplanes", "=", "None", ",", "npartitions", "=", "None", ",", "labels", "=", "None", ",", "engine", "=", "None", ",", "credentials", "=", "None", ",", "discard_extra", "=", "False", ")", ":", "from", "tifffile", "import", "TiffFile", "if", "nplanes", "is", "not", "None", "and", "nplanes", "<=", "0", ":", "raise", "ValueError", "(", "'nplanes must be positive if passed, got %d'", "%", "nplanes", ")", "def", "getarray", "(", "idx_buffer_filename", ")", ":", "idx", ",", "buf", ",", "fname", "=", "idx_buffer_filename", "fbuf", "=", "BytesIO", "(", "buf", ")", "tfh", "=", "TiffFile", "(", "fbuf", ")", "ary", "=", "tfh", ".", "asarray", "(", ")", "pageCount", "=", "ary", ".", "shape", "[", "0", "]", "if", "nplanes", "is", "not", "None", ":", "extra", "=", "pageCount", "%", "nplanes", "if", "extra", ":", "if", "discard_extra", ":", "pageCount", "=", "pageCount", "-", "extra", "logging", ".", "getLogger", "(", "'thunder'", ")", ".", "warn", "(", "'Ignored %d pages in file %s'", "%", "(", "extra", ",", "fname", ")", ")", "else", ":", "raise", "ValueError", "(", "\"nplanes '%d' does not evenly divide '%d in file %s'\"", "%", "(", "nplanes", ",", "pageCount", ",", "fname", ")", ")", "values", "=", "[", "ary", "[", "i", ":", "(", "i", "+", "nplanes", ")", "]", "for", "i", "in", "range", "(", "0", ",", "pageCount", ",", "nplanes", ")", "]", "else", ":", "values", "=", "[", "ary", "]", "tfh", ".", "close", "(", ")", "if", "ary", ".", "ndim", "==", "3", ":", "values", "=", "[", "val", ".", "squeeze", "(", ")", "for", "val", "in", "values", "]", "nvals", "=", "len", "(", "values", ")", "keys", "=", "[", "(", "idx", "*", "nvals", "+", "timepoint", ",", ")", "for", "timepoint", "in", "range", "(", "nvals", ")", "]", "return", "zip", "(", "keys", ",", "values", ")", "recount", "=", "False", "if", "nplanes", "is", "None", "else", "True", "data", "=", "frompath", "(", "path", ",", "accessor", "=", "getarray", ",", "ext", "=", "ext", ",", "start", "=", "start", ",", "stop", "=", "stop", ",", "recursive", "=", "recursive", ",", "npartitions", "=", "npartitions", ",", "recount", "=", "recount", ",", "labels", "=", "labels", ",", "engine", "=", "engine", ",", "credentials", "=", "credentials", ")", "if", "engine", "is", "not", "None", "and", "npartitions", "is", "not", "None", "and", "data", ".", "npartitions", "(", ")", "<", "npartitions", ":", "data", "=", "data", ".", "repartition", "(", "npartitions", ")", "return", "data" ]
Fix curses addch function for python 3 . 4 . 0
def patchCurses ( self ) : if ( sys . version_info ) [ : 3 ] == ( 3 , 4 , 0 ) : self . addchar = lambda y , x , * args : self . win . addch ( x , y , * args ) else : self . addchar = self . win . addch
4,089
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L98-L105
[ "def", "allEndpoints", "(", "self", ")", ":", "paths", "=", "[", "]", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "matcher", ".", "iterPatterns", "(", ")", ")", ":", "paths", ".", "append", "(", "dict", "(", "path", "=", "\"/\"", ".", "join", "(", "k", ")", ",", "plural", "=", "str", "(", "v", ".", "rtype", ".", "plural", ")", ",", "type", "=", "str", "(", "v", ".", "rtype", ".", "entityType", ".", "name", ")", ",", "type_spec", "=", "v", ".", "rtype", ".", "entityType", ".", "getSpec", "(", ")", ")", ")", "return", "paths" ]
Draw splash screen
def splash ( self ) : dirname = os . path . split ( os . path . abspath ( __file__ ) ) [ 0 ] try : splash = open ( os . path . join ( dirname , "splash" ) , "r" ) . readlines ( ) except IOError : return width = len ( max ( splash , key = len ) ) y = int ( self . y_grid / 2 ) - len ( splash ) x = int ( self . x_grid / 2 ) - int ( width / 2 ) if self . x_grid > width : for i , line in enumerate ( splash ) : self . win . addstr ( y + i , x , line , curses . color_pair ( 5 ) )
4,090
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L110-L126
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Draw information on population size and current generation
def drawHUD ( self ) : self . win . move ( self . height - 2 , self . x_pad ) self . win . clrtoeol ( ) self . win . box ( ) self . addstr ( 2 , self . x_pad + 1 , "Population: %i" % len ( self . grid ) ) self . addstr ( 3 , self . x_pad + 1 , "Generation: %s" % self . current_gen ) self . addstr ( 3 , self . x_grid - 21 , "s: start p: pause" ) self . addstr ( 2 , self . x_grid - 21 , "r: restart q: quit" )
4,091
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L128-L138
[ "def", "points_to_spline_entity", "(", "points", ",", "smooth", "=", "None", ",", "count", "=", "None", ")", ":", "from", "scipy", ".", "interpolate", "import", "splprep", "if", "count", "is", "None", ":", "count", "=", "len", "(", "points", ")", "if", "smooth", "is", "None", ":", "smooth", "=", "0.002", "points", "=", "np", ".", "asanyarray", "(", "points", ",", "dtype", "=", "np", ".", "float64", ")", "closed", "=", "np", ".", "linalg", ".", "norm", "(", "points", "[", "0", "]", "-", "points", "[", "-", "1", "]", ")", "<", "tol", ".", "merge", "knots", ",", "control", ",", "degree", "=", "splprep", "(", "points", ".", "T", ",", "s", "=", "smooth", ")", "[", "0", "]", "control", "=", "np", ".", "transpose", "(", "control", ")", "index", "=", "np", ".", "arange", "(", "len", "(", "control", ")", ")", "if", "closed", ":", "control", "[", "0", "]", "=", "control", "[", "[", "0", ",", "-", "1", "]", "]", ".", "mean", "(", "axis", "=", "0", ")", "control", "=", "control", "[", ":", "-", "1", "]", "index", "[", "-", "1", "]", "=", "index", "[", "0", "]", "entity", "=", "entities", ".", "BSpline", "(", "points", "=", "index", ",", "knots", "=", "knots", ",", "closed", "=", "closed", ")", "return", "entity", ",", "control" ]
Redraw the grid with the new generation
def drawGrid ( self ) : for cell in self . grid : y , x = cell y += self . y_pad x += self . x_pad if self . traditional : sprite = '.' color = curses . color_pair ( 4 ) else : sprite = self . char [ self . grid [ cell ] - 1 ] color = curses . color_pair ( self . grid [ cell ] ) self . addchar ( y , x , sprite , color ) self . win . refresh ( )
4,092
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L140-L158
[ "def", "GetAttachmentIdFromMediaId", "(", "media_id", ")", ":", "altchars", "=", "'+-'", "if", "not", "six", ".", "PY2", ":", "altchars", "=", "altchars", ".", "encode", "(", "'utf-8'", ")", "# altchars for '+' and '/'. We keep '+' but replace '/' with '-'", "buffer", "=", "base64", ".", "b64decode", "(", "str", "(", "media_id", ")", ",", "altchars", ")", "resoure_id_length", "=", "20", "attachment_id", "=", "''", "if", "len", "(", "buffer", ")", ">", "resoure_id_length", ":", "# We are cutting off the storage index.", "attachment_id", "=", "base64", ".", "b64encode", "(", "buffer", "[", "0", ":", "resoure_id_length", "]", ",", "altchars", ")", "if", "not", "six", ".", "PY2", ":", "attachment_id", "=", "attachment_id", ".", "decode", "(", "'utf-8'", ")", "else", ":", "attachment_id", "=", "media_id", "return", "attachment_id" ]
Decide the fate of the cells
def nextGen ( self ) : self . current_gen += 1 self . change_gen [ self . current_gen % 3 ] = copy . copy ( self . grid ) grid_cp = copy . copy ( self . grid ) for cell in self . grid : y , x = cell y1 = ( y - 1 ) % self . y_grid y2 = ( y + 1 ) % self . y_grid x1 = ( x - 1 ) % self . x_grid x2 = ( x + 1 ) % self . x_grid n = self . countNeighbours ( cell ) if n < 2 or n > 3 : del grid_cp [ cell ] self . addchar ( y + self . y_pad , x + self . x_pad , ' ' ) else : grid_cp [ cell ] = min ( self . grid [ cell ] + 1 , self . color_max ) for neighbour in product ( [ y1 , y , y2 ] , [ x1 , x , x2 ] ) : if not self . grid . get ( neighbour ) : if self . countNeighbours ( neighbour ) == 3 : y , x = neighbour y = y % self . y_grid x = x % self . x_grid neighbour = y , x grid_cp [ neighbour ] = 1 self . grid = grid_cp
4,093
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L160-L191
[ "def", "validate_instance_dbname", "(", "self", ",", "dbname", ")", ":", "# 1-64 alphanumeric characters, cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "dbname", ")", "is", "not", "None", ":", "if", "len", "(", "dbname", ")", "<=", "41", "and", "len", "(", "dbname", ")", ">=", "1", ":", "if", "dbname", ".", "lower", "(", ")", "not", "in", "MYSQL_RESERVED_WORDS", ":", "return", "True", "return", "'*** Error: Database names must be 1-64 alphanumeric characters,\\\n cannot be a reserved MySQL word.'" ]
Return the number active neighbours within one positions away from cell
def countNeighbours ( self , cell ) : count = 0 y , x = cell y = y % self . y_grid x = x % self . x_grid y1 = ( y - 1 ) % self . y_grid y2 = ( y + 1 ) % self . y_grid x1 = ( x - 1 ) % self . x_grid x2 = ( x + 1 ) % self . x_grid cell = y , x for neighbour in product ( [ y1 , y , y2 ] , [ x1 , x , x2 ] ) : if neighbour != cell and self . grid . get ( neighbour ) : count += 1 return count
4,094
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L193-L210
[ "def", "get_class", "(", "class_key", ")", ":", "if", "class_key", "not", "in", "CLASSES", ":", "for", "basecls", "in", "(", "MediaMetadata", ",", "MediaCollection", ")", ":", "if", "class_key", ".", "startswith", "(", "basecls", ".", "__name__", ")", ":", "# So MediaMetadataTrack turns into MSTrack", "class_name", "=", "'MS'", "+", "class_key", ".", "replace", "(", "basecls", ".", "__name__", ",", "''", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "class_name", "=", "class_name", ".", "encode", "(", "'ascii'", ")", "CLASSES", "[", "class_key", "]", "=", "type", "(", "class_name", ",", "(", "basecls", ",", ")", ",", "{", "}", ")", "_LOG", ".", "info", "(", "'Class %s created'", ",", "CLASSES", "[", "class_key", "]", ")", "return", "CLASSES", "[", "class_key", "]" ]
Initialise the game grid
def initGrid ( self ) : blinker = [ ( 4 , 4 ) , ( 4 , 5 ) , ( 4 , 6 ) ] toad = [ ( 9 , 5 ) , ( 9 , 6 ) , ( 9 , 7 ) , ( 10 , 4 ) , ( 10 , 5 ) , ( 10 , 6 ) ] glider = [ ( 4 , 11 ) , ( 5 , 12 ) , ( 6 , 10 ) , ( 6 , 11 ) , ( 6 , 12 ) ] r_pentomino = [ ( 10 , 60 ) , ( 9 , 61 ) , ( 10 , 61 ) , ( 11 , 61 ) , ( 9 , 62 ) ] self . grid = { } if self . test : for cell in chain ( blinker , toad , glider , r_pentomino ) : self . grid [ cell ] = 1 else : for _ in range ( self . initsize ) : ry = random . randint ( self . y_pad , self . y_grid - 1 ) rx = random . randint ( self . x_pad , self . x_grid - 1 ) self . grid [ ( ry , rx ) ] = 1
4,095
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L212-L230
[ "def", "parseReaderConfig", "(", "self", ",", "confdict", ")", ":", "logger", ".", "debug", "(", "'parseReaderConfig input: %s'", ",", "confdict", ")", "conf", "=", "{", "}", "for", "k", ",", "v", "in", "confdict", ".", "items", "(", ")", ":", "if", "not", "k", ".", "startswith", "(", "'Parameter'", ")", ":", "continue", "ty", "=", "v", "[", "'Type'", "]", "data", "=", "v", "[", "'Data'", "]", "vendor", "=", "None", "subtype", "=", "None", "try", ":", "vendor", ",", "subtype", "=", "v", "[", "'Vendor'", "]", ",", "v", "[", "'Subtype'", "]", "except", "KeyError", ":", "pass", "if", "ty", "==", "1023", ":", "if", "vendor", "==", "25882", "and", "subtype", "==", "37", ":", "tempc", "=", "struct", ".", "unpack", "(", "'!H'", ",", "data", ")", "[", "0", "]", "conf", ".", "update", "(", "temperature", "=", "tempc", ")", "else", ":", "conf", "[", "ty", "]", "=", "data", "return", "conf" ]
Restart the game from a new generation 0
def restart ( self ) : self . initGrid ( ) self . win . clear ( ) self . current_gen = 1 self . start
4,096
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L278-L285
[ "def", "ConsultarTipoActividad", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "tipoActividadConsultar", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", ",", "'cuit'", ":", "self", ".", "Cuit", ",", "}", ",", ")", "[", "'tipoActividadReturn'", "]", "self", ".", "__analizar_errores", "(", "ret", ")", "array", "=", "ret", ".", "get", "(", "'tiposActividad'", ",", "[", "]", ")", "return", "[", "(", "\"%s %%s %s %%s %s\"", "%", "(", "sep", ",", "sep", ",", "sep", ")", ")", "%", "(", "it", "[", "'codigoDescripcion'", "]", "[", "'codigo'", "]", ",", "it", "[", "'codigoDescripcion'", "]", "[", "'descripcion'", "]", ")", "for", "it", "in", "array", "]" ]
Game Finished - Restart or Quit
def end ( self ) : if self . loop : self . restart return self . addstr ( 2 , self . x_grid / 2 - 4 , "GAMEOVER" , 7 ) if self . hud : self . addstr ( 2 , self . x_pad + 13 , len ( self . grid ) , 5 ) self . addstr ( 3 , self . x_pad + 13 , self . current_gen , 5 ) if self . test : exit ( ) while self . state == 'stopped' : key = self . win . getch ( ) if key == ord ( 'q' ) : exit ( ) if key in [ ord ( 's' ) , ord ( 'r' ) ] : self . restart
4,097
https://github.com/iiSeymour/game-of-life/blob/288bc87179ffd986ca066bcd98ea6e0951dd7970/conway/gol.py#L288-L309
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "base_path", ")", "admin_metadata_fpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\".dtool\"", ",", "\"dtool\"", ")", "with", "open", "(", "admin_metadata_fpath", ")", "as", "fh", ":", "admin_metadata", "=", "json", ".", "load", "(", "fh", ")", "http_manifest", "=", "{", "\"admin_metadata\"", ":", "admin_metadata", ",", "\"manifest_url\"", ":", "self", ".", "generate_url", "(", "\".dtool/manifest.json\"", ")", ",", "\"readme_url\"", ":", "self", ".", "generate_url", "(", "\"README.yml\"", ")", ",", "\"overlays\"", ":", "self", ".", "generate_overlay_urls", "(", ")", ",", "\"item_urls\"", ":", "self", ".", "generate_item_urls", "(", ")", "}", "return", "bytes", "(", "json", ".", "dumps", "(", "http_manifest", ")", ",", "\"utf-8\"", ")" ]
Combine arrays using the mean with masks and offsets .
def mean ( arrays , masks = None , dtype = None , out = None , zeros = None , scales = None , weights = None ) : return generic_combine ( intl_combine . mean_method ( ) , arrays , masks = masks , dtype = dtype , out = out , zeros = zeros , scales = scales , weights = weights )
4,098
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L22-L59
[ "def", "rename_column", "(", "self", ",", "column", ",", "new_name", ")", ":", "if", "type", "(", "column", ")", "is", "not", "str", ":", "column", "=", "self", ".", "ckeys", "[", "column", "]", "self", ".", "ckeys", "[", "self", ".", "ckeys", ".", "index", "(", "column", ")", "]", "=", "new_name", "self", ".", "columns", "[", "new_name", "]", "=", "self", ".", "columns", ".", "pop", "(", "column", ")", "return", "self" ]
Combine arrays using the median with masks .
def median ( arrays , masks = None , dtype = None , out = None , zeros = None , scales = None , weights = None ) : return generic_combine ( intl_combine . median_method ( ) , arrays , masks = masks , dtype = dtype , out = out , zeros = zeros , scales = scales , weights = weights )
4,099
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L62-L85
[ "def", "resume", "(", "env", ",", "identifier", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "env", ".", "client", "[", "'Virtual_Guest'", "]", ".", "resume", "(", "id", "=", "vs_id", ")" ]