query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Calculate the Base 64 encoding of the HMAC for the given document .
def sha1_hmac ( secret , document ) : signature = hmac . new ( secret , document , hashlib . sha1 ) . digest ( ) . encode ( "base64" ) [ : - 1 ] return signature
7,600
https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L6-L11
[ "def", "not_storable", "(", "_type", ")", ":", "return", "Storable", "(", "_type", ",", "handlers", "=", "StorableHandler", "(", "poke", "=", "fake_poke", ",", "peek", "=", "fail_peek", "(", "_type", ")", ")", ")" ]
Return a version of the query string with the _e _k and _s values removed .
def filter_query_string ( query ) : return '&' . join ( [ q for q in query . split ( '&' ) if not ( q . startswith ( '_k=' ) or q . startswith ( '_e=' ) or q . startswith ( '_s' ) ) ] )
7,601
https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L14-L20
[ "def", "set_exception", "(", "self", ",", "exception", ")", ":", "# Sanity check: A future can only complete once.", "if", "self", ".", "done", "(", ")", ":", "raise", "RuntimeError", "(", "\"set_exception can only be called once.\"", ")", "# Set the exception and trigger the future.", "self", ".", "_exception", "=", "exception", "self", ".", "_trigger", "(", ")" ]
Return a signature that corresponds to the signed URL .
def fost_hmac_url_signature ( key , secret , host , path , query_string , expires ) : if query_string : document = '%s%s?%s\n%s' % ( host , path , query_string , expires ) else : document = '%s%s\n%s' % ( host , path , expires ) signature = sha1_hmac ( secret , document ) return signature
7,602
https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L23-L33
[ "def", "read_vocab_file", "(", "file_path", ")", ":", "with", "file_io", ".", "FileIO", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "vocab_pd", "=", "pd", ".", "read_csv", "(", "f", ",", "header", "=", "None", ",", "names", "=", "[", "'vocab'", ",", "'count'", "]", ",", "dtype", "=", "str", ",", "# Prevent pd from converting numerical categories.", "na_filter", "=", "False", ")", "# Prevent pd from converting 'NA' to a NaN.", "vocab", "=", "vocab_pd", "[", "'vocab'", "]", ".", "tolist", "(", ")", "ex_count", "=", "vocab_pd", "[", "'count'", "]", ".", "astype", "(", "int", ")", ".", "tolist", "(", ")", "return", "vocab", ",", "ex_count" ]
Calculate the signature for the given secret and arguments .
def fost_hmac_request_signature ( secret , method , path , timestamp , headers = { } , body = '' ) : signed_headers , header_values = 'X-FOST-Headers' , [ ] for header , value in headers . items ( ) : signed_headers += ' ' + header header_values . append ( value ) return fost_hmac_request_signature_with_headers ( secret , method , path , timestamp , [ signed_headers ] + header_values , body )
7,603
https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L36-L47
[ "def", "_get_exception_class_from_status_code", "(", "status_code", ")", ":", "if", "status_code", "==", "'100'", ":", "return", "None", "exc_class", "=", "STATUS_CODE_MAPPING", ".", "get", "(", "status_code", ")", "if", "not", "exc_class", ":", "# No status code match, return the \"I don't know wtf this is\"", "# exception class.", "return", "STATUS_CODE_MAPPING", "[", "'UNKNOWN'", "]", "else", ":", "# Match found, yay.", "return", "exc_class" ]
Calculate the signature for the given secret and other arguments .
def fost_hmac_request_signature_with_headers ( secret , method , path , timestamp , headers , body ) : document = "%s %s\n%s\n%s\n%s" % ( method , path , timestamp , '\n' . join ( headers ) , body ) signature = sha1_hmac ( secret , document ) logging . info ( "Calculated signature %s for document\n%s" , signature , document ) return document , signature
7,604
https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L50-L64
[ "def", "explode_groups", "(", "self", ",", "eps", ",", "return_emap", "=", "False", ")", ":", "assert_", "(", "0.0", "<=", "eps", "<=", "1.0", ")", "remap", "=", "nm", ".", "empty", "(", "(", "self", ".", "n_nod", ",", ")", ",", "dtype", "=", "nm", ".", "int32", ")", "offset", "=", "0", "if", "return_emap", ":", "rows", ",", "cols", "=", "[", "]", ",", "[", "]", "coors", "=", "[", "]", "ngroups", "=", "[", "]", "conns", "=", "[", "]", "mat_ids", "=", "[", "]", "descs", "=", "[", "]", "for", "ig", ",", "conn", "in", "enumerate", "(", "self", ".", "conns", ")", ":", "nodes", "=", "nm", ".", "unique", "(", "conn", ")", "group_coors", "=", "self", ".", "coors", "[", "nodes", "]", "n_nod", "=", "group_coors", ".", "shape", "[", "0", "]", "centre", "=", "group_coors", ".", "sum", "(", "axis", "=", "0", ")", "/", "float", "(", "n_nod", ")", "vectors", "=", "group_coors", "-", "centre", "[", "None", ",", ":", "]", "new_coors", "=", "centre", "+", "(", "vectors", "*", "eps", ")", "remap", "[", "nodes", "]", "=", "nm", ".", "arange", "(", "n_nod", ",", "dtype", "=", "nm", ".", "int32", ")", "+", "offset", "new_conn", "=", "remap", "[", "conn", "]", "coors", ".", "append", "(", "new_coors", ")", "ngroups", ".", "append", "(", "self", ".", "ngroups", "[", "nodes", "]", ")", "conns", ".", "append", "(", "new_conn", ")", "mat_ids", ".", "append", "(", "self", ".", "mat_ids", "[", "ig", "]", ")", "descs", ".", "append", "(", "self", ".", "descs", "[", "ig", "]", ")", "offset", "+=", "n_nod", "if", "return_emap", ":", "cols", ".", "append", "(", "nodes", ")", "rows", ".", "append", "(", "remap", "[", "nodes", "]", ")", "coors", "=", "nm", ".", "concatenate", "(", "coors", ",", "axis", "=", "0", ")", "ngroups", "=", "nm", ".", "concatenate", "(", "ngroups", ",", "axis", "=", "0", ")", "mesh", "=", "Mesh", ".", "from_data", "(", "'exploded_'", "+", "self", ".", "name", ",", "coors", ",", "ngroups", ",", "conns", ",", "mat_ids", ",", "descs", ")", "if", "return_emap", ":", "rows", "=", "nm", ".", "concatenate", "(", "rows", ")", "cols", "=", "nm", ".", "concatenate", "(", "cols", ")", "data", "=", "nm", ".", "ones", "(", "rows", ".", "shape", "[", "0", "]", ",", "dtype", "=", "nm", ".", "float64", ")", "emap", "=", "sp", ".", "coo_matrix", "(", "(", "data", ",", "(", "rows", ",", "cols", ")", ")", ",", "shape", "=", "(", "mesh", ".", "n_nod", ",", "self", ".", "n_nod", ")", ")", "return", "mesh", ",", "emap", "else", ":", "return", "mesh" ]
Get an Order by ID .
def get_order ( membersuite_id , client = None ) : if not membersuite_id : return None client = client or get_new_client ( request_session = True ) if not client . session_id : client . request_session ( ) object_query = "SELECT Object() FROM ORDER WHERE ID = '{}'" . format ( membersuite_id ) result = client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] if msql_result [ "Success" ] : membersuite_object_data = ( msql_result [ "ResultValue" ] [ "SingleObject" ] ) else : raise ExecuteMSQLError ( result = result ) return Order ( membersuite_object_data = membersuite_object_data )
7,605
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/orders/services.py#L6-L29
[ "def", "secure", "(", "self", ")", ":", "log", ".", "debug", "(", "'ConCache securing sockets'", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "cache_sock", ")", ":", "os", ".", "chmod", "(", "self", ".", "cache_sock", ",", "0o600", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "update_sock", ")", ":", "os", ".", "chmod", "(", "self", ".", "update_sock", ",", "0o600", ")", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "upd_t_sock", ")", ":", "os", ".", "chmod", "(", "self", ".", "upd_t_sock", ",", "0o600", ")" ]
Export a private key in PEM - format
def export_private_key ( self , password = None ) : if self . __private_key is None : raise ValueError ( 'Unable to call this method. Private key must be set' ) if password is not None : if isinstance ( password , str ) is True : password = password . encode ( ) return self . __private_key . private_bytes ( encoding = serialization . Encoding . PEM , format = serialization . PrivateFormat . PKCS8 , encryption_algorithm = serialization . BestAvailableEncryption ( password ) ) return self . __private_key . private_bytes ( encoding = serialization . Encoding . PEM , format = serialization . PrivateFormat . TraditionalOpenSSL , encryption_algorithm = serialization . NoEncryption ( ) )
7,606
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L106-L128
[ "def", "command_max_delay", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "max_delay", "=", "self", ".", "max_delay_var", ".", "get", "(", ")", "except", "ValueError", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "if", "max_delay", "<", "0", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "if", "max_delay", ">", "0.1", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "self", ".", "runtime_cfg", ".", "max_delay", "=", "max_delay", "self", ".", "max_delay_var", ".", "set", "(", "self", ".", "runtime_cfg", ".", "max_delay", ")" ]
Export a public key in PEM - format
def export_public_key ( self ) : if self . __public_key is None : raise ValueError ( 'Unable to call this method. Public key must be set' ) return self . __public_key . public_bytes ( encoding = serialization . Encoding . PEM , format = serialization . PublicFormat . SubjectPublicKeyInfo )
7,607
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L130-L141
[ "def", "_CheckPacketSize", "(", "cursor", ")", ":", "cur_packet_size", "=", "int", "(", "_ReadVariable", "(", "\"max_allowed_packet\"", ",", "cursor", ")", ")", "if", "cur_packet_size", "<", "MAX_PACKET_SIZE", ":", "raise", "Error", "(", "\"MySQL max_allowed_packet of {0} is required, got {1}. \"", "\"Please set max_allowed_packet={0} in your MySQL config.\"", ".", "format", "(", "MAX_PACKET_SIZE", ",", "cur_packet_size", ")", ")" ]
Import a private key from data in PEM - format
def import_private_key ( self , pem_text , password = None ) : if isinstance ( pem_text , str ) is True : pem_text = pem_text . encode ( ) if password is not None and isinstance ( password , str ) is True : password = password . encode ( ) self . __set_private_key ( serialization . load_pem_private_key ( pem_text , password = password , backend = default_backend ( ) ) )
7,608
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L144-L158
[ "def", "_deleteComboBoxes", "(", "self", ",", "row", ")", ":", "tree", "=", "self", ".", "tree", "model", "=", "self", ".", "tree", ".", "model", "(", ")", "for", "col", "in", "range", "(", "self", ".", "COL_FIRST_COMBO", ",", "self", ".", "maxCombos", ")", ":", "logger", ".", "debug", "(", "\"Removing combobox at: ({}, {})\"", ".", "format", "(", "row", ",", "col", ")", ")", "tree", ".", "setIndexWidget", "(", "model", ".", "index", "(", "row", ",", "col", ")", ",", "None", ")", "self", ".", "_comboBoxes", "=", "[", "]" ]
Decrypt a data that used PKCS1 OAEP protocol
def decrypt ( self , data , oaep_hash_fn_name = None , mgf1_hash_fn_name = None ) : if self . __private_key is None : raise ValueError ( 'Unable to call this method. Private key must be set' ) if oaep_hash_fn_name is None : oaep_hash_fn_name = self . __class__ . __default_oaep_hash_function_name__ if mgf1_hash_fn_name is None : mgf1_hash_fn_name = self . __class__ . __default_mgf1_hash_function_name__ oaep_hash_cls = getattr ( hashes , oaep_hash_fn_name ) mgf1_hash_cls = getattr ( hashes , mgf1_hash_fn_name ) return self . __private_key . decrypt ( data , padding . OAEP ( mgf = padding . MGF1 ( algorithm = mgf1_hash_cls ( ) ) , algorithm = oaep_hash_cls ( ) , label = None ) )
7,609
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L208-L236
[ "def", "is_valid_assignment", "(", "self", ",", "mtf_dimension_name", ",", "mesh_dimension_name", ")", ":", "return", "(", "(", "mtf_dimension_name", "in", "self", ".", "_splittable_mtf_dimension_names", ")", "and", "(", "self", ".", "_mtf_dimension_name_to_size_gcd", "[", "mtf_dimension_name", "]", "%", "self", ".", "_mesh_dimension_name_to_size", "[", "mesh_dimension_name", "]", "==", "0", ")", ")" ]
Validate Perform value validation against validation settings and return simple result object
def validate ( self , value , model = None , context = None ) : length = len ( str ( value ) ) params = dict ( min = self . min , max = self . max ) # too short? if self . min and self . max is None : if length < self . min : return Error ( self . too_short , params ) # too long? if self . max and self . min is None : if length > self . max : return Error ( self . too_long , params ) # within range? if self . min and self . max : if length < self . min or length > self . max : return Error ( self . not_in_range , params ) # success otherwise return Error ( )
7,610
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/validators/length.py#L34-L65
[ "def", "sparse_segment", "(", "cords", ")", ":", "cords", "=", "np", ".", "array", "(", "cords", ")", "+", "1", "slices", "=", "[", "]", "for", "cord", "in", "cords", ":", "slices", ".", "append", "(", "slice", "(", "1", ",", "2", "**", "cord", "+", "1", ",", "2", ")", ")", "grid", "=", "np", ".", "mgrid", "[", "slices", "]", "indices", "=", "grid", ".", "reshape", "(", "len", "(", "cords", ")", ",", "np", ".", "prod", "(", "grid", ".", "shape", "[", "1", ":", "]", ")", ")", ".", "T", "sgrid", "=", "indices", "*", "2.", "**", "-", "cords", "return", "sgrid" ]
Associate arbitrary data with widgetObj .
def qteSaveMacroData ( self , data , widgetObj : QtGui . QWidget = None ) : # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) and ( widgetObj is not None ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # If no widget was specified then use the calling widget. if not widgetObj : widgetObj = self . qteWidget # Store the supplied data in the applet specific macro storage. widgetObj . _qteAdmin . macroData [ self . qteMacroName ( ) ] = data
7,611
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L216-L256
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Retrieve widgetObj specific data previously saved with qteSaveMacroData .
def qteMacroData ( self , widgetObj : QtGui . QWidget = None ) : # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) and ( widgetObj is not None ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # If no widget was specified then use the calling widget. if not widgetObj : widgetObj = self . qteWidget # Retrieve the data structure. try : _ = widgetObj . _qteAdmin . macroData [ self . qteMacroName ( ) ] except KeyError : # If the entry does not exist then this is a bug; create # an empty entry for next time. widgetObj . _qteAdmin . macroData [ self . qteMacroName ( ) ] = None # Return the data. return widgetObj . _qteAdmin . macroData [ self . qteMacroName ( ) ]
7,612
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L259-L306
[ "def", "GetAdGroups", "(", "self", ",", "client_customer_id", ",", "campaign_id", ")", ":", "self", ".", "client", ".", "SetClientCustomerId", "(", "client_customer_id", ")", "selector", "=", "{", "'fields'", ":", "[", "'Id'", ",", "'Name'", ",", "'Status'", "]", ",", "'predicates'", ":", "[", "{", "'field'", ":", "'CampaignId'", ",", "'operator'", ":", "'EQUALS'", ",", "'values'", ":", "[", "campaign_id", "]", "}", ",", "{", "'field'", ":", "'Status'", ",", "'operator'", ":", "'NOT_EQUALS'", ",", "'values'", ":", "[", "'REMOVED'", "]", "}", "]", "}", "adgroups", "=", "self", ".", "client", ".", "GetService", "(", "'AdGroupService'", ")", ".", "get", "(", "selector", ")", "if", "int", "(", "adgroups", "[", "'totalNumEntries'", "]", ")", ">", "0", ":", "return", "adgroups", "[", "'entries'", "]", "else", ":", "return", "None" ]
Specify the applet signatures with which this macro is compatible .
def qteSetAppletSignature ( self , appletSignatures : ( str , tuple , list ) ) : # Convert the argument to a tuple if it is not already a tuple # or list. if not isinstance ( appletSignatures , ( tuple , list ) ) : appletSignatures = appletSignatures , # Ensure that all arguments in the tuple/list are strings. for idx , val in enumerate ( appletSignatures ) : if not isinstance ( val , str ) : args = ( 'appletSignatures' , 'str' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Store the compatible applet signatures as a tuple (of strings). self . _qteAppletSignatures = tuple ( appletSignatures )
7,613
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L343-L377
[ "def", "flushing_disabled", "(", "self", ")", ":", "states", "=", "self", ".", "get_index_translog_disable_flush", "(", ")", ".", "values", "(", ")", "if", "not", "states", ":", "return", "\"unknown\"", "if", "all", "(", "s", "==", "True", "for", "s", "in", "states", ")", ":", "return", "\"disabled\"", "if", "all", "(", "s", "==", "False", "for", "s", "in", "states", ")", ":", "return", "\"enabled\"", "if", "any", "(", "s", "==", "False", "for", "s", "in", "states", ")", ":", "return", "\"some\"", "return", "\"unknown\"" ]
Specify the widget signatures with which this macro is compatible .
def qteSetWidgetSignature ( self , widgetSignatures : ( str , tuple , list ) ) : # Convert the argument to a tuple if it is not already a tuple # or list. if not isinstance ( widgetSignatures , ( tuple , list ) ) : widgetSignatures = widgetSignatures , # Ensure that all arguments in the tuple/list are strings. for idx , val in enumerate ( widgetSignatures ) : if not isinstance ( val , str ) : args = ( 'widgetSignatures' , 'str' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Store the compatible widget signatures as a tuple (of strings). self . _qteWidgetSignatures = tuple ( widgetSignatures )
7,614
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L380-L416
[ "def", "get_users", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEAM_USERS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
This method is called by Qtmacs to prepare the macro for execution .
def qtePrepareToRun ( self ) : # Report the execution attempt. msgObj = QtmacsMessage ( ( self . qteMacroName ( ) , self . qteWidget ) , None ) msgObj . setSignalName ( 'qtesigMacroStart' ) self . qteMain . qtesigMacroStart . emit ( msgObj ) # Try to run the macro and radio the success via the # ``qtesigMacroFinished`` signal. try : self . qteRun ( ) self . qteMain . qtesigMacroFinished . emit ( msgObj ) except Exception as err : if self . qteApplet is None : appID = appSig = None else : appID = self . qteApplet . qteAppletID ( ) appSig = self . qteApplet . qteAppletSignature ( ) msg = ( 'Macro <b>{}</b> (called from the <b>{}</b> applet' ' with ID <b>{}</b>) did not execute properly.' ) msg = msg . format ( self . qteMacroName ( ) , appSig , appID ) if isinstance ( err , QtmacsArgumentError ) : msg += '<br/>' + str ( err ) # Irrespective of the error, log it, enable macro # processing (in case it got disabled), and trigger the # error signal. self . qteMain . qteEnableMacroProcessing ( ) self . qteMain . qtesigMacroError . emit ( msgObj ) self . qteLogger . exception ( msg , exc_info = True , stack_info = True )
7,615
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L418-L469
[ "def", "get_info_by_tail_number", "(", "self", ",", "tail_number", ",", "page", "=", "1", ",", "limit", "=", "100", ")", ":", "url", "=", "REG_BASE", ".", "format", "(", "tail_number", ",", "str", "(", "self", ".", "AUTH_TOKEN", ")", ",", "page", ",", "limit", ")", "return", "self", ".", "_fr24", ".", "get_aircraft_data", "(", "url", ")" ]
Returns true if every formset in formsets is valid .
def all_valid ( formsets ) : valid = True for formset in formsets : if not formset . is_valid ( ) : valid = False return valid
7,616
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L7-L13
[ "def", "createL2456Columns", "(", "network", ",", "networkConfig", ")", ":", "# Create each column", "numCorticalColumns", "=", "networkConfig", "[", "\"numCorticalColumns\"", "]", "for", "i", "in", "xrange", "(", "numCorticalColumns", ")", ":", "networkConfigCopy", "=", "copy", ".", "deepcopy", "(", "networkConfig", ")", "randomSeedBase", "=", "networkConfigCopy", "[", "\"randomSeedBase\"", "]", "networkConfigCopy", "[", "\"L2Params\"", "]", "[", "\"seed\"", "]", "=", "randomSeedBase", "+", "i", "networkConfigCopy", "[", "\"L4Params\"", "]", "[", "\"seed\"", "]", "=", "randomSeedBase", "+", "i", "networkConfigCopy", "[", "\"L5Params\"", "]", "[", "\"seed\"", "]", "=", "randomSeedBase", "+", "i", "networkConfigCopy", "[", "\"L6Params\"", "]", "[", "\"seed\"", "]", "=", "randomSeedBase", "+", "i", "networkConfigCopy", "[", "\"L2Params\"", "]", "[", "\"numOtherCorticalColumns\"", "]", "=", "numCorticalColumns", "-", "1", "networkConfigCopy", "[", "\"L5Params\"", "]", "[", "\"numOtherCorticalColumns\"", "]", "=", "numCorticalColumns", "-", "1", "suffix", "=", "\"_\"", "+", "str", "(", "i", ")", "network", "=", "_createL2456Column", "(", "network", ",", "networkConfigCopy", ",", "suffix", ")", "# Now connect the L2 columns laterally to every other L2 column, and", "# the same for L5 columns.", "for", "i", "in", "range", "(", "networkConfig", "[", "\"numCorticalColumns\"", "]", ")", ":", "suffixSrc", "=", "\"_\"", "+", "str", "(", "i", ")", "for", "j", "in", "range", "(", "networkConfig", "[", "\"numCorticalColumns\"", "]", ")", ":", "if", "i", "!=", "j", ":", "suffixDest", "=", "\"_\"", "+", "str", "(", "j", ")", "network", ".", "link", "(", "\"L2Column\"", "+", "suffixSrc", ",", "\"L2Column\"", "+", "suffixDest", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"feedForwardOutput\"", ",", "destInput", "=", "\"lateralInput\"", ")", "network", ".", "link", "(", "\"L5Column\"", "+", "suffixSrc", ",", "\"L5Column\"", "+", "suffixDest", ",", "\"UniformLink\"", ",", "\"\"", ",", "srcOutput", "=", "\"feedForwardOutput\"", ",", "destInput", "=", "\"lateralInput\"", ")", "enableProfiling", "(", "network", ")", "return", "network" ]
If the form and formsets are valid save the associated models .
def forms_valid ( self , inlines ) : for formset in inlines : formset . save ( ) return HttpResponseRedirect ( self . get_success_url ( ) )
7,617
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L34-L40
[ "def", "get_monitors", "(", "self", ",", "condition", "=", "None", ",", "page_size", "=", "1000", ")", ":", "req_kwargs", "=", "{", "}", "if", "condition", ":", "req_kwargs", "[", "'condition'", "]", "=", "condition", ".", "compile", "(", ")", "for", "monitor_data", "in", "self", ".", "_conn", ".", "iter_json_pages", "(", "\"/ws/Monitor\"", ",", "*", "*", "req_kwargs", ")", ":", "yield", "DeviceCloudMonitor", ".", "from_json", "(", "self", ".", "_conn", ",", "monitor_data", ",", "self", ".", "_tcp_client_manager", ")" ]
Handles POST requests instantiating a form and formset instances with the passed POST variables and then checked for validity .
def post ( self , request , * args , * * kwargs ) : self . object = self . get_object ( ) self . get_context_data ( ) inlines = self . construct_inlines ( ) if all_valid ( inlines ) : return self . forms_valid ( inlines ) return self . forms_invalid ( inlines )
7,618
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L60-L71
[ "def", "correspondence", "(", "soup", ")", ":", "correspondence", "=", "[", "]", "author_notes_nodes", "=", "raw_parser", ".", "author_notes", "(", "soup", ")", "if", "author_notes_nodes", ":", "corresp_nodes", "=", "raw_parser", ".", "corresp", "(", "author_notes_nodes", ")", "for", "tag", "in", "corresp_nodes", ":", "correspondence", ".", "append", "(", "tag", ".", "text", ")", "return", "correspondence" ]
Returns the supplied success URL .
def get_success_url ( self ) : if self . success_url : # Forcing possible reverse_lazy evaluation url = force_text ( self . success_url ) else : raise ImproperlyConfigured ( "No URL to redirect to. Provide a success_url." ) return url
7,619
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L78-L88
[ "def", "wave_infochunk", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "file", ":", "if", "file", ".", "read", "(", "4", ")", "!=", "b\"RIFF\"", ":", "return", "None", "data_size", "=", "file", ".", "read", "(", "4", ")", "# container size", "if", "file", ".", "read", "(", "4", ")", "!=", "b\"WAVE\"", ":", "return", "None", "while", "True", ":", "chunkid", "=", "file", ".", "read", "(", "4", ")", "sizebuf", "=", "file", ".", "read", "(", "4", ")", "if", "len", "(", "sizebuf", ")", "<", "4", "or", "len", "(", "chunkid", ")", "<", "4", ":", "return", "None", "size", "=", "struct", ".", "unpack", "(", "b'<L'", ",", "sizebuf", ")", "[", "0", "]", "if", "chunkid", "[", "0", ":", "3", "]", "!=", "b\"fmt\"", ":", "if", "size", "%", "2", "==", "1", ":", "seek", "=", "size", "+", "1", "else", ":", "seek", "=", "size", "file", ".", "seek", "(", "size", ",", "1", ")", "else", ":", "return", "bytearray", "(", "b\"RIFF\"", "+", "data_size", "+", "b\"WAVE\"", "+", "chunkid", "+", "sizebuf", "+", "file", ".", "read", "(", "size", ")", ")" ]
Display the last status message and partially completed key sequences .
def displayStatusMessage ( self , msgObj ) : # Ensure the message ends with a newline character. msg = msgObj . data if not msg . endswith ( '\n' ) : msg = msg + '\n' # Display the message in the status field. self . qteLabel . setText ( msg )
7,620
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/statusbar.py#L78-L101
[ "def", "user_can_edit_news", "(", "user", ")", ":", "newsitem_models", "=", "[", "model", ".", "get_newsitem_model", "(", ")", "for", "model", "in", "NEWSINDEX_MODEL_CLASSES", "]", "if", "user", ".", "is_active", "and", "user", ".", "is_superuser", ":", "# admin can edit news iff any news types exist", "return", "bool", "(", "newsitem_models", ")", "for", "NewsItem", "in", "newsitem_models", ":", "for", "perm", "in", "format_perms", "(", "NewsItem", ",", "[", "'add'", ",", "'change'", ",", "'delete'", "]", ")", ":", "if", "user", ".", "has_perm", "(", "perm", ")", ":", "return", "True", "return", "False" ]
Fetch and display the next batch of log messages .
def qteUpdateLogSlot ( self ) : # Fetch all log records that have arrived since the last # fetch() call and update the record counter. log = self . logHandler . fetch ( start = self . qteLogCnt ) self . qteLogCnt += len ( log ) # Return immediately if no log message is available (this case # should be impossible). if not len ( log ) : return # Remove all duplicate entries and count their repetitions. log_pruned = [ ] last_entry = log [ 0 ] num_rep = - 1 for cur_entry in log : # If the previous log message is identical to the current # one increase its repetition counter. If the two log # messages differ, add the last message to the output log # and reset the repetition counter. if last_entry . msg == cur_entry . msg : num_rep += 1 else : log_pruned . append ( [ last_entry , num_rep ] ) num_rep = 0 last_entry = cur_entry # The very last entry must be added by hand. log_pruned . append ( [ cur_entry , num_rep ] ) # Format the log entries (eg. color coding etc.) log_formatted = "" for cur_entry in log_pruned : log_formatted += self . qteFormatMessage ( cur_entry [ 0 ] , cur_entry [ 1 ] ) log_formatted + '\n' # Insert the formatted text all at once as calls to insertHtml # are expensive. self . qteText . insertHtml ( log_formatted ) self . qteMoveToEndOfBuffer ( ) # If the log contained an error (or something else of interest # to the user) then switch to the messages buffer (ie. switch # to this very applet). if self . qteAutoActivate : self . qteAutoActivate = False self . qteMain . qteMakeAppletActive ( self )
7,621
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/logviewer.py#L196-L246
[ "def", "_is_charge_balanced", "(", "struct", ")", ":", "if", "sum", "(", "[", "s", ".", "specie", ".", "oxi_state", "for", "s", "in", "struct", ".", "sites", "]", ")", "==", "0.0", ":", "return", "True", "else", ":", "return", "False" ]
Move cursor to the end of the buffer to facilitate auto scrolling .
def qteMoveToEndOfBuffer ( self ) : tc = self . qteText . textCursor ( ) tc . movePosition ( QtGui . QTextCursor . End ) self . qteText . setTextCursor ( tc )
7,622
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/logviewer.py#L248-L259
[ "def", "_build_template_map", "(", "cookbook", ",", "cookbook_name", ",", "stencil", ")", ":", "template_map", "=", "{", "'cookbook'", ":", "{", "\"name\"", ":", "cookbook_name", "}", ",", "'options'", ":", "stencil", "[", "'options'", "]", "}", "# Cookbooks may not yet have metadata, so we pass an empty dict if so", "try", ":", "template_map", "[", "'cookbook'", "]", "=", "cookbook", ".", "metadata", ".", "to_dict", "(", ")", ".", "copy", "(", ")", "except", "ValueError", ":", "# ValueError may be returned if this cookbook does not yet have any", "# metadata.rb written by a stencil. This is okay, as everyone should", "# be using the base stencil first, and then we'll try to call", "# cookbook.metadata again in this method later down.", "pass", "template_map", "[", "'cookbook'", "]", "[", "'year'", "]", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "year", "return", "template_map" ]
Function for iterating through a list of profile components and signing separate individual profile tokens .
def sign_token_records ( profile_components , parent_private_key , signing_algorithm = "ES256K" ) : if signing_algorithm != "ES256K" : raise ValueError ( "Signing algorithm not supported" ) token_records = [ ] for profile_component in profile_components : private_key = ECPrivateKey ( parent_private_key ) public_key = private_key . public_key ( ) subject = { "publicKey" : public_key . to_hex ( ) } token = sign_token ( profile_component , private_key . to_hex ( ) , subject , signing_algorithm = signing_algorithm ) token_record = wrap_token ( token ) token_record [ "parentPublicKey" ] = public_key . to_hex ( ) token_records . append ( token_record ) return token_records
7,623
https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/token_signing.py#L46-L69
[ "def", "arcball_constrain_to_axis", "(", "point", ",", "axis", ")", ":", "v", "=", "np", ".", "array", "(", "point", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "True", ")", "a", "=", "np", ".", "array", "(", "axis", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "True", ")", "v", "-=", "a", "*", "np", ".", "dot", "(", "a", ",", "v", ")", "# on plane", "n", "=", "vector_norm", "(", "v", ")", "if", "n", ">", "_EPS", ":", "if", "v", "[", "2", "]", "<", "0.0", ":", "np", ".", "negative", "(", "v", ",", "v", ")", "v", "/=", "n", "return", "v", "if", "a", "[", "2", "]", "==", "1.0", ":", "return", "np", ".", "array", "(", "[", "1.0", ",", "0.0", ",", "0.0", "]", ")", "return", "unit_vector", "(", "[", "-", "a", "[", "1", "]", ",", "a", "[", "0", "]", ",", "0.0", "]", ")" ]
Normalize locale Extracts language code from passed in locale string to be used later for dictionaries loading .
def normalize_locale ( locale ) : import re match = re . match ( r'^[a-z]+' , locale . lower ( ) ) if match : return match . group ( )
7,624
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L22-L34
[ "def", "squareRoot", "(", "requestContext", ",", "seriesList", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"squareRoot(%s)\"", "%", "(", "series", ".", "name", ")", "for", "i", ",", "value", "in", "enumerate", "(", "series", ")", ":", "series", "[", "i", "]", "=", "safePow", "(", "value", ",", "0.5", ")", "return", "seriesList" ]
Get translation dictionary Returns a dictionary for locale or raises an exception if such can t be located . If a dictionary for locale was previously loaded returns that otherwise goes through registered locations and merges any found custom dictionaries with defaults .
def get_translations ( self , locale ) : locale = self . normalize_locale ( locale ) if locale in self . translations : return self . translations [ locale ] translations = { } for path in self . dirs : file = os . path . join ( path , '{}.py' . format ( locale ) ) if not os . path . isfile ( file ) : continue loader = SourceFileLoader ( locale , file ) locale_dict = loader . load_module ( ) if not hasattr ( locale_dict , 'translations' ) : continue language = getattr ( locale_dict , 'translations' ) if translations : translations = language else : merged = dict ( translations . items ( ) | language . items ( ) ) translations = merged if translations : self . translations [ locale ] = translations return translations err = 'No translations found for locale [{}]' raise NoTranslations ( err . format ( locale ) )
7,625
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L51-L89
[ "def", "close", "(", "self", ")", ":", "self", ".", "alive", "=", "False", "self", ".", "rxThread", ".", "join", "(", ")", "self", ".", "serial", ".", "close", "(", ")" ]
Translate Translates a message to the given locale language . Will return original message if no translation exists for the message .
def translate ( self , message , locale ) : translations = self . get_translations ( locale ) if message in translations : return translations [ message ] # return untranslated return message
7,626
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L93-L108
[ "def", "add", "(", "self", ",", "opener", ")", ":", "index", "=", "len", "(", "self", ".", "openers", ")", "self", ".", "openers", "[", "index", "]", "=", "opener", "for", "name", "in", "opener", ".", "names", ":", "self", ".", "registry", "[", "name", "]", "=", "index" ]
Flatten a multi - deminision list and return a iterable
def flatten ( l ) : for el in l : # I don;t want dict to be flattened if isinstance ( el , Iterable ) and not isinstance ( el , ( str , bytes ) ) and not isinstance ( el , dict ) : yield from flatten ( el ) else : yield el
7,627
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L33-L50
[ "def", "_connect_hive", "(", "self", ",", "hive", ")", ":", "try", ":", "handle", "=", "self", ".", "_remote_hives", "[", "hive", "]", "except", "KeyError", ":", "handle", "=", "win32", ".", "RegConnectRegistry", "(", "self", ".", "_machine", ",", "hive", ")", "self", ".", "_remote_hives", "[", "hive", "]", "=", "handle", "return", "handle" ]
Taken a list of lists returns a big list of lists contain all the possibilities of elements of sublist combining together .
def crossCombine ( l ) : resultList = [ ] firstList = l [ 0 ] rest = l [ 1 : ] if len ( rest ) == 0 : return firstList for e in firstList : for e1 in crossCombine ( rest ) : resultList . append ( combinteDict ( e , e1 ) ) return resultList
7,628
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L53-L82
[ "def", "user_agent", "(", "self", ",", "text", ",", "*", "*", "kwargs", ")", ":", "indicator_obj", "=", "UserAgent", "(", "text", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_indicator", "(", "indicator_obj", ")" ]
Combine to argument into a single flat list
def combine ( a1 , a2 ) : if not isinstance ( a1 , list ) : a1 = [ a1 ] if not isinstance ( a2 , list ) : a2 = [ a2 ] return a1 + a2
7,629
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L85-L101
[ "def", "_validate_checksum", "(", "self", ",", "buffer", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"Validating the buffer\"", ")", "if", "len", "(", "buffer", ")", "==", "0", ":", "self", ".", "_log", ".", "debug", "(", "\"Buffer was empty\"", ")", "if", "self", ".", "_conn", ".", "isOpen", "(", ")", ":", "self", ".", "_log", ".", "debug", "(", "'Closing connection'", ")", "self", ".", "_conn", ".", "close", "(", ")", "return", "False", "p0", "=", "hex2int", "(", "buffer", "[", "0", "]", ")", "p1", "=", "hex2int", "(", "buffer", "[", "1", "]", ")", "checksum", "=", "sum", "(", "[", "hex2int", "(", "c", ")", "for", "c", "in", "buffer", "[", ":", "35", "]", "]", ")", "&", "0xFF", "p35", "=", "hex2int", "(", "buffer", "[", "35", "]", ")", "if", "p0", "!=", "165", "or", "p1", "!=", "150", "or", "p35", "!=", "checksum", ":", "self", ".", "_log", ".", "debug", "(", "\"Buffer checksum was not valid\"", ")", "return", "False", "return", "True" ]
Chech an object is single or pair or neither .
def singleOrPair ( obj ) : if len ( list ( obj . __class__ . __mro__ ) ) <= 2 : return 'Neither' else : # Pair check comes first for Pair is a subclass of Single if ancestorJr ( obj ) is Pair : return 'Pair' elif ancestor ( obj ) is Single : return 'Single' else : return 'Neither'
7,630
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L146-L166
[ "def", "create_supercut_in_batches", "(", "composition", ",", "outputfile", ",", "padding", ")", ":", "total_clips", "=", "len", "(", "composition", ")", "start_index", "=", "0", "end_index", "=", "BATCH_SIZE", "batch_comp", "=", "[", "]", "while", "start_index", "<", "total_clips", ":", "filename", "=", "outputfile", "+", "'.tmp'", "+", "str", "(", "start_index", ")", "+", "'.mp4'", "try", ":", "create_supercut", "(", "composition", "[", "start_index", ":", "end_index", "]", ",", "filename", ",", "padding", ")", "batch_comp", ".", "append", "(", "filename", ")", "gc", ".", "collect", "(", ")", "start_index", "+=", "BATCH_SIZE", "end_index", "+=", "BATCH_SIZE", "except", ":", "start_index", "+=", "BATCH_SIZE", "end_index", "+=", "BATCH_SIZE", "next", "clips", "=", "[", "VideoFileClip", "(", "filename", ")", "for", "filename", "in", "batch_comp", "]", "video", "=", "concatenate", "(", "clips", ")", "video", ".", "to_videofile", "(", "outputfile", ",", "codec", "=", "\"libx264\"", ",", "temp_audiofile", "=", "'temp-audio.m4a'", ",", "remove_temp", "=", "True", ",", "audio_codec", "=", "'aac'", ")", "# remove partial video files", "for", "filename", "in", "batch_comp", ":", "os", ".", "remove", "(", "filename", ")", "cleanup_log_files", "(", "outputfile", ")" ]
Remove every instance that matches the input from a list
def removeEverything ( toBeRemoved , l ) : successful = True while successful : try : # list.remove will remove item if equal, # which is evaluated by __eq__ l . remove ( toBeRemoved ) except : successful = False
7,631
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L169-L185
[ "def", "__rv_french", "(", "self", ",", "word", ",", "vowels", ")", ":", "rv", "=", "\"\"", "if", "len", "(", "word", ")", ">=", "2", ":", "if", "(", "word", ".", "startswith", "(", "(", "\"par\"", ",", "\"col\"", ",", "\"tap\"", ")", ")", "or", "(", "word", "[", "0", "]", "in", "vowels", "and", "word", "[", "1", "]", "in", "vowels", ")", ")", ":", "rv", "=", "word", "[", "3", ":", "]", "else", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "word", ")", ")", ":", "if", "word", "[", "i", "]", "in", "vowels", ":", "rv", "=", "word", "[", "i", "+", "1", ":", "]", "break", "return", "rv" ]
convert value and add to self . value
def add ( self , * value ) : flattenedValueList = list ( flatten ( value ) ) return self . _add ( flattenedValueList , self . value )
7,632
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L309-L319
[ "def", "_decrypt_ciphertext", "(", "cipher", ")", ":", "try", ":", "cipher", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "cipher", ")", ".", "replace", "(", "r'\\n'", ",", "'\\n'", ")", "except", "UnicodeDecodeError", ":", "# ciphertext is binary", "pass", "cipher", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_bytes", "(", "cipher", ")", "cmd", "=", "[", "_get_gpg_exec", "(", ")", ",", "'--homedir'", ",", "_get_key_dir", "(", ")", ",", "'--status-fd'", ",", "'2'", ",", "'--no-tty'", ",", "'-d'", "]", "proc", "=", "Popen", "(", "cmd", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "shell", "=", "False", ")", "decrypted_data", ",", "decrypt_error", "=", "proc", ".", "communicate", "(", "input", "=", "cipher", ")", "if", "not", "decrypted_data", ":", "try", ":", "cipher", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "cipher", ")", "except", "UnicodeDecodeError", ":", "# decrypted data contains undecodable binary data", "pass", "log", ".", "warning", "(", "'Could not decrypt cipher %s, received: %s'", ",", "cipher", ",", "decrypt_error", ")", "return", "cipher", "else", ":", "try", ":", "decrypted_data", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "decrypted_data", ")", "except", "UnicodeDecodeError", ":", "# decrypted data contains undecodable binary data", "pass", "return", "decrypted_data" ]
Remove elements from a list by matching the elements in the other list .
def _remove ( self , removeList , selfValue ) : for removeValue in removeList : print ( removeValue , removeList ) # if removeValue equal to selfValue, remove removeEverything ( removeValue , selfValue )
7,633
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L321-L335
[ "def", "spkopa", "(", "filename", ")", ":", "filename", "=", "stypes", ".", "stringToCharP", "(", "filename", ")", "handle", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "spkopa_c", "(", "filename", ",", "ctypes", ".", "byref", "(", "handle", ")", ")", "return", "handle", ".", "value" ]
remove elements from self . value by matching .
def remove ( self , * l ) : removeList = list ( flatten ( l ) ) self . _remove ( removeList , self . value )
7,634
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L337-L347
[ "def", "make_android_api_method", "(", "req_method", ",", "secure", "=", "True", ",", "version", "=", "0", ")", ":", "def", "outer_func", "(", "func", ")", ":", "def", "inner_func", "(", "self", ",", "*", "*", "kwargs", ")", ":", "req_url", "=", "self", ".", "_build_request_url", "(", "secure", ",", "func", ".", "__name__", ",", "version", ")", "req_func", "=", "self", ".", "_build_request", "(", "req_method", ",", "req_url", ",", "params", "=", "kwargs", ")", "response", "=", "req_func", "(", ")", "func", "(", "self", ",", "response", ")", "return", "response", "return", "inner_func", "return", "outer_func" ]
Write the job to the corresponding plist .
def write ( self ) : with open ( self . me , 'w' ) as f : f . write ( self . printMe ( self . tag , self . value ) )
7,635
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L367-L370
[ "def", "remove_diskgroup", "(", "cache_disk_id", ",", "data_accessibility", "=", "True", ",", "service_instance", "=", "None", ")", ":", "log", ".", "trace", "(", "'Validating diskgroup input'", ")", "host_ref", "=", "_get_proxy_target", "(", "service_instance", ")", "hostname", "=", "__proxy__", "[", "'esxi.get_details'", "]", "(", ")", "[", "'esxi_host'", "]", "diskgroups", "=", "salt", ".", "utils", ".", "vmware", ".", "get_diskgroups", "(", "host_ref", ",", "cache_disk_ids", "=", "[", "cache_disk_id", "]", ")", "if", "not", "diskgroups", ":", "raise", "VMwareObjectRetrievalError", "(", "'No diskgroup with cache disk id \\'{0}\\' was found in ESXi '", "'host \\'{1}\\''", ".", "format", "(", "cache_disk_id", ",", "hostname", ")", ")", "log", ".", "trace", "(", "'data accessibility = %s'", ",", "data_accessibility", ")", "salt", ".", "utils", ".", "vsan", ".", "remove_diskgroup", "(", "service_instance", ",", "host_ref", ",", "diskgroups", "[", "0", "]", ",", "data_accessibility", "=", "data_accessibility", ")", "return", "True" ]
add inner to outer
def add ( self , * l ) : for a in flatten ( l ) : self . _add ( [ self . Inner ( a ) ] , self . l )
7,636
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L593-L600
[ "def", "get_user_last_submissions", "(", "self", ",", "limit", "=", "5", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "{", "}", "request", ".", "update", "(", "{", "\"username\"", ":", "self", ".", "_user_manager", ".", "session_username", "(", ")", "}", ")", "# Before, submissions were first sorted by submission date, then grouped", "# and then resorted by submission date before limiting. Actually, grouping", "# and pushing, keeping the max date, followed by result filtering is much more", "# efficient", "data", "=", "self", ".", "_database", ".", "submissions", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "request", "}", ",", "{", "\"$group\"", ":", "{", "\"_id\"", ":", "{", "\"courseid\"", ":", "\"$courseid\"", ",", "\"taskid\"", ":", "\"$taskid\"", "}", ",", "\"submitted_on\"", ":", "{", "\"$max\"", ":", "\"$submitted_on\"", "}", ",", "\"submissions\"", ":", "{", "\"$push\"", ":", "{", "\"_id\"", ":", "\"$_id\"", ",", "\"result\"", ":", "\"$result\"", ",", "\"status\"", ":", "\"$status\"", ",", "\"courseid\"", ":", "\"$courseid\"", ",", "\"taskid\"", ":", "\"$taskid\"", ",", "\"submitted_on\"", ":", "\"$submitted_on\"", "}", "}", ",", "}", "}", ",", "{", "\"$project\"", ":", "{", "\"submitted_on\"", ":", "1", ",", "\"submissions\"", ":", "{", "# This could be replaced by $filter if mongo v3.2 is set as dependency", "\"$setDifference\"", ":", "[", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$submissions\"", ",", "\"as\"", ":", "\"submission\"", ",", "\"in\"", ":", "{", "\"$cond\"", ":", "[", "{", "\"$eq\"", ":", "[", "\"$submitted_on\"", ",", "\"$$submission.submitted_on\"", "]", "}", ",", "\"$$submission\"", ",", "False", "]", "}", "}", "}", ",", "[", "False", "]", "]", "}", "}", "}", ",", "{", "\"$sort\"", ":", "{", "\"submitted_on\"", ":", "pymongo", ".", "DESCENDING", "}", "}", ",", "{", "\"$limit\"", ":", "limit", "}", "]", ")", "return", "[", "item", "[", "\"submissions\"", "]", "[", "0", "]", "for", "item", "in", "data", "]" ]
remove inner from outer
def remove ( self , * l ) : for a in flatten ( l ) : self . _remove ( [ self . Inner ( a ) ] , self . l )
7,637
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L602-L609
[ "def", "getMetastable", "(", "rates", ",", "ver", ":", "np", ".", "ndarray", ",", "lamb", ",", "br", ",", "reactfn", ":", "Path", ")", ":", "with", "h5py", ".", "File", "(", "reactfn", ",", "'r'", ")", "as", "f", ":", "A", "=", "f", "[", "'/metastable/A'", "]", "[", ":", "]", "lambnew", "=", "f", "[", "'/metastable/lambda'", "]", ".", "value", ".", "ravel", "(", "order", "=", "'F'", ")", "# some are not 1-D!", "vnew", "=", "np", ".", "concatenate", "(", "(", "A", "[", ":", "2", "]", "*", "rates", ".", "loc", "[", "...", ",", "'no1s'", "]", ".", "values", "[", ":", ",", "None", "]", ",", "A", "[", "2", ":", "4", "]", "*", "rates", ".", "loc", "[", "...", ",", "'no1d'", "]", ".", "values", "[", ":", ",", "None", "]", ",", "A", "[", "4", ":", "]", "*", "rates", ".", "loc", "[", "...", ",", "'noii2p'", "]", ".", "values", "[", ":", ",", "None", "]", ")", ",", "axis", "=", "-", "1", ")", "assert", "vnew", ".", "shape", "==", "(", "rates", ".", "shape", "[", "0", "]", ",", "A", ".", "size", ")", "return", "catvl", "(", "rates", ".", "alt_km", ",", "ver", ",", "vnew", ",", "lamb", ",", "lambnew", ",", "br", ")" ]
adds a dict as pair
def add ( self , dic ) : for kw in dic : checkKey ( kw , self . keyWord ) self . _add ( [ Pair ( kw , StringSingle ( dic [ kw ] ) ) ] , self . d )
7,638
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L661-L669
[ "def", "pip_install_requirements", "(", "requirements", ",", "constraints", "=", "None", ",", "*", "*", "options", ")", ":", "command", "=", "[", "\"install\"", "]", "available_options", "=", "(", "'proxy'", ",", "'src'", ",", "'log'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "command", ".", "append", "(", "\"-r {0}\"", ".", "format", "(", "requirements", ")", ")", "if", "constraints", ":", "command", ".", "append", "(", "\"-c {0}\"", ".", "format", "(", "constraints", ")", ")", "log", "(", "\"Installing from file: {} with constraints {} \"", "\"and options: {}\"", ".", "format", "(", "requirements", ",", "constraints", ",", "command", ")", ")", "else", ":", "log", "(", "\"Installing from file: {} with options: {}\"", ".", "format", "(", "requirements", ",", "command", ")", ")", "pip_execute", "(", "command", ")" ]
remove the pair by passing a identical dict
def remove ( self , dic ) : for kw in dic : removePair = Pair ( kw , dic [ kw ] ) self . _remove ( [ removePair ] )
7,639
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L671-L679
[ "def", "segment", "(", "self", ",", "webvtt", ",", "output", "=", "''", ",", "seconds", "=", "SECONDS", ",", "mpegts", "=", "MPEGTS", ")", ":", "if", "isinstance", "(", "webvtt", ",", "str", ")", ":", "# if a string is supplied we parse the file", "captions", "=", "WebVTT", "(", ")", ".", "read", "(", "webvtt", ")", ".", "captions", "elif", "not", "self", ".", "_validate_webvtt", "(", "webvtt", ")", ":", "raise", "InvalidCaptionsError", "(", "'The captions provided are invalid'", ")", "else", ":", "# we expect to have a webvtt object", "captions", "=", "webvtt", ".", "captions", "self", ".", "_total_segments", "=", "0", "if", "not", "captions", "else", "int", "(", "ceil", "(", "captions", "[", "-", "1", "]", ".", "end_in_seconds", "/", "seconds", ")", ")", "self", ".", "_output_folder", "=", "output", "self", ".", "_seconds", "=", "seconds", "self", ".", "_mpegts", "=", "mpegts", "output_folder", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "output", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "output_folder", ")", ":", "os", ".", "makedirs", "(", "output_folder", ")", "self", ".", "_slice_segments", "(", "captions", ")", "self", ".", "_write_segments", "(", ")", "self", ".", "_write_manifest", "(", ")" ]
update self . value with basenumber and time interval
def _update ( self , baseNumber , magnification ) : interval = int ( baseNumber * magnification ) self . value = [ IntegerSingle ( interval ) ]
7,640
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L876-L884
[ "def", "get_vector", "(", "self", ")", ":", "vec", "=", "{", "}", "for", "dim", "in", "[", "'forbidden'", ",", "'required'", ",", "'permitted'", "]", ":", "if", "self", ".", "survey", "[", "dim", "]", "is", "None", ":", "continue", "dim_vec", "=", "map", "(", "lambda", "x", ":", "(", "x", "[", "'tag'", "]", ",", "x", "[", "'answer'", "]", ")", ",", "self", ".", "survey", "[", "dim", "]", ")", "vec", "[", "dim", "]", "=", "dict", "(", "dim_vec", ")", "return", "vec" ]
set unit to second
def second ( self ) : self . magnification = 1 self . _update ( self . baseNumber , self . magnification ) return self
7,641
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L887-L891
[ "def", "mol_supplier", "(", "lines", ",", "no_halt", ",", "assign_descriptors", ")", ":", "def", "sdf_block", "(", "lns", ")", ":", "mol", "=", "[", "]", "opt", "=", "[", "]", "is_mol", "=", "True", "for", "line", "in", "lns", ":", "if", "line", ".", "startswith", "(", "\"$$$$\"", ")", ":", "yield", "mol", "[", ":", "]", ",", "opt", "[", ":", "]", "is_mol", "=", "True", "mol", ".", "clear", "(", ")", "opt", ".", "clear", "(", ")", "elif", "line", ".", "startswith", "(", "\"M END\"", ")", ":", "is_mol", "=", "False", "elif", "is_mol", ":", "mol", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "else", ":", "opt", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "if", "mol", ":", "yield", "mol", ",", "opt", "for", "i", ",", "(", "mol", ",", "opt", ")", "in", "enumerate", "(", "sdf_block", "(", "lines", ")", ")", ":", "try", ":", "c", "=", "molecule", "(", "mol", ")", "if", "assign_descriptors", ":", "molutil", ".", "assign_descriptors", "(", "c", ")", "except", "ValueError", "as", "err", ":", "if", "no_halt", ":", "print", "(", "\"Unsupported symbol: {} (#{} in v2000reader)\"", ".", "format", "(", "err", ",", "i", "+", "1", ")", ")", "c", "=", "molutil", ".", "null_molecule", "(", "assign_descriptors", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported symbol: {}\"", ".", "format", "(", "err", ")", ")", "except", "RuntimeError", "as", "err", ":", "if", "no_halt", ":", "print", "(", "\"Failed to minimize ring: {} (#{} in v2000reader)\"", ".", "format", "(", "err", ",", "i", "+", "1", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Failed to minimize ring: {}\"", ".", "format", "(", "err", ")", ")", "except", ":", "if", "no_halt", ":", "print", "(", "\"Unexpected error (#{} in v2000reader)\"", ".", "format", "(", "i", "+", "1", ")", ")", "c", "=", "molutil", ".", "null_molecule", "(", "assign_descriptors", ")", "c", ".", "data", "=", "optional_data", "(", "opt", ")", "yield", "c", "continue", "else", ":", "print", "(", "traceback", ".", "format_exc", "(", ")", ")", "raise", "Exception", "(", "\"Unsupported Error\"", ")", "c", ".", "data", "=", "optional_data", "(", "opt", ")", "yield", "c" ]
set unit to minute
def minute ( self ) : self . magnification = 60 self . _update ( self . baseNumber , self . magnification ) return self
7,642
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L894-L898
[ "def", "etm_supported", "(", "self", ")", ":", "res", "=", "self", ".", "_dll", ".", "JLINKARM_ETM_IsPresent", "(", ")", "if", "(", "res", "==", "1", ")", ":", "return", "True", "# JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices. This", "# fallback checks if ETM is present by checking the Cortex ROM table", "# for debugging information for ETM.", "info", "=", "ctypes", ".", "c_uint32", "(", "0", ")", "index", "=", "enums", ".", "JLinkROMTable", ".", "ETM", "res", "=", "self", ".", "_dll", ".", "JLINKARM_GetDebugInfo", "(", "index", ",", "ctypes", ".", "byref", "(", "info", ")", ")", "if", "(", "res", "==", "1", ")", ":", "return", "False", "return", "True" ]
set unit to hour
def hour ( self ) : self . magnification = 3600 self . _update ( self . baseNumber , self . magnification ) return self
7,643
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L901-L905
[ "def", "_get_env_var", "(", "env_var_name", ")", ":", "if", "env_var_name", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "env_var_name", "]", "fname", "=", "os", ".", "path", ".", "join", "(", "get_home", "(", ")", ",", "'.tangorc'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "fname", "=", "\"/etc/tangorc\"", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "None", "for", "line", "in", "open", "(", "fname", ")", ":", "strippedline", "=", "line", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "not", "strippedline", ":", "# empty line", "continue", "tup", "=", "strippedline", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "tup", ")", "!=", "2", ":", "# illegal line!", "continue", "key", ",", "val", "=", "map", "(", "str", ".", "strip", ",", "tup", ")", "if", "key", "==", "env_var_name", ":", "return", "val" ]
set unit to day
def day ( self ) : self . magnification = 86400 self . _update ( self . baseNumber , self . magnification ) return self
7,644
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L908-L912
[ "def", "robust_data_range", "(", "arr", ",", "robust", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "# from the seaborn code ", "# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201", "def", "_get_vmin_vmax", "(", "arr2d", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "if", "vmin", "is", "None", ":", "vmin", "=", "np", ".", "percentile", "(", "arr2d", ",", "2", ")", "if", "robust", "else", "arr2d", ".", "min", "(", ")", "if", "vmax", "is", "None", ":", "vmax", "=", "np", ".", "percentile", "(", "arr2d", ",", "98", ")", "if", "robust", "else", "arr2d", ".", "max", "(", ")", "return", "vmin", ",", "vmax", "if", "len", "(", "arr", ".", "shape", ")", "==", "3", "and", "vmin", "is", "None", "and", "vmax", "is", "None", ":", "vmin", "=", "[", "]", "vmax", "=", "[", "]", "for", "i", "in", "range", "(", "arr", ".", "shape", "[", "2", "]", ")", ":", "arr_i", "=", "arr", "[", ":", ",", ":", ",", "i", "]", "vmin_i", ",", "vmax_i", "=", "_get_vmin_vmax", "(", "arr_i", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", "vmin", ".", "append", "(", "vmin_i", ")", "vmax", ".", "append", "(", "vmax_i", ")", "else", ":", "vmin", ",", "vmax", "=", "_get_vmin_vmax", "(", "arr", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "return", "vmin", ",", "vmax" ]
set unit to week
def week ( self ) : self . magnification = 345600 self . _update ( self . baseNumber , self . magnification ) return self
7,645
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L915-L919
[ "def", "robust_data_range", "(", "arr", ",", "robust", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "# from the seaborn code ", "# https://github.com/mwaskom/seaborn/blob/3a3ec75befab52c02650c62772a90f8c23046038/seaborn/matrix.py#L201", "def", "_get_vmin_vmax", "(", "arr2d", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "if", "vmin", "is", "None", ":", "vmin", "=", "np", ".", "percentile", "(", "arr2d", ",", "2", ")", "if", "robust", "else", "arr2d", ".", "min", "(", ")", "if", "vmax", "is", "None", ":", "vmax", "=", "np", ".", "percentile", "(", "arr2d", ",", "98", ")", "if", "robust", "else", "arr2d", ".", "max", "(", ")", "return", "vmin", ",", "vmax", "if", "len", "(", "arr", ".", "shape", ")", "==", "3", "and", "vmin", "is", "None", "and", "vmax", "is", "None", ":", "vmin", "=", "[", "]", "vmax", "=", "[", "]", "for", "i", "in", "range", "(", "arr", ".", "shape", "[", "2", "]", ")", ":", "arr_i", "=", "arr", "[", ":", ",", ":", ",", "i", "]", "vmin_i", ",", "vmax_i", "=", "_get_vmin_vmax", "(", "arr_i", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", "vmin", ".", "append", "(", "vmin_i", ")", "vmax", ".", "append", "(", "vmax_i", ")", "else", ":", "vmin", ",", "vmax", "=", "_get_vmin_vmax", "(", "arr", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "return", "vmin", ",", "vmax" ]
add a config to StartCalendarInterval .
def add ( self , * dic ) : dicList = list ( flatten ( dic ) ) # for every dict in the list passed in for d in dicList : # make a dict single (list of pairs) di = [ ] for k in d : # checkKey(k, self.keyWord) di . append ( Pair ( k , IntegerSingle ( d [ k ] ) ) ) dictSingle = DictSingle ( di ) # append dict single to array single's value self . _add ( [ dictSingle ] , self . l )
7,646
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L963-L979
[ "def", "error403", "(", "error", ")", ":", "tb", "=", "error", ".", "traceback", "if", "isinstance", "(", "tb", ",", "dict", ")", "and", "\"name\"", "in", "tb", "and", "\"uuid\"", "in", "tb", ":", "return", "SimpleTemplate", "(", "PRIVATE_ACCESS_MSG", ")", ".", "render", "(", "name", "=", "error", ".", "traceback", "[", "\"name\"", "]", ",", "uuid", "=", "error", ".", "traceback", "[", "\"uuid\"", "]", ")", "return", "\"Access denied!\"" ]
remove a calendar config .
def remove ( self , * dic ) : dicList = list ( flatten ( dic ) ) for d in dicList : di = [ ] for k in d : # checkkey(k, self.keyword) di . append ( Pair ( k , IntegerSingle ( d [ k ] ) ) ) dictSingle = DictSingle ( di ) # append dict single to array single self . _remove ( [ dictSingle ] , self . l )
7,647
https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L981-L995
[ "def", "silence", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "flag_set", ":", "AbstractSet", "[", "Flag", "]", ",", "flag_op", ":", "FlagOp", ")", "->", "None", ":", "session_flags", "=", "self", ".", "session_flags", "permanent_flag_set", "=", "self", ".", "permanent_flags", "&", "flag_set", "session_flag_set", "=", "session_flags", "&", "flag_set", "for", "seq", ",", "msg", "in", "self", ".", "_messages", ".", "get_all", "(", "seq_set", ")", ":", "msg_flags", "=", "msg", ".", "permanent_flags", "msg_sflags", "=", "session_flags", ".", "get", "(", "msg", ".", "uid", ")", "updated_flags", "=", "flag_op", ".", "apply", "(", "msg_flags", ",", "permanent_flag_set", ")", "updated_sflags", "=", "flag_op", ".", "apply", "(", "msg_sflags", ",", "session_flag_set", ")", "if", "msg_flags", "!=", "updated_flags", ":", "self", ".", "_silenced_flags", ".", "add", "(", "(", "msg", ".", "uid", ",", "updated_flags", ")", ")", "if", "msg_sflags", "!=", "updated_sflags", ":", "self", ".", "_silenced_sflags", ".", "add", "(", "(", "msg", ".", "uid", ",", "updated_sflags", ")", ")" ]
Builds the url of the resource s index .
def get_index_url ( self , resource = None , * * kwargs ) : default_kwargs = self . default_kwargs_for_urls ( ) if resource == self . get_resource_name ( ) else { } default_kwargs . update ( kwargs ) return self . get_full_url ( self . app . reverse ( '{}_index' . format ( resource or self . get_resource_name ( ) ) , * * default_kwargs ) )
7,648
https://github.com/dmonroy/chilero/blob/8f1118a60cb7eab3f9ad31cb8a14b30bc102893d/chilero/web/resource.py#L40-L58
[ "def", "map_midc_to_pvlib", "(", "variable_map", ",", "field_name", ")", ":", "new_field_name", "=", "field_name", "for", "midc_name", ",", "pvlib_name", "in", "variable_map", ".", "items", "(", ")", ":", "if", "field_name", ".", "startswith", "(", "midc_name", ")", ":", "# extract the instrument and units field and then remove units", "instrument_units", "=", "field_name", "[", "len", "(", "midc_name", ")", ":", "]", "units_index", "=", "instrument_units", ".", "find", "(", "'['", ")", "instrument", "=", "instrument_units", "[", ":", "units_index", "-", "1", "]", "new_field_name", "=", "pvlib_name", "+", "instrument", ".", "replace", "(", "' '", ",", "'_'", ")", "break", "return", "new_field_name" ]
Returns the url to the parent endpoint .
def get_parent ( self ) : if self . is_entity ( ) : return self . get_index_url ( * * self . default_kwargs_for_urls ( ) ) elif self . _parent is not None : resource = self . _parent . rsplit ( '_' , 1 ) [ 0 ] parts = self . default_kwargs_for_urls ( ) if '{}_id' . format ( resource ) in parts : id = parts . pop ( '{}_id' . format ( resource ) ) parts [ 'id' ] = id return self . get_full_url ( self . app . reverse ( self . _parent , * * parts ) )
7,649
https://github.com/dmonroy/chilero/blob/8f1118a60cb7eab3f9ad31cb8a14b30bc102893d/chilero/web/resource.py#L143-L158
[ "def", "_fit_temporal", "(", "noise", ",", "mask", ",", "template", ",", "stimfunction_tr", ",", "tr_duration", ",", "spatial_sd", ",", "temporal_proportion", ",", "temporal_sd", ",", "noise_dict", ",", "fit_thresh", ",", "fit_delta", ",", "iterations", ",", ")", ":", "# Pull out the", "dim_tr", "=", "noise", ".", "shape", "dim", "=", "dim_tr", "[", "0", ":", "3", "]", "base", "=", "template", "*", "noise_dict", "[", "'max_activity'", "]", "base", "=", "base", ".", "reshape", "(", "dim", "[", "0", "]", ",", "dim", "[", "1", "]", ",", "dim", "[", "2", "]", ",", "1", ")", "mean_signal", "=", "(", "base", "[", "mask", ">", "0", "]", ")", ".", "mean", "(", ")", "# Iterate through different parameters to fit SNR and SFNR", "temp_sd_orig", "=", "np", ".", "copy", "(", "temporal_sd", ")", "# Make a copy of the dictionary so it can be modified", "new_nd", "=", "copy", ".", "deepcopy", "(", "noise_dict", ")", "# What SFNR do you want", "target_sfnr", "=", "noise_dict", "[", "'sfnr'", "]", "# What AR do you want?", "target_ar", "=", "noise_dict", "[", "'auto_reg_rho'", "]", "[", "0", "]", "# Iterate through different MA parameters to fit AR", "for", "iteration", "in", "list", "(", "range", "(", "iterations", ")", ")", ":", "# If there are iterations left to perform then recalculate the", "# metrics and try again", "# Calculate the new SFNR", "new_sfnr", "=", "_calc_sfnr", "(", "noise", ",", "mask", ")", "# Calculate the AR", "new_ar", ",", "_", "=", "_calc_ARMA_noise", "(", "noise", ",", "mask", ",", "len", "(", "noise_dict", "[", "'auto_reg_rho'", "]", ")", ",", "len", "(", "noise_dict", "[", "'ma_rho'", "]", ")", ",", ")", "# Calculate the difference between the real and simulated data", "sfnr_diff", "=", "abs", "(", "new_sfnr", "-", "target_sfnr", ")", "/", "target_sfnr", "# Calculate the difference in the first AR component", "ar_diff", "=", "new_ar", "[", "0", "]", "-", "target_ar", "# If the SFNR and AR is sufficiently close then break the loop", "if", "(", "abs", "(", "ar_diff", ")", "/", "target_ar", ")", "<", "fit_thresh", "and", "sfnr_diff", "<", "fit_thresh", ":", "msg", "=", "'Terminated AR fit after '", "+", "str", "(", "iteration", ")", "+", "' iterations.'", "logger", ".", "info", "(", "msg", ")", "break", "# Otherwise update the noise metrics. Get the new temporal noise value", "temp_sd_new", "=", "mean_signal", "/", "new_sfnr", "temporal_sd", "-=", "(", "(", "temp_sd_new", "-", "temp_sd_orig", ")", "*", "fit_delta", ")", "# Prevent these going out of range", "if", "temporal_sd", "<", "0", "or", "np", ".", "isnan", "(", "temporal_sd", ")", ":", "temporal_sd", "=", "10e-3", "# Set the new system noise", "temp_sd_system_new", "=", "np", ".", "sqrt", "(", "(", "temporal_sd", "**", "2", ")", "*", "temporal_proportion", ")", "# Get the new AR value", "new_nd", "[", "'auto_reg_rho'", "]", "[", "0", "]", "-=", "(", "ar_diff", "*", "fit_delta", ")", "# Don't let the AR coefficient exceed 1", "if", "new_nd", "[", "'auto_reg_rho'", "]", "[", "0", "]", ">=", "1", ":", "new_nd", "[", "'auto_reg_rho'", "]", "[", "0", "]", "=", "0.99", "# Generate the noise. The appropriate", "noise_temporal", "=", "_generate_noise_temporal", "(", "stimfunction_tr", ",", "tr_duration", ",", "dim", ",", "template", ",", "mask", ",", "new_nd", ",", ")", "# Set up the machine noise", "noise_system", "=", "_generate_noise_system", "(", "dimensions_tr", "=", "dim_tr", ",", "spatial_sd", "=", "spatial_sd", ",", "temporal_sd", "=", "temp_sd_system_new", ",", ")", "# Sum up the noise of the brain", "noise", "=", "base", "+", "(", "noise_temporal", "*", "temporal_sd", ")", "+", "noise_system", "# Reject negative values (only happens outside of the brain)", "noise", "[", "noise", "<", "0", "]", "=", "0", "# Failed to converge", "if", "iterations", "==", "0", ":", "logger", ".", "info", "(", "'No fitting iterations were run'", ")", "elif", "iteration", "==", "iterations", ":", "logger", ".", "warning", "(", "'AR failed to converge.'", ")", "# Return the updated noise", "return", "noise" ]
Export the specified context to be capable context transferring
def export_context ( cls , context ) : if context is None : return result = [ ( x . context_name ( ) , x . context_value ( ) ) for x in context ] result . reverse ( ) return tuple ( result )
7,650
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/command/context.py#L141-L151
[ "def", "write", "(", "self", ",", "filename", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "writer", "=", "open", "(", "filename", ",", "'w'", ")", "if", "ext", "==", "'.py'", ":", "writer", ".", "write", "(", "pprint", ".", "pformat", "(", "self", ")", ")", "elif", "ext", "==", "'.yaml'", ":", "writer", ".", "write", "(", "yaml", ".", "dump", "(", "self", ")", ")", "else", ":", "writer", ".", "close", "(", ")", "raise", "Exception", "(", "'Unrecognized config format: %s'", "%", "ext", ")", "writer", ".", "close", "(", ")" ]
Check if context request is compatible with adapters specification . True - if compatible False - otherwise
def match ( self , command_context = None , * * command_env ) : spec = self . specification ( ) if command_context is None and spec is None : return True elif command_context is not None and spec is not None : return command_context == spec return False
7,651
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/command/context.py#L214-L227
[ "def", "copy", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "self", ".", "anneal", ",", "self", ".", "tm", ",", "overhang", "=", "self", ".", "overhang", ",", "name", "=", "self", ".", "name", ",", "note", "=", "self", ".", "note", ")" ]
Truthy if any element in enum_one is present in enum_two
def any_shared ( enum_one , enum_two ) : if not is_collection ( enum_one ) or not is_collection ( enum_two ) : return False enum_one = enum_one if isinstance ( enum_one , ( set , dict ) ) else set ( enum_one ) enum_two = enum_two if isinstance ( enum_two , ( set , dict ) ) else set ( enum_two ) return any ( e in enum_two for e in enum_one )
7,652
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/checks.py#L13-L21
[ "def", "ScanSource", "(", "self", ",", "source_path", ")", ":", "# Symbolic links are resolved here and not earlier to preserve the user", "# specified source path in storage and reporting.", "if", "os", ".", "path", ".", "islink", "(", "source_path", ")", ":", "source_path", "=", "os", ".", "path", ".", "realpath", "(", "source_path", ")", "if", "(", "not", "source_path", ".", "startswith", "(", "'\\\\\\\\.\\\\'", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "source_path", ")", ")", ":", "raise", "errors", ".", "SourceScannerError", "(", "'No such device, file or directory: {0:s}.'", ".", "format", "(", "source_path", ")", ")", "scan_context", "=", "source_scanner", ".", "SourceScannerContext", "(", ")", "scan_context", ".", "OpenSourcePath", "(", "source_path", ")", "try", ":", "self", ".", "_source_scanner", ".", "Scan", "(", "scan_context", ")", "except", "(", "ValueError", ",", "dfvfs_errors", ".", "BackEndError", ")", "as", "exception", ":", "raise", "errors", ".", "SourceScannerError", "(", "'Unable to scan source with error: {0!s}.'", ".", "format", "(", "exception", ")", ")", "if", "scan_context", ".", "source_type", "not", "in", "(", "scan_context", ".", "SOURCE_TYPE_STORAGE_MEDIA_DEVICE", ",", "scan_context", ".", "SOURCE_TYPE_STORAGE_MEDIA_IMAGE", ")", ":", "scan_node", "=", "scan_context", ".", "GetRootScanNode", "(", ")", "self", ".", "_source_path_specs", ".", "append", "(", "scan_node", ".", "path_spec", ")", "return", "scan_context", "# Get the first node where where we need to decide what to process.", "scan_node", "=", "scan_context", ".", "GetRootScanNode", "(", ")", "while", "len", "(", "scan_node", ".", "sub_nodes", ")", "==", "1", ":", "scan_node", "=", "scan_node", ".", "sub_nodes", "[", "0", "]", "base_path_specs", "=", "[", "]", "if", "scan_node", ".", "type_indicator", "!=", "(", "dfvfs_definitions", ".", "TYPE_INDICATOR_TSK_PARTITION", ")", ":", "self", ".", "_ScanVolume", "(", "scan_context", ",", "scan_node", ",", "base_path_specs", ")", "else", ":", "# Determine which partition needs to be processed.", "partition_identifiers", "=", "self", ".", "_GetTSKPartitionIdentifiers", "(", "scan_node", ")", "if", "not", "partition_identifiers", ":", "raise", "errors", ".", "SourceScannerError", "(", "'No partitions found.'", ")", "for", "partition_identifier", "in", "partition_identifiers", ":", "location", "=", "'/{0:s}'", ".", "format", "(", "partition_identifier", ")", "sub_scan_node", "=", "scan_node", ".", "GetSubNodeByLocation", "(", "location", ")", "self", ".", "_ScanVolume", "(", "scan_context", ",", "sub_scan_node", ",", "base_path_specs", ")", "if", "not", "base_path_specs", ":", "raise", "errors", ".", "SourceScannerError", "(", "'No supported file system found in source.'", ")", "self", ".", "_source_path_specs", "=", "base_path_specs", "return", "scan_context" ]
Check this route for matching the given request . If this route is matched then target route is returned .
def match ( self , request , service ) : uri = self . normalize_uri ( request . path ( ) ) if request . session ( ) . protocol ( ) not in self . protocols : return if request . method ( ) not in self . methods : return if self . virtual_hosts and request . virtual_host ( ) not in self . virtual_hosts : return if self . ports and int ( request . session ( ) . server_address ( ) . port ( ) ) not in self . ports : return match_obj = self . re_pattern . match ( uri ) if not match_obj : return presenter_action = self . action presenter_args = self . presenter_args . copy ( ) for i in range ( len ( self . route_args ) ) : if self . route_args [ i ] == 'action' : presenter_action = match_obj . group ( i + 1 ) else : presenter_args [ self . route_args [ i ] ] = match_obj . group ( i + 1 ) return WWebTargetRoute ( self . presenter , presenter_action , self , service . route_map ( ) , * * presenter_args )
7,653
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L338-L374
[ "def", "_sync_with_file", "(", "self", ")", ":", "self", ".", "_records", "=", "[", "]", "i", "=", "-", "1", "for", "i", ",", "line", "in", "self", ".", "_enum_lines", "(", ")", ":", "self", ".", "_records", ".", "append", "(", "None", ")", "self", ".", "_last_synced_index", "=", "i" ]
Connect the given pattern with the given presenter
def connect ( self , pattern , presenter , * * kwargs ) : self . __routes . append ( WWebRoute ( pattern , presenter , * * kwargs ) )
7,654
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L540-L548
[ "def", "hash_to_unsigned", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "string_types", ")", ":", "# Return a CRC32 value identical across Python versions and platforms", "# by stripping the sign bit as on", "# http://docs.python.org/library/zlib.html.", "return", "crc32", "(", "data", ".", "encode", "(", "'utf-8'", ")", ")", "&", "0xffffffff", "else", ":", "return", "int", "(", "data", ")" ]
Import route written as a string
def import_route ( self , route_as_txt ) : route_match = WWebRouteMap . import_route_re . match ( route_as_txt ) if route_match is None : raise ValueError ( 'Invalid route code' ) pattern = route_match . group ( 1 ) presenter_name = route_match . group ( 2 ) route_args = route_match . group ( 4 ) # may be None if route_args is not None : result_args = { } for arg_declaration in route_args . split ( "," ) : arg_match = WWebRouteMap . import_route_arg_re . match ( arg_declaration ) if arg_match is None : raise RuntimeError ( 'Invalid argument declaration in route' ) result_args [ arg_match . group ( 1 ) ] = arg_match . group ( 3 ) self . connect ( pattern , presenter_name , * * result_args ) else : self . connect ( pattern , presenter_name )
7,655
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L561-L585
[ "def", "unmount", "(", "self", ")", ":", "self", ".", "unmount_bindmounts", "(", ")", "self", ".", "unmount_mounts", "(", ")", "self", ".", "unmount_volume_groups", "(", ")", "self", ".", "unmount_loopbacks", "(", ")", "self", ".", "unmount_base_images", "(", ")", "self", ".", "clean_dirs", "(", ")" ]
Process single request from the given session
def process_request ( self , session ) : debugger = self . debugger ( ) debugger_session_id = debugger . session_id ( ) if debugger is not None else None try : request = session . read_request ( ) if debugger_session_id is not None : debugger . request ( debugger_session_id , request , session . protocol_version ( ) , session . protocol ( ) ) try : target_route = self . route_map ( ) . route ( request , self ) if debugger_session_id is not None : debugger . target_route ( debugger_session_id , target_route ) if target_route is not None : response = self . execute ( request , target_route ) else : presenter_cls = self . route_map ( ) . error_presenter ( ) presenter = presenter_cls ( request ) response = presenter . error_code ( code = 404 ) if debugger_session_id is not None : debugger . response ( debugger_session_id , response ) except Exception as e : if debugger_session_id is not None : debugger . exception ( debugger_session_id , e ) presenter_cls = self . route_map ( ) . error_presenter ( ) presenter = presenter_cls ( request ) response = presenter . exception_error ( e ) session . write_response ( request , response , * response . __pushed_responses__ ( ) ) except Exception as e : if debugger_session_id is not None : debugger . exception ( debugger_session_id , e ) session . session_close ( ) if debugger_session_id is not None : debugger . finalize ( debugger_session_id )
7,656
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L670-L718
[ "def", "create_meta_main", "(", "create_path", ",", "config", ",", "role", ",", "categories", ")", ":", "meta_file", "=", "c", ".", "DEFAULT_META_FILE", ".", "replace", "(", "\"%author_name\"", ",", "config", "[", "\"author_name\"", "]", ")", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%author_company\"", ",", "config", "[", "\"author_company\"", "]", ")", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%license_type\"", ",", "config", "[", "\"license_type\"", "]", ")", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%role_name\"", ",", "role", ")", "# Normalize the category so %categories always gets replaced.", "if", "not", "categories", ":", "categories", "=", "\"\"", "meta_file", "=", "meta_file", ".", "replace", "(", "\"%categories\"", ",", "categories", ")", "string_to_file", "(", "create_path", ",", "meta_file", ")" ]
Create presenter from the given requests and target routes
def create_presenter ( self , request , target_route ) : presenter_name = target_route . presenter_name ( ) if self . presenter_collection ( ) . has ( presenter_name ) is False : raise RuntimeError ( 'No such presenter: %s' % presenter_name ) presenter_class = self . presenter_collection ( ) . presenter ( presenter_name ) return self . presenter_factory ( ) . instantiate ( presenter_class , request , target_route , self )
7,657
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L721-L732
[ "def", "convert_to_utc", "(", "time", ")", ":", "# time is already in UTC", "if", "'Z'", "in", "time", ":", "return", "time", "else", ":", "time_formatted", "=", "time", "[", ":", "-", "3", "]", "+", "time", "[", "-", "2", ":", "]", "dt", "=", "datetime", ".", "strptime", "(", "time_formatted", ",", "'%Y-%m-%dT%H:%M:%S%z'", ")", "dt", "=", "dt", ".", "astimezone", "(", "timezone", "(", "'UTC'", ")", ")", "return", "dt", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")" ]
Execute the given presenter as a target for the given client request
def proxy ( self , request , original_target_route , presenter_name , * * kwargs ) : action_kwargs = kwargs . copy ( ) action_name = 'index' if 'action' in action_kwargs : action_name = action_kwargs [ 'action' ] action_kwargs . pop ( 'action' ) original_route = original_target_route . route ( ) original_route_map = original_target_route . route_map ( ) target_route = WWebTargetRoute ( presenter_name , action_name , original_route , original_route_map , * * action_kwargs ) return self . execute ( request , target_route )
7,658
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L804-L825
[ "def", "sort_values", "(", "self", ",", "ascending", "=", "False", ")", ":", "if", "self", ".", "index_type", "is", "not", "None", ":", "index_expr", "=", "grizzly_impl", ".", "get_field", "(", "self", ".", "expr", ",", "0", ")", "column_expr", "=", "grizzly_impl", ".", "get_field", "(", "self", ".", "expr", ",", "1", ")", "zip_expr", "=", "grizzly_impl", ".", "zip_columns", "(", "[", "index_expr", ",", "column_expr", "]", ")", "result_expr", "=", "grizzly_impl", ".", "sort", "(", "zip_expr", ",", "1", ",", "self", ".", "weld_type", ",", "ascending", ")", "unzip_expr", "=", "grizzly_impl", ".", "unzip_columns", "(", "result_expr", ",", "[", "self", ".", "index_type", ",", "self", ".", "weld_type", "]", ")", "return", "SeriesWeld", "(", "unzip_expr", ",", "self", ".", "weld_type", ",", "self", ".", "df", ",", "self", ".", "column_name", ",", "self", ".", "index_type", ",", "self", ".", "index_name", ")", "else", ":", "result_expr", "=", "grizzly_impl", ".", "sort", "(", "self", ".", "expr", ")" ]
Returns the start of the section the given point belongs to .
def find_point_in_section_list ( point , section_list ) : if point < section_list [ 0 ] or point > section_list [ - 1 ] : return None if point in section_list : if point == section_list [ - 1 ] : return section_list [ - 2 ] ind = section_list . bisect ( point ) - 1 if ind == 0 : return section_list [ 0 ] return section_list [ ind ] try : ind = section_list . bisect ( point ) return section_list [ ind - 1 ] except IndexError : return None
7,659
https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L4-L53
[ "def", "from_mapping", "(", "self", ",", "mapping", ":", "Optional", "[", "Mapping", "[", "str", ",", "Any", "]", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "mappings", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "if", "mapping", "is", "not", "None", ":", "mappings", ".", "update", "(", "mapping", ")", "mappings", ".", "update", "(", "kwargs", ")", "for", "key", ",", "value", "in", "mappings", ".", "items", "(", ")", ":", "if", "key", ".", "isupper", "(", ")", ":", "self", "[", "key", "]", "=", "value" ]
Returns the index range all sections belonging to the given range .
def find_range_ix_in_section_list ( start , end , section_list ) : if start > section_list [ - 1 ] or end < section_list [ 0 ] : return [ 0 , 0 ] if start < section_list [ 0 ] : start_section = section_list [ 0 ] else : start_section = find_point_in_section_list ( start , section_list ) if end > section_list [ - 1 ] : end_section = section_list [ - 2 ] else : end_section = find_point_in_section_list ( end , section_list ) return [ section_list . index ( start_section ) , section_list . index ( end_section ) + 1 ]
7,660
https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L56-L107
[ "def", "account_unmute", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/accounts/{0}/unmute'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'POST'", ",", "url", ")" ]
Returns all sections belonging to the given range .
def find_range_in_section_list ( start , end , section_list ) : ind = find_range_ix_in_section_list ( start , end , section_list ) return section_list [ ind [ 0 ] : ind [ 1 ] ]
7,661
https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L110-L151
[ "def", "cublasZgemm", "(", "handle", ",", "transa", ",", "transb", ",", "m", ",", "n", ",", "k", ",", "alpha", ",", "A", ",", "lda", ",", "B", ",", "ldb", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasZgemm_v2", "(", "handle", ",", "_CUBLAS_OP", "[", "transa", "]", ",", "_CUBLAS_OP", "[", "transb", "]", ",", "m", ",", "n", ",", "k", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "alpha", ".", "real", ",", "alpha", ".", "imag", ")", ")", ",", "int", "(", "A", ")", ",", "lda", ",", "int", "(", "B", ")", ",", "ldb", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "beta", ".", "real", ",", "beta", ".", "imag", ")", ")", ",", "int", "(", "C", ")", ",", "ldc", ")", "cublasCheckStatus", "(", "status", ")" ]
Returns the index range all points inside the given range .
def find_range_ix_in_point_list ( start , end , point_list ) : return [ point_list . bisect_left ( start ) , point_list . bisect_right ( end ) ]
7,662
https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L154-L188
[ "def", "url_to_resource", "(", "url", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "get_current_request", "(", ")", "# cnv = request.registry.getAdapter(request, IResourceUrlConverter)", "reg", "=", "get_current_registry", "(", ")", "cnv", "=", "reg", ".", "getAdapter", "(", "request", ",", "IResourceUrlConverter", ")", "return", "cnv", ".", "url_to_resource", "(", "url", ")" ]
Return list of strings that are made by splitting coma - separated option value . Method returns empty list if option value is empty string
def split_option ( self , section , option ) : value = self [ section ] [ option ] . strip ( ) if value == "" : return [ ] return [ x . strip ( ) for x in ( value . split ( "," ) ) ]
7,663
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L39-L50
[ "def", "render", "(", "self", ",", "filename", ")", ":", "self", ".", "elapsed_time", "=", "-", "time", "(", ")", "dpi", "=", "100", "fig", "=", "figure", "(", "figsize", "=", "(", "16", ",", "9", ")", ",", "dpi", "=", "dpi", ")", "with", "self", ".", "writer", ".", "saving", "(", "fig", ",", "filename", ",", "dpi", ")", ":", "for", "frame_id", "in", "xrange", "(", "self", ".", "frames", "+", "1", ")", ":", "self", ".", "renderFrame", "(", "frame_id", ")", "self", ".", "writer", ".", "grab_frame", "(", ")", "self", ".", "elapsed_time", "+=", "time", "(", ")" ]
Load configuration from given configuration .
def merge ( self , config ) : if isinstance ( config , ConfigParser ) is True : self . update ( config ) elif isinstance ( config , str ) : self . read ( config )
7,664
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L54-L63
[ "def", "revoke_session", "(", "self", ",", "sid", "=", "''", ",", "token", "=", "''", ")", ":", "if", "not", "sid", ":", "if", "token", ":", "sid", "=", "self", ".", "handler", ".", "sid", "(", "token", ")", "else", ":", "raise", "ValueError", "(", "'Need one of \"sid\" or \"token\"'", ")", "for", "typ", "in", "[", "'access_token'", ",", "'refresh_token'", ",", "'code'", "]", ":", "try", ":", "self", ".", "revoke_token", "(", "self", "[", "sid", "]", "[", "typ", "]", ",", "typ", ")", "except", "KeyError", ":", "# If no such token has been issued", "pass", "self", ".", "update", "(", "sid", ",", "revoked", "=", "True", ")" ]
Load configuration section from other configuration . If specified section doesn t exist in current configuration then it will be added automatically .
def merge_section ( self , config , section_to , section_from = None ) : section_from = section_from if section_from is not None else section_to if section_from not in config . sections ( ) : raise ValueError ( 'There is no such section "%s" in config' % section_from ) if section_to not in self . sections ( ) : self . add_section ( section_to ) for option in config [ section_from ] . keys ( ) : self . set ( section_to , option , config [ section_from ] [ option ] )
7,665
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L66-L83
[ "def", "run", "(", "self", ")", ":", "port", ",", "tensorboard_process", "=", "self", ".", "create_tensorboard_process", "(", ")", "LOGGER", ".", "info", "(", "'TensorBoard 0.1.7 at http://localhost:{}'", ".", "format", "(", "port", ")", ")", "while", "not", "self", ".", "estimator", ".", "checkpoint_path", ":", "self", ".", "event", ".", "wait", "(", "1", ")", "with", "self", ".", "_temporary_directory", "(", ")", "as", "aws_sync_dir", ":", "while", "not", "self", ".", "event", ".", "is_set", "(", ")", ":", "args", "=", "[", "'aws'", ",", "'s3'", ",", "'sync'", ",", "self", ".", "estimator", ".", "checkpoint_path", ",", "aws_sync_dir", "]", "subprocess", ".", "call", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "self", ".", "_sync_directories", "(", "aws_sync_dir", ",", "self", ".", "logdir", ")", "self", ".", "event", ".", "wait", "(", "10", ")", "tensorboard_process", ".", "terminate", "(", ")" ]
Check and return option from section from configuration . Option name is equal to option prefix
def __option ( self ) : section = self . section ( ) option = self . option_prefix ( ) if self . config ( ) . has_option ( section , option ) is False : raise NoOptionError ( option , section ) return section , option
7,666
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L139-L148
[ "def", "start_stress", "(", "self", ",", "stress_cmd", ")", ":", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "dev_null", ":", "try", ":", "stress_proc", "=", "subprocess", ".", "Popen", "(", "stress_cmd", ",", "stdout", "=", "dev_null", ",", "stderr", "=", "dev_null", ")", "self", ".", "set_stress_process", "(", "psutil", ".", "Process", "(", "stress_proc", ".", "pid", ")", ")", "except", "OSError", ":", "logging", ".", "debug", "(", "\"Unable to start stress\"", ")" ]
Select options from this selection that are started with the specified prefix
def select_options ( self , options_prefix ) : return WConfigSelection ( self . config ( ) , self . section ( ) , self . option_prefix ( ) + options_prefix )
7,667
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L184-L192
[ "def", "read_tabular", "(", "filename", ",", "dtype_conversion", "=", "None", ")", ":", "if", "dtype_conversion", "is", "None", ":", "dtype_conversion", "=", "{", "}", "name", ",", "ext", "=", "filename", ".", "split", "(", "\".\"", ",", "1", ")", "ext", "=", "ext", ".", "lower", "(", ")", "# Completely empty columns are interpreted as float by default.", "dtype_conversion", "[", "\"comment\"", "]", "=", "str", "if", "\"csv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_csv", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"tsv\"", "in", "ext", ":", "df", "=", "pd", ".", "read_table", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "\"xls\"", "in", "ext", "or", "\"xlsx\"", "in", "ext", ":", "df", "=", "pd", ".", "read_excel", "(", "filename", ",", "dtype", "=", "dtype_conversion", ",", "encoding", "=", "\"utf-8\"", ")", "# TODO: Add a function to parse ODS data into a pandas data frame.", "else", ":", "raise", "ValueError", "(", "\"Unknown file format '{}'.\"", ".", "format", "(", "ext", ")", ")", "return", "df" ]
Check whether configuration selection has the specified option .
def has_option ( self , option_name = None ) : if option_name is None : option_name = '' return self . config ( ) . has_option ( self . section ( ) , self . option_prefix ( ) + option_name )
7,668
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L205-L214
[ "async", "def", "update_lease_async", "(", "self", ",", "lease", ")", ":", "if", "lease", "is", "None", ":", "return", "False", "if", "not", "lease", ".", "token", ":", "return", "False", "_logger", ".", "debug", "(", "\"Updating lease %r %r\"", ",", "self", ".", "host", ".", "guid", ",", "lease", ".", "partition_id", ")", "# First, renew the lease to make sure the update will go through.", "if", "await", "self", ".", "renew_lease_async", "(", "lease", ")", ":", "try", ":", "await", "self", ".", "host", ".", "loop", ".", "run_in_executor", "(", "self", ".", "executor", ",", "functools", ".", "partial", "(", "self", ".", "storage_client", ".", "create_blob_from_text", ",", "self", ".", "lease_container_name", ",", "lease", ".", "partition_id", ",", "json", ".", "dumps", "(", "lease", ".", "serializable", "(", ")", ")", ",", "lease_id", "=", "lease", ".", "token", ")", ")", "except", "Exception", "as", "err", ":", "# pylint: disable=broad-except", "_logger", ".", "error", "(", "\"Failed to update lease %r %r %r\"", ",", "self", ".", "host", ".", "guid", ",", "lease", ".", "partition_id", ",", "err", ")", "raise", "err", "else", ":", "return", "False", "return", "True" ]
Generate checks for positional argument testing
def _args_checks_gen ( self , decorated_function , function_spec , arg_specs ) : inspected_args = function_spec . args args_check = { } for i in range ( len ( inspected_args ) ) : arg_name = inspected_args [ i ] if arg_name in arg_specs . keys ( ) : args_check [ arg_name ] = self . check ( arg_specs [ arg_name ] , arg_name , decorated_function ) return args_check
7,669
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L120-L137
[ "def", "save", "(", "self", ")", ":", "project_paths", "=", "OrderedDict", "(", ")", "for", "project", ",", "d", "in", "OrderedDict", "(", "self", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "project_path", "=", "d", "[", "'root'", "]", "fname", "=", "osp", ".", "join", "(", "project_path", ",", "'.project'", ",", "'.project.yml'", ")", "if", "not", "osp", ".", "exists", "(", "osp", ".", "dirname", "(", "fname", ")", ")", ":", "os", ".", "makedirs", "(", "osp", ".", "dirname", "(", "fname", ")", ")", "if", "osp", ".", "exists", "(", "fname", ")", ":", "os", ".", "rename", "(", "fname", ",", "fname", "+", "'~'", ")", "d", "=", "self", ".", "rel_paths", "(", "copy", ".", "deepcopy", "(", "d", ")", ")", "safe_dump", "(", "d", ",", "fname", ",", "default_flow_style", "=", "False", ")", "project_paths", "[", "project", "]", "=", "project_path", "else", ":", "project_paths", "=", "self", ".", "project_paths", "[", "project", "]", "self", ".", "project_paths", "=", "project_paths", "safe_dump", "(", "project_paths", ",", "self", ".", "all_projects", ",", "default_flow_style", "=", "False", ")" ]
Generate checks for keyword argument testing
def _kwargs_checks_gen ( self , decorated_function , function_spec , arg_specs ) : args_names = [ ] args_names . extend ( function_spec . args ) if function_spec . varargs is not None : args_names . append ( function_spec . args ) args_check = { } for arg_name in arg_specs . keys ( ) : if arg_name not in args_names : args_check [ arg_name ] = self . check ( arg_specs [ arg_name ] , arg_name , decorated_function ) return args_check
7,670
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L199-L220
[ "def", "_ExtractMetadataFromFileEntry", "(", "self", ",", "mediator", ",", "file_entry", ",", "data_stream", ")", ":", "# Do not extract metadata from the root file entry when it is virtual.", "if", "file_entry", ".", "IsRoot", "(", ")", "and", "file_entry", ".", "type_indicator", "not", "in", "(", "self", ".", "_TYPES_WITH_ROOT_METADATA", ")", ":", "return", "# We always want to extract the file entry metadata but we only want", "# to parse it once per file entry, so we only use it if we are", "# processing the default data stream of regular files.", "if", "data_stream", "and", "not", "data_stream", ".", "IsDefault", "(", ")", ":", "return", "display_name", "=", "mediator", ".", "GetDisplayName", "(", ")", "logger", ".", "debug", "(", "'[ExtractMetadataFromFileEntry] processing file entry: {0:s}'", ".", "format", "(", "display_name", ")", ")", "self", ".", "processing_status", "=", "definitions", ".", "STATUS_INDICATOR_EXTRACTING", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StartTiming", "(", "'extracting'", ")", "self", ".", "_event_extractor", ".", "ParseFileEntryMetadata", "(", "mediator", ",", "file_entry", ")", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StopTiming", "(", "'extracting'", ")", "self", ".", "processing_status", "=", "definitions", ".", "STATUS_INDICATOR_RUNNING" ]
Return decorator that can decorate target function
def decorator ( self , * * arg_specs ) : if self . decorate_disabled ( ) is True : def empty_decorator ( decorated_function ) : return decorated_function return empty_decorator def first_level_decorator ( decorated_function ) : function_spec = getfullargspec ( decorated_function ) args_checks = self . _args_checks_gen ( decorated_function , function_spec , arg_specs ) varargs_check = self . _varargs_checks_gen ( decorated_function , function_spec , arg_specs ) kwargs_checks = self . _kwargs_checks_gen ( decorated_function , function_spec , arg_specs ) def second_level_decorator ( original_function , * args , * * kwargs ) : self . _args_checks_test ( original_function , function_spec , args_checks , args , arg_specs ) self . _varargs_checks_test ( original_function , function_spec , varargs_check , args , arg_specs ) self . _kwargs_checks_test ( original_function , kwargs_checks , kwargs , arg_specs ) return original_function ( * args , * * kwargs ) return decorator ( second_level_decorator ) ( decorated_function ) return first_level_decorator
7,671
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L241-L270
[ "def", "create_binding", "(", "self", ",", "vhost", ",", "exchange", ",", "queue", ",", "rt_key", "=", "None", ",", "args", "=", "None", ")", ":", "vhost", "=", "quote", "(", "vhost", ",", "''", ")", "exchange", "=", "quote", "(", "exchange", ",", "''", ")", "queue", "=", "quote", "(", "queue", ",", "''", ")", "body", "=", "json", ".", "dumps", "(", "{", "'routing_key'", ":", "rt_key", ",", "'arguments'", ":", "args", "or", "[", "]", "}", ")", "path", "=", "Client", ".", "urls", "[", "'bindings_between_exch_queue'", "]", "%", "(", "vhost", ",", "exchange", ",", "queue", ")", "binding", "=", "self", ".", "_call", "(", "path", ",", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "Client", ".", "json_headers", ")", "return", "binding" ]
Return function name in pretty style
def function_name ( fn ) : fn_name = fn . __name__ if hasattr ( fn , '__qualname__' ) : return fn . __qualname__ elif hasattr ( fn , '__self__' ) : owner = fn . __self__ if isclass ( owner ) is False : owner = owner . __class__ return '%s.%s' % ( owner . __name__ , fn_name ) return fn_name
7,672
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L298-L312
[ "def", "_ParseLogonApplications", "(", "self", ",", "parser_mediator", ",", "registry_key", ")", ":", "for", "application", "in", "self", ".", "_LOGON_APPLICATIONS", ":", "command_value", "=", "registry_key", ".", "GetValueByName", "(", "application", ")", "if", "not", "command_value", ":", "continue", "values_dict", "=", "{", "'Application'", ":", "application", ",", "'Command'", ":", "command_value", ".", "GetDataAsObject", "(", ")", ",", "'Trigger'", ":", "'Logon'", "}", "event_data", "=", "windows_events", ".", "WindowsRegistryEventData", "(", ")", "event_data", ".", "key_path", "=", "registry_key", ".", "path", "event_data", ".", "offset", "=", "registry_key", ".", "offset", "event_data", ".", "regvalue", "=", "values_dict", "event_data", ".", "source_append", "=", "': Winlogon'", "event", "=", "time_events", ".", "DateTimeValuesEvent", "(", "registry_key", ".", "last_written_time", ",", "definitions", ".", "TIME_DESCRIPTION_WRITTEN", ")", "parser_mediator", ".", "ProduceEventWithEventData", "(", "event", ",", "event_data", ")" ]
Return callable that checks function parameter for type validity . Checks parameter if it is instance of specified class or classes
def check ( self , type_spec , arg_name , decorated_function ) : def raise_exception ( x_spec ) : exc_text = 'Argument "%s" for function "%s" has invalid type' % ( arg_name , Verifier . function_name ( decorated_function ) ) exc_text += ' (%s should be %s)' % ( x_spec , type_spec ) raise TypeError ( exc_text ) if isinstance ( type_spec , ( tuple , list , set ) ) : for single_type in type_spec : if ( single_type is not None ) and isclass ( single_type ) is False : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' ) if None in type_spec : type_spec = tuple ( filter ( lambda x : x is not None , type_spec ) ) return lambda x : None if x is None or isinstance ( x , tuple ( type_spec ) ) is True else raise_exception ( str ( ( type ( x ) ) ) ) else : return lambda x : None if isinstance ( x , tuple ( type_spec ) ) is True else raise_exception ( str ( ( type ( x ) ) ) ) elif isclass ( type_spec ) : return lambda x : None if isinstance ( x , type_spec ) is True else raise_exception ( str ( ( type ( x ) ) ) ) else : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' )
7,673
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L326-L360
[ "def", "add_string", "(", "self", ",", "data", ")", ":", "lines", "=", "[", "]", "while", "data", ":", "match", "=", "self", ".", "_line_end_re", ".", "search", "(", "data", ")", "if", "match", "is", "None", ":", "chunk", "=", "data", "else", ":", "chunk", "=", "data", "[", ":", "match", ".", "end", "(", ")", "]", "data", "=", "data", "[", "len", "(", "chunk", ")", ":", "]", "if", "self", ".", "_buf", "and", "self", ".", "_buf", "[", "-", "1", "]", ".", "endswith", "(", "b", "(", "'\\r'", ")", ")", "and", "not", "chunk", ".", "startswith", "(", "b", "(", "'\\n'", ")", ")", ":", "# if we get a carriage return followed by something other than", "# a newline then we assume that we're overwriting the current", "# line (ie. a progress bar)", "#", "# We don't terminate lines that end with a carriage return until", "# we see what's coming next so we can distinguish between a", "# progress bar situation and a Windows line terminator.", "#", "# TODO(adrian): some day these hacks should be replaced with", "# real terminal emulation", "lines", ".", "append", "(", "self", ".", "_finish_line", "(", ")", ")", "self", ".", "_buf", ".", "append", "(", "chunk", ")", "if", "chunk", ".", "endswith", "(", "b", "(", "'\\n'", ")", ")", ":", "lines", ".", "append", "(", "self", ".", "_finish_line", "(", ")", ")", "return", "lines" ]
Return callable that checks function parameter for class validity . Checks parameter if it is class or subclass of specified class or classes
def check ( self , type_spec , arg_name , decorated_function ) : def raise_exception ( text_spec ) : exc_text = 'Argument "%s" for function "%s" has invalid type' % ( arg_name , Verifier . function_name ( decorated_function ) ) exc_text += ' (%s)' % text_spec raise TypeError ( exc_text ) if isinstance ( type_spec , ( tuple , list , set ) ) : for single_type in type_spec : if ( single_type is not None ) and isclass ( single_type ) is False : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' ) if None in type_spec : type_spec = tuple ( filter ( lambda x : x is not None , type_spec ) ) return lambda x : None if x is None or ( isclass ( x ) is True and issubclass ( x , type_spec ) is True ) else raise_exception ( str ( x ) ) else : return lambda x : None if ( isclass ( x ) is True and issubclass ( x , type_spec ) is True ) else raise_exception ( str ( x ) ) elif isclass ( type_spec ) : return lambda x : None if ( isclass ( x ) is True and issubclass ( x , type_spec ) is True ) else raise_exception ( str ( x ) ) else : raise RuntimeError ( 'Invalid specification. Must be type or tuple/list/set of types' )
7,674
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L374-L409
[ "def", "save_md", "(", "p", ",", "*", "vsheets", ")", ":", "with", "p", ".", "open_text", "(", "mode", "=", "'w'", ")", "as", "fp", ":", "for", "vs", "in", "vsheets", ":", "if", "len", "(", "vsheets", ")", ">", "1", ":", "fp", ".", "write", "(", "'# %s\\n\\n'", "%", "vs", ".", "name", ")", "fp", ".", "write", "(", "'|'", "+", "'|'", ".", "join", "(", "'%-*s'", "%", "(", "col", ".", "width", "or", "options", ".", "default_width", ",", "markdown_escape", "(", "col", ".", "name", ")", ")", "for", "col", "in", "vs", ".", "visibleCols", ")", "+", "'|\\n'", ")", "fp", ".", "write", "(", "'|'", "+", "'+'", ".", "join", "(", "markdown_colhdr", "(", "col", ")", "for", "col", "in", "vs", ".", "visibleCols", ")", "+", "'|\\n'", ")", "for", "row", "in", "Progress", "(", "vs", ".", "rows", ",", "'saving'", ")", ":", "fp", ".", "write", "(", "'|'", "+", "'|'", ".", "join", "(", "'%-*s'", "%", "(", "col", ".", "width", "or", "options", ".", "default_width", ",", "markdown_escape", "(", "col", ".", "getDisplayValue", "(", "row", ")", ")", ")", "for", "col", "in", "vs", ".", "visibleCols", ")", "+", "'|\\n'", ")", "fp", ".", "write", "(", "'\\n'", ")", "status", "(", "'%s save finished'", "%", "p", ")" ]
Return callable that checks function parameter for value validity . Checks parameter if its value passes specified restrictions .
def check ( self , value_spec , arg_name , decorated_function ) : def raise_exception ( text_spec ) : exc_text = 'Argument "%s" for function "%s" has invalid value' % ( arg_name , Verifier . function_name ( decorated_function ) ) exc_text += ' (%s)' % text_spec raise ValueError ( exc_text ) if isinstance ( value_spec , ( tuple , list , set ) ) : for single_value in value_spec : if isfunction ( single_value ) is False : raise RuntimeError ( 'Invalid specification. Must be function or tuple/list/set of functions' ) def check ( x ) : for f in value_spec : if f ( x ) is not True : raise_exception ( str ( x ) ) return check elif isfunction ( value_spec ) : return lambda x : None if value_spec ( x ) is True else raise_exception ( str ( x ) ) else : raise RuntimeError ( 'Invalid specification. Must be function or tuple/list/set of functions' )
7,675
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L425-L461
[ "def", "add_string", "(", "self", ",", "data", ")", ":", "lines", "=", "[", "]", "while", "data", ":", "match", "=", "self", ".", "_line_end_re", ".", "search", "(", "data", ")", "if", "match", "is", "None", ":", "chunk", "=", "data", "else", ":", "chunk", "=", "data", "[", ":", "match", ".", "end", "(", ")", "]", "data", "=", "data", "[", "len", "(", "chunk", ")", ":", "]", "if", "self", ".", "_buf", "and", "self", ".", "_buf", "[", "-", "1", "]", ".", "endswith", "(", "b", "(", "'\\r'", ")", ")", "and", "not", "chunk", ".", "startswith", "(", "b", "(", "'\\n'", ")", ")", ":", "# if we get a carriage return followed by something other than", "# a newline then we assume that we're overwriting the current", "# line (ie. a progress bar)", "#", "# We don't terminate lines that end with a carriage return until", "# we see what's coming next so we can distinguish between a", "# progress bar situation and a Windows line terminator.", "#", "# TODO(adrian): some day these hacks should be replaced with", "# real terminal emulation", "lines", ".", "append", "(", "self", ".", "_finish_line", "(", ")", ")", "self", ".", "_buf", ".", "append", "(", "chunk", ")", "if", "chunk", ".", "endswith", "(", "b", "(", "'\\n'", ")", ")", ":", "lines", ".", "append", "(", "self", ".", "_finish_line", "(", ")", ")", "return", "lines" ]
Decorator that is used for caching result .
def cache_control ( validator = None , storage = None ) : def default_validator ( * args , * * kwargs ) : return True if validator is None : validator = default_validator if storage is None : storage = WGlobalSingletonCacheStorage ( ) def first_level_decorator ( decorated_function ) : def second_level_decorator ( original_function , * args , * * kwargs ) : validator_check = validator ( original_function , * args , * * kwargs ) cache_entry = storage . get_cache ( original_function , * args , * * kwargs ) if validator_check is not True or cache_entry . has_value is False : result = original_function ( * args , * * kwargs ) storage . put ( result , original_function , * args , * * kwargs ) return result else : return cache_entry . cached_value return decorator ( second_level_decorator ) ( decorated_function ) return first_level_decorator
7,676
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L384-L421
[ "def", "__placeSellOrder", "(", "self", ",", "tick", ")", ":", "if", "self", ".", "__position", "<", "0", ":", "return", "share", "=", "self", ".", "__position", "order", "=", "Order", "(", "accountId", "=", "self", ".", "__strategy", ".", "accountId", ",", "action", "=", "Action", ".", "SELL", ",", "is_market", "=", "True", ",", "symbol", "=", "self", ".", "__symbol", ",", "share", "=", "-", "share", ")", "if", "self", ".", "__strategy", ".", "placeOrder", "(", "order", ")", ":", "self", ".", "__position", "=", "0", "self", ".", "__buyPrice", "=", "0" ]
Check if there is a result for given function
def has ( self , decorated_function , * args , * * kwargs ) : return self . get_cache ( decorated_function , * args , * * kwargs ) . has_value
7,677
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L99-L108
[ "def", "cursor", "(", "self", ")", ":", "self", ".", "_assert_open", "(", ")", "if", "self", ".", "mars_enabled", ":", "in_tran", "=", "self", ".", "_conn", ".", "tds72_transaction", "if", "in_tran", "and", "self", ".", "_dirty", ":", "try", ":", "return", "_MarsCursor", "(", "self", ",", "self", ".", "_conn", ".", "create_session", "(", "self", ".", "_tzinfo_factory", ")", ",", "self", ".", "_tzinfo_factory", ")", "except", "(", "socket", ".", "error", ",", "OSError", ")", "as", "e", ":", "self", ".", "_conn", ".", "close", "(", ")", "raise", "else", ":", "try", ":", "return", "_MarsCursor", "(", "self", ",", "self", ".", "_conn", ".", "create_session", "(", "self", ".", "_tzinfo_factory", ")", ",", "self", ".", "_tzinfo_factory", ")", "except", "(", "socket", ".", "error", ",", "OSError", ")", "as", "e", ":", "if", "e", ".", "errno", "not", "in", "(", "errno", ".", "EPIPE", ",", "errno", ".", "ECONNRESET", ")", ":", "raise", "self", ".", "_conn", ".", "close", "(", ")", "except", "ClosedConnectionError", ":", "pass", "self", ".", "_assert_open", "(", ")", "return", "_MarsCursor", "(", "self", ",", "self", ".", "_conn", ".", "create_session", "(", "self", ".", "_tzinfo_factory", ")", ",", "self", ".", "_tzinfo_factory", ")", "else", ":", "return", "Cursor", "(", "self", ",", "self", ".", "_conn", ".", "main_session", ",", "self", ".", "_tzinfo_factory", ")" ]
Check whether function is a bounded method or not . If check fails then exception is raised
def __check ( self , decorated_function , * args , * * kwargs ) : # TODO replace this function with decorator which can be turned off like verify_* does if len ( args ) >= 1 : obj = args [ 0 ] function_name = decorated_function . __name__ if hasattr ( obj , function_name ) is True : fn = getattr ( obj , function_name ) if callable ( fn ) and fn . __self__ == obj : return raise RuntimeError ( 'Only bounded methods are allowed' )
7,678
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L279-L296
[ "def", "channeldir_node_to_row", "(", "self", ",", "path_tuple", ")", ":", "row", "=", "dict", "(", ")", "for", "key", "in", "CONTENT_INFO_HEADER", ":", "row", "[", "key", "]", "=", "None", "row", "[", "CONTENT_PATH_KEY", "]", "=", "\"/\"", ".", "join", "(", "path_tuple", ")", "# use / in .csv on Windows and UNIX", "title", "=", "path_tuple", "[", "-", "1", "]", ".", "replace", "(", "'_'", ",", "' '", ")", "for", "ext", "in", "content_kinds", ".", "MAPPING", ".", "keys", "(", ")", ":", "if", "title", ".", "endswith", "(", "ext", ")", ":", "title", "=", "title", ".", "replace", "(", "'.'", "+", "ext", ",", "''", ")", "row", "[", "CONTENT_TITLE_KEY", "]", "=", "title", "row", "[", "CONTENT_SOURCEID_KEY", "]", "=", "path_tuple", "[", "-", "1", "]", "return", "row" ]
Create a directory if it doesn t exist .
def ensure_dir ( directory : str ) -> None : if not os . path . isdir ( directory ) : LOG . debug ( f"Directory {directory} does not exist, creating it." ) os . makedirs ( directory )
7,679
https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L22-L26
[ "def", "_rows_event_to_dict", "(", "e", ",", "stream", ")", ":", "pk_cols", "=", "e", ".", "primary_key", "if", "isinstance", "(", "e", ".", "primary_key", ",", "(", "list", ",", "tuple", ")", ")", "else", "(", "e", ".", "primary_key", ",", ")", "if", "isinstance", "(", "e", ",", "row_event", ".", "UpdateRowsEvent", ")", ":", "sig", "=", "signals", ".", "rows_updated", "action", "=", "'update'", "row_converter", "=", "_convert_update_row", "elif", "isinstance", "(", "e", ",", "row_event", ".", "WriteRowsEvent", ")", ":", "sig", "=", "signals", ".", "rows_inserted", "action", "=", "'insert'", "row_converter", "=", "_convert_write_row", "elif", "isinstance", "(", "e", ",", "row_event", ".", "DeleteRowsEvent", ")", ":", "sig", "=", "signals", ".", "rows_deleted", "action", "=", "'delete'", "row_converter", "=", "_convert_write_row", "else", ":", "assert", "False", ",", "'Invalid binlog event'", "meta", "=", "{", "'time'", ":", "e", ".", "timestamp", ",", "'log_pos'", ":", "stream", ".", "log_pos", ",", "'log_file'", ":", "stream", ".", "log_file", ",", "'schema'", ":", "e", ".", "schema", ",", "'table'", ":", "e", ".", "table", ",", "'action'", ":", "action", ",", "}", "rows", "=", "list", "(", "map", "(", "row_converter", ",", "e", ".", "rows", ")", ")", "for", "row", "in", "rows", ":", "row", "[", "'keys'", "]", "=", "{", "k", ":", "row", "[", "'values'", "]", "[", "k", "]", "for", "k", "in", "pk_cols", "}", "return", "rows", ",", "meta" ]
Apply expanduser and expandvars to directory to expand ~ and env vars .
def expand ( directory : str ) -> str : temp1 = os . path . expanduser ( directory ) return os . path . expandvars ( temp1 )
7,680
https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L28-L31
[ "def", "appendColumn", "(", "self", ",", "name", ")", ":", "try", ":", "self", ".", "getColumnByName", "(", "name", ")", "# if we get here the table already has that column", "raise", "ValueError", "(", "\"duplicate Column '%s'\"", "%", "name", ")", "except", "KeyError", ":", "pass", "column", "=", "Column", "(", "AttributesImpl", "(", "{", "u\"Name\"", ":", "\"%s:%s\"", "%", "(", "StripTableName", "(", "self", ".", "tableName", ")", ",", "name", ")", ",", "u\"Type\"", ":", "self", ".", "validcolumns", "[", "name", "]", "}", ")", ")", "streams", "=", "self", ".", "getElementsByTagName", "(", "ligolw", ".", "Stream", ".", "tagName", ")", "if", "streams", ":", "self", ".", "insertBefore", "(", "column", ",", "streams", "[", "0", "]", ")", "else", ":", "self", ".", "appendChild", "(", "column", ")", "return", "column" ]
Create function to download with rate limiting and text progress .
def generate_downloader ( headers : Dict [ str , str ] , args : Any , max_per_hour : int = 30 ) -> Callable [ ... , None ] : def _downloader ( url : str , dest : str ) -> None : @ rate_limited ( max_per_hour , args ) def _rate_limited_download ( ) -> None : # Create parent directory of file, and its parents, if they don't exist. parent = os . path . dirname ( dest ) if not os . path . exists ( parent ) : os . makedirs ( parent ) response = requests . get ( url , headers = headers , stream = True ) LOG . info ( f"Downloading from '{url}'." ) LOG . info ( f"Trying to save to '{dest}'." ) length = response . headers . get ( "content-length" ) if length is None : total_length = 0 else : total_length = int ( length ) expected_size = ( total_length / CHUNK_SIZE ) + 1 chunks = response . iter_content ( chunk_size = CHUNK_SIZE ) open ( dest , "a" , encoding = FORCED_ENCODING ) . close ( ) # per http://stackoverflow.com/a/20943461 with open ( dest , "wb" ) as stream : for chunk in tui . progress . bar ( chunks , expected_size = expected_size ) : if not chunk : return stream . write ( chunk ) stream . flush ( ) _rate_limited_download ( ) return _downloader
7,681
https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L33-L71
[ "def", "catalogFactory", "(", "name", ",", "*", "*", "kwargs", ")", ":", "fn", "=", "lambda", "member", ":", "inspect", ".", "isclass", "(", "member", ")", "and", "member", ".", "__module__", "==", "__name__", "catalogs", "=", "odict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "fn", ")", ")", "if", "name", "not", "in", "list", "(", "catalogs", ".", "keys", "(", ")", ")", ":", "msg", "=", "\"%s not found in catalogs:\\n %s\"", "%", "(", "name", ",", "list", "(", "kernels", ".", "keys", "(", ")", ")", ")", "logger", ".", "error", "(", "msg", ")", "msg", "=", "\"Unrecognized catalog: %s\"", "%", "name", "raise", "Exception", "(", "msg", ")", "return", "catalogs", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
Given a string like 1 23 4 - 8 32 1 return a unique list of those integers in the string and the integers in the ranges in the string . Non - numbers ignored . Not necessarily sorted
def parse_int_string ( int_string : str ) -> List [ int ] : cleaned = " " . join ( int_string . strip ( ) . split ( ) ) cleaned = cleaned . replace ( " - " , "-" ) cleaned = cleaned . replace ( "," , " " ) tokens = cleaned . split ( " " ) indices : Set [ int ] = set ( ) for token in tokens : if "-" in token : endpoints = token . split ( "-" ) if len ( endpoints ) != 2 : LOG . info ( f"Dropping '{token}' as invalid - weird range." ) continue start = int ( endpoints [ 0 ] ) end = int ( endpoints [ 1 ] ) + 1 indices = indices . union ( indices , set ( range ( start , end ) ) ) else : try : indices . add ( int ( token ) ) except ValueError : LOG . info ( f"Dropping '{token}' as invalid - not an int." ) return list ( indices )
7,682
https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L77-L107
[ "def", "save_matpower", "(", "self", ",", "fd", ")", ":", "from", "pylon", ".", "io", "import", "MATPOWERWriter", "MATPOWERWriter", "(", "self", ")", ".", "write", "(", "fd", ")" ]
Set up proper logging .
def set_up_logging ( log_filename : str = "log" , verbosity : int = 0 ) -> logging . Logger : LOG . setLevel ( logging . DEBUG ) # Log everything verbosely to a file. file_handler = RotatingFileHandler ( filename = log_filename , maxBytes = 1024000000 , backupCount = 10 ) verbose_form = logging . Formatter ( fmt = "%(asctime)s - %(levelname)s - %(module)s - %(message)s" ) file_handler . setFormatter ( verbose_form ) file_handler . setLevel ( logging . DEBUG ) LOG . addHandler ( file_handler ) # Provide a stdout handler logging at INFO. stream_handler = logging . StreamHandler ( sys . stdout ) simple_form = logging . Formatter ( fmt = "%(message)s" ) stream_handler . setFormatter ( simple_form ) if verbosity > 0 : stream_handler . setLevel ( logging . DEBUG ) else : stream_handler . setLevel ( logging . INFO ) LOG . addHandler ( stream_handler ) return LOG
7,683
https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L180-L203
[ "def", "item_enclosure_url", "(", "self", ",", "item", ")", ":", "try", ":", "url", "=", "item", ".", "image", ".", "url", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "img", "=", "BeautifulSoup", "(", "item", ".", "html_content", ",", "'html.parser'", ")", ".", "find", "(", "'img'", ")", "url", "=", "img", ".", "get", "(", "'src'", ")", "if", "img", "else", "None", "self", ".", "cached_enclosure_url", "=", "url", "if", "url", ":", "url", "=", "urljoin", "(", "self", ".", "site_url", ",", "url", ")", "if", "self", ".", "feed_format", "==", "'rss'", ":", "url", "=", "url", ".", "replace", "(", "'https://'", ",", "'http://'", ")", "return", "url" ]
Get random line from a file .
def random_line ( file_path : str , encoding : str = FORCED_ENCODING ) -> str : # Fancy alg from http://stackoverflow.com/a/35579149 to avoid loading full file. line_num = 0 selected_line = "" with open ( file_path , encoding = encoding ) as stream : while True : line = stream . readline ( ) if not line : break line_num += 1 if random . uniform ( 0 , line_num ) < 1 : selected_line = line return selected_line . strip ( )
7,684
https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L205-L219
[ "def", "register", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "dimensions", "=", "dict", "(", "(", "k", ",", "str", "(", "v", ")", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ")", "composite_key", "=", "self", ".", "_composite_name", "(", "key", ",", "dimensions", ")", "self", ".", "_metadata", "[", "composite_key", "]", "=", "{", "'metric'", ":", "key", ",", "'dimensions'", ":", "dimensions", "}", "return", "composite_key" ]
Converted probability of being treated to total percentage of clinical cases treated
def get_percentage_from_prob ( prob ) : assert isinstance ( prob , ( float , int ) ) prob = float ( prob ) assert prob >= 0 assert prob <= 1 percentages = list ( probability_list . keys ( ) ) percentages . sort ( ) for percentage in percentages : if prob < probability_list [ percentage ] : return percentage - 1 return 100
7,685
https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/healthsystem.py#L135-L149
[ "def", "inject", "(", "module_name", "=", "None", ",", "module_prefix", "=", "'[???]'", ",", "DEBUG", "=", "False", ",", "module", "=", "None", ",", "N", "=", "1", ")", ":", "#noinject(module_name, module_prefix, DEBUG, module, N=1)", "noinject", "(", "module_name", ",", "module_prefix", ",", "DEBUG", ",", "module", ",", "N", "=", "N", ")", "module", "=", "_get_module", "(", "module_name", ",", "module", ")", "rrr", "=", "make_module_reload_func", "(", "None", ",", "module_prefix", ",", "module", ")", "profile_", "=", "make_module_profile_func", "(", "None", ",", "module_prefix", ",", "module", ")", "print_funcs", "=", "inject_print_functions", "(", "None", ",", "module_prefix", ",", "DEBUG", ",", "module", ")", "(", "print", ",", "print_", ",", "printDBG", ")", "=", "print_funcs", "return", "(", "print", ",", "print_", ",", "printDBG", ",", "rrr", ",", "profile_", ")" ]
Converts generator functions into list returning functions .
def listify ( generator_func ) : def list_func ( * args , * * kwargs ) : return degenerate ( generator_func ( * args , * * kwargs ) ) return list_func
7,686
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/decorators.py#L3-L15
[ "def", "_compute_ogg_page_crc", "(", "page", ")", ":", "page_zero_crc", "=", "page", "[", ":", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "]", "+", "b\"\\00\"", "*", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", "+", "page", "[", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "+", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", ":", "]", "return", "ogg_page_crc", "(", "page_zero_crc", ")" ]
Verifies whether two positions are the same . A tolerance value determines how close the two positions must be to be considered same .
def locations_within ( a , b , tolerance ) : ret = '' # Clone b so that we can destroy it. b = dict ( b ) for ( key , value ) in a . items ( ) : if key not in b : raise ValueError ( "b does not have the key: " + key ) if abs ( int ( value ) - int ( b [ key ] ) ) > tolerance : ret += 'key {0} differs: {1} {2}' . format ( key , int ( value ) , int ( b [ key ] ) ) del b [ key ] if b : raise ValueError ( "keys in b not seen in a: " + ", " . join ( b . keys ( ) ) ) return ret
7,687
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L479-L525
[ "def", "sample", "(", "self", ")", ":", "sample", "=", "[", "]", "iterator", "=", "iter", "(", "self", ".", "__sample_extended_rows", ")", "iterator", "=", "self", ".", "__apply_processors", "(", "iterator", ")", "for", "row_number", ",", "headers", ",", "row", "in", "iterator", ":", "sample", ".", "append", "(", "row", ")", "return", "sample" ]
Sends a character to the currently active element with Ctrl pressed . This method takes care of pressing and releasing Ctrl .
def ctrl_x ( self , x , to = None ) : seq = [ Keys . CONTROL , x , Keys . CONTROL ] # This works around a bug in Selenium that happens in FF on # Windows, and in Chrome on Linux. # # The bug was reported here: # # https://code.google.com/p/selenium/issues/detail?id=7303 # if ( self . firefox and self . windows ) or ( self . linux and self . chrome ) : seq . append ( Keys . PAUSE ) if to is None : ActionChains ( self . driver ) . send_keys ( seq ) . perform ( ) else : self . send_keys ( to , seq )
7,688
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L132-L155
[ "def", "_read_prm_file", "(", "prm_filename", ")", ":", "logger", ".", "debug", "(", "\"Reading config-file: %s\"", "%", "prm_filename", ")", "try", ":", "with", "open", "(", "prm_filename", ",", "\"r\"", ")", "as", "config_file", ":", "prm_dict", "=", "yaml", ".", "load", "(", "config_file", ")", "except", "yaml", ".", "YAMLError", ":", "raise", "ConfigFileNotRead", "else", ":", "_update_prms", "(", "prm_dict", ")" ]
Sends a character to the currently active element with Command pressed . This method takes care of pressing and releasing Command .
def command_x ( self , x , to = None ) : if to is None : ActionChains ( self . driver ) . send_keys ( [ Keys . COMMAND , x , Keys . COMMAND ] ) . perform ( ) else : self . send_keys ( to , [ Keys . COMMAND , x , Keys . COMMAND ] )
7,689
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L167-L178
[ "def", "_read_prm_file", "(", "prm_filename", ")", ":", "logger", ".", "debug", "(", "\"Reading config-file: %s\"", "%", "prm_filename", ")", "try", ":", "with", "open", "(", "prm_filename", ",", "\"r\"", ")", "as", "config_file", ":", "prm_dict", "=", "yaml", ".", "load", "(", "config_file", ")", "except", "yaml", ".", "YAMLError", ":", "raise", "ConfigFileNotRead", "else", ":", "_update_prms", "(", "prm_dict", ")" ]
Waits for a condition to be true .
def wait ( self , condition ) : return WebDriverWait ( self . driver , self . timeout ) . until ( condition )
7,690
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L391-L399
[ "def", "tojson", "(", "self", ")", ":", "json_str", "=", "ctypes", ".", "c_char_p", "(", ")", "check_call", "(", "_LIB", ".", "MXSymbolSaveToJSON", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "json_str", ")", ")", ")", "return", "py_str", "(", "json_str", ".", "value", ")" ]
Waits for a condition to be false .
def wait_until_not ( self , condition ) : return WebDriverWait ( self . driver , self . timeout ) . until_not ( condition )
7,691
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L401-L409
[ "def", "register_dataframe_method", "(", "method", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "class", "AccessorMethod", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "pandas_obj", ")", ":", "self", ".", "_obj", "=", "pandas_obj", "@", "wraps", "(", "method", ")", "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "method", "(", "self", ".", "_obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", "register_dataframe_accessor", "(", "method", ".", "__name__", ")", "(", "AccessorMethod", ")", "return", "method", "return", "inner", "(", ")" ]
Processes a sorted and page - partitioned sequence of revision documents into and adds statistics to the persistence field each token added in the revision persisted through future revisions .
def persistence2stats ( rev_docs , min_persisted = 5 , min_visible = 1209600 , include = None , exclude = None , verbose = False ) : rev_docs = mwxml . utilities . normalize ( rev_docs ) min_persisted = int ( min_persisted ) min_visible = int ( min_visible ) include = include if include is not None else lambda t : True exclude = exclude if exclude is not None else lambda t : False for rev_doc in rev_docs : persistence_doc = rev_doc [ 'persistence' ] stats_doc = { 'tokens_added' : 0 , 'persistent_tokens' : 0 , 'non_self_persistent_tokens' : 0 , 'sum_log_persisted' : 0 , 'sum_log_non_self_persisted' : 0 , 'sum_log_seconds_visible' : 0 , 'censored' : False , 'non_self_censored' : False } filtered_docs = ( t for t in persistence_doc [ 'tokens' ] if include ( t [ 'text' ] ) and not exclude ( t [ 'text' ] ) ) for token_doc in filtered_docs : if verbose : sys . stderr . write ( "." ) sys . stderr . flush ( ) stats_doc [ 'tokens_added' ] += 1 stats_doc [ 'sum_log_persisted' ] += log ( token_doc [ 'persisted' ] + 1 ) stats_doc [ 'sum_log_non_self_persisted' ] += log ( token_doc [ 'non_self_persisted' ] + 1 ) stats_doc [ 'sum_log_seconds_visible' ] += log ( token_doc [ 'seconds_visible' ] + 1 ) # Look for time threshold if token_doc [ 'seconds_visible' ] >= min_visible : stats_doc [ 'persistent_tokens' ] += 1 stats_doc [ 'non_self_persistent_tokens' ] += 1 else : # Look for review threshold stats_doc [ 'persistent_tokens' ] += token_doc [ 'persisted' ] >= min_persisted stats_doc [ 'non_self_persistent_tokens' ] += token_doc [ 'non_self_persisted' ] >= min_persisted # Check for censoring if persistence_doc [ 'seconds_possible' ] < min_visible : stats_doc [ 'censored' ] = True stats_doc [ 'non_self_censored' ] = True else : if persistence_doc [ 'revisions_processed' ] < min_persisted : stats_doc [ 'censored' ] = True if persistence_doc [ 'non_self_processed' ] < min_persisted : stats_doc [ 'non_self_censored' ] = True if verbose : sys . stderr . write ( "\n" ) sys . stderr . flush ( ) rev_doc [ 'persistence' ] . update ( stats_doc ) yield rev_doc
7,692
https://github.com/mediawiki-utilities/python-mwpersistence/blob/2b98847fb8acaca38b3cbf94bde3fd7e27d2b67d/mwpersistence/utilities/persistence2stats.py#L88-L187
[ "def", "_get_window_list", "(", "self", ")", ":", "window_list", "=", "Quartz", ".", "CGWindowListCopyWindowInfo", "(", "Quartz", ".", "kCGWindowListExcludeDesktopElements", ",", "Quartz", ".", "kCGNullWindowID", ")", "return", "window_list" ]
Return task health . If None - task is healthy otherwise - maximum severity of sensors
def healthy ( self ) : state = None for sensor in self . _sensors . values ( ) : if sensor . healthy ( ) is False : if state is None or sensor . severity ( ) . value > state . value : state = sensor . severity ( ) if state == WTaskHealthSensor . WTaskSensorSeverity . critical : break return state
7,693
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/health.py#L169-L182
[ "def", "save_file", "(", "self", ")", ":", "l", "=", "[", "]", "walk", "=", "self", ".", "walker", "for", "edit", "in", "walk", ".", "lines", ":", "# collect the text already stored in edit widgets", "if", "edit", ".", "original_text", ".", "expandtabs", "(", ")", "==", "edit", ".", "edit_text", ":", "l", ".", "append", "(", "edit", ".", "original_text", ")", "else", ":", "l", ".", "append", "(", "re_tab", "(", "edit", ".", "edit_text", ")", ")", "# then the rest", "while", "walk", ".", "file", "is", "not", "None", ":", "l", ".", "append", "(", "walk", ".", "read_next_line", "(", ")", ")", "# write back to disk", "outfile", "=", "open", "(", "self", ".", "save_name", ",", "\"w\"", ")", "l_iter", "=", "iter", "(", "l", ")", "line", "=", "next", "(", "l_iter", ")", "prefix", "=", "\"\"", "while", "True", ":", "try", ":", "outfile", ".", "write", "(", "prefix", "+", "line", ")", "prefix", "=", "\"\\n\"", "line", "=", "next", "(", "l_iter", ")", "except", "StopIteration", ":", "if", "line", "!=", "\"\\n\"", ":", "outfile", ".", "write", "(", "\"\\n\"", ")", "break" ]
Create preprocessing data
def preproc ( self , which = 'sin' , * * kwargs ) : self . app_main ( * * kwargs ) config = self . exp_config config [ 'infile' ] = infile = osp . join ( config [ 'expdir' ] , 'input.dat' ) func = getattr ( np , which ) # np.sin, np.cos or np.tan data = func ( np . linspace ( - np . pi , np . pi ) ) self . logger . info ( 'Saving input data to %s' , infile ) np . savetxt ( infile , data )
7,694
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/docs/square_preproc.py#L17-L36
[ "def", "strip_uri", "(", "repo", ")", ":", "splits", "=", "repo", ".", "split", "(", ")", "for", "idx", "in", "range", "(", "len", "(", "splits", ")", ")", ":", "if", "any", "(", "splits", "[", "idx", "]", ".", "startswith", "(", "x", ")", "for", "x", "in", "(", "'http://'", ",", "'https://'", ",", "'ftp://'", ")", ")", ":", "splits", "[", "idx", "]", "=", "splits", "[", "idx", "]", ".", "rstrip", "(", "'/'", ")", "return", "' '", ".", "join", "(", "splits", ")" ]
Return tuple of current mount points
def mounts ( cls ) : result = [ ] with open ( cls . __mounts_file__ ) as f : for mount_record in f : result . append ( WMountPoint ( mount_record ) ) return tuple ( result )
7,695
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/mounts.py#L123-L132
[ "def", "create_api_client", "(", "api", "=", "'BatchV1'", ")", ":", "k8s_config", ".", "load_incluster_config", "(", ")", "api_configuration", "=", "client", ".", "Configuration", "(", ")", "api_configuration", ".", "verify_ssl", "=", "False", "if", "api", "==", "'extensions/v1beta1'", ":", "api_client", "=", "client", ".", "ExtensionsV1beta1Api", "(", ")", "elif", "api", "==", "'CoreV1'", ":", "api_client", "=", "client", ".", "CoreV1Api", "(", ")", "elif", "api", "==", "'StorageV1'", ":", "api_client", "=", "client", ".", "StorageV1Api", "(", ")", "else", ":", "api_client", "=", "client", ".", "BatchV1Api", "(", ")", "return", "api_client" ]
Return mount point that where the given path is reside on
def mount_point ( cls , file_path ) : mount = None for mp in cls . mounts ( ) : mp_path = mp . path ( ) if file_path . startswith ( mp_path ) is True : if mount is None or len ( mount . path ( ) ) <= len ( mp_path ) : mount = mp return mount
7,696
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/mounts.py#L137-L151
[ "def", "register_dataframe_method", "(", "method", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "class", "AccessorMethod", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "pandas_obj", ")", ":", "self", ".", "_obj", "=", "pandas_obj", "@", "wraps", "(", "method", ")", "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "method", "(", "self", ".", "_obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", "register_dataframe_accessor", "(", "method", ".", "__name__", ")", "(", "AccessorMethod", ")", "return", "method", "return", "inner", "(", ")" ]
Mount a device to mount directory
def mount ( cls , device , mount_directory , fs = None , options = None , cmd_timeout = None , sudo = False ) : cmd = [ ] if sudo is False else [ 'sudo' ] cmd . extend ( [ 'mount' , device , os . path . abspath ( mount_directory ) ] ) if fs is not None : cmd . extend ( [ '-t' , fs ] ) if options is not None and len ( options ) > 0 : cmd . append ( '-o' ) cmd . extend ( options ) subprocess . check_output ( cmd , timeout = cmd_timeout )
7,697
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/mounts.py#L158-L180
[ "def", "KL", "(", "self", ",", "other", ")", ":", "return", ".5", "*", "(", "np", ".", "sum", "(", "self", ".", "variance", "/", "other", ".", "variance", ")", "+", "(", "(", "other", ".", "mean", "-", "self", ".", "mean", ")", "**", "2", "/", "other", ".", "variance", ")", ".", "sum", "(", ")", "-", "self", ".", "num_data", "*", "self", ".", "input_dim", "+", "np", ".", "sum", "(", "np", ".", "log", "(", "other", ".", "variance", ")", ")", "-", "np", ".", "sum", "(", "np", ".", "log", "(", "self", ".", "variance", ")", ")", ")" ]
Retrieves all current OrganizationType objects
def get_org_types ( self ) : if not self . client . session_id : self . client . request_session ( ) object_query = "SELECT Objects() FROM OrganizationType" result = self . client . execute_object_query ( object_query = object_query ) msql_result = result [ 'body' ] [ "ExecuteMSQLResult" ] return self . package_org_types ( msql_result [ "ResultValue" ] [ "ObjectSearchResult" ] [ "Objects" ] [ "MemberSuiteObject" ] )
7,698
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L80-L93
[ "def", "retract", "(", "args", ")", ":", "if", "not", "args", ".", "msg", ":", "return", "\"Syntax: !vote retract <pollnum>\"", "if", "not", "args", ".", "msg", ".", "isdigit", "(", ")", ":", "return", "\"Not A Valid Positive Integer.\"", "response", "=", "get_response", "(", "args", ".", "session", ",", "args", ".", "msg", ",", "args", ".", "nick", ")", "if", "response", "is", "None", ":", "return", "\"You haven't voted on that poll yet!\"", "args", ".", "session", ".", "delete", "(", "response", ")", "return", "\"Vote retracted\"" ]
Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use .
def package_org_types ( self , obj_list ) : org_type_list = [ ] for obj in obj_list : sane_obj = convert_ms_object ( obj [ 'Fields' ] [ 'KeyValueOfstringanyType' ] ) org = OrganizationType ( sane_obj ) org_type_list . append ( org ) return org_type_list
7,699
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L95-L107
[ "def", "assert_files_same", "(", "path1", ",", "path2", ")", ":", "# type: (str, str) -> None", "difflines", "=", "compare_files", "(", "path1", ",", "path2", ")", "assert", "len", "(", "difflines", ")", "==", "0", ",", "''", ".", "join", "(", "[", "'\\n'", "]", "+", "difflines", ")" ]