query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
for accessing global parameters
def param ( self , key , default = None ) : if key in self . parameters : return self . parameters [ key ] return default
8,000
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L811-L815
[ "def", "find_structure", "(", "self", ",", "filename_or_structure", ")", ":", "try", ":", "if", "isinstance", "(", "filename_or_structure", ",", "str", ")", ":", "s", "=", "Structure", ".", "from_file", "(", "filename_or_structure", ")", "elif", "isinstance", "(", "filename_or_structure", ",", "Structure", ")", ":", "s", "=", "filename_or_structure", "else", ":", "raise", "MPRestError", "(", "\"Provide filename or Structure object.\"", ")", "payload", "=", "{", "'structure'", ":", "json", ".", "dumps", "(", "s", ".", "as_dict", "(", ")", ",", "cls", "=", "MontyEncoder", ")", "}", "response", "=", "self", ".", "session", ".", "post", "(", "'{}/find_structure'", ".", "format", "(", "self", ".", "preamble", ")", ",", "data", "=", "payload", ")", "if", "response", ".", "status_code", "in", "[", "200", ",", "400", "]", ":", "resp", "=", "json", ".", "loads", "(", "response", ".", "text", ",", "cls", "=", "MontyDecoder", ")", "if", "resp", "[", "'valid_response'", "]", ":", "return", "resp", "[", "'response'", "]", "else", ":", "raise", "MPRestError", "(", "resp", "[", "\"error\"", "]", ")", "raise", "MPRestError", "(", "\"REST error with status code {} and error {}\"", ".", "format", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")", "except", "Exception", "as", "ex", ":", "raise", "MPRestError", "(", "str", "(", "ex", ")", ")" ]
Use this function to enter and exit the context at the beginning and end of a generator .
def generator ( self , gen , * args , * * kwargs ) : with self ( * args , * * kwargs ) : for i in gen : yield i
8,001
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L962-L975
[ "def", "update", "(", "self", ",", "other", ")", ":", "self", ".", "update_ttl", "(", "other", ".", "ttl", ")", "super", "(", "Rdataset", ",", "self", ")", ".", "update", "(", "other", ")" ]
Returns the original string if it was valid raises an argument error if it s not .
def validate_url ( self , original_string ) : # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse . urlparse ( original_string ) try : if self . path_only : assert not any ( [ pieces . scheme , pieces . netloc ] ) assert pieces . path else : assert all ( [ pieces . scheme , pieces . netloc ] ) valid_chars = set ( string . letters + string . digits + ":-_." ) assert set ( pieces . netloc ) <= valid_chars assert pieces . scheme in [ 'http' , 'https' ] except AssertionError as e : raise ArgumentError ( self . item_name , "The input you've provided is not a valid URL." ) return pieces
8,002
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/arguments/url.py#L15-L37
[ "def", "get_max_events_in_both_arrays", "(", "events_one", ",", "events_two", ")", ":", "events_one", "=", "np", ".", "ascontiguousarray", "(", "events_one", ")", "# change memory alignement for c++ library", "events_two", "=", "np", ".", "ascontiguousarray", "(", "events_two", ")", "# change memory alignement for c++ library", "event_result", "=", "np", ".", "empty", "(", "shape", "=", "(", "events_one", ".", "shape", "[", "0", "]", "+", "events_two", ".", "shape", "[", "0", "]", ",", ")", ",", "dtype", "=", "events_one", ".", "dtype", ")", "count", "=", "analysis_functions", ".", "get_max_events_in_both_arrays", "(", "events_one", ",", "events_two", ",", "event_result", ")", "return", "event_result", "[", ":", "count", "]" ]
Returns a chapter of the bible first checking to see if that chapter is on disk . If not hen it attempts to fetch it from the internet .
def get_chapter ( self , book_name , book_chapter , cache_chapter = True ) : try : logging . debug ( "Attempting to read chapter from disk" ) verses_list = self . _get_ondisk_chapter ( book_name , book_chapter ) except Exception as e : logging . debug ( "Could not read file from disk. Attempting the internet.." ) logging . debug ( e . message ) verses_list = self . _get_online_chapter ( book_name , book_chapter , cache_chapter = cache_chapter ) return verses_list
8,003
https://github.com/alextricity25/dwell_in_you_richly/blob/e705e1bc4fc0b8d2aa25680dfc432762b361c783/diyr/utils/bible.py#L122-L141
[ "def", "prox_unity", "(", "X", ",", "step", ",", "axis", "=", "0", ")", ":", "return", "X", "/", "np", ".", "sum", "(", "X", ",", "axis", "=", "axis", ",", "keepdims", "=", "True", ")" ]
Looks up a verse from online . recoveryversion . bible then returns it .
def verse_lookup ( self , book_name , book_chapter , verse , cache_chapter = True ) : verses_list = self . get_chapter ( book_name , str ( book_chapter ) , cache_chapter = cache_chapter ) return verses_list [ int ( verse ) - 1 ]
8,004
https://github.com/alextricity25/dwell_in_you_richly/blob/e705e1bc4fc0b8d2aa25680dfc432762b361c783/diyr/utils/bible.py#L230-L238
[ "def", "_get_window_list", "(", "self", ")", ":", "window_list", "=", "Quartz", ".", "CGWindowListCopyWindowInfo", "(", "Quartz", ".", "kCGWindowListExcludeDesktopElements", ",", "Quartz", ".", "kCGNullWindowID", ")", "return", "window_list" ]
Extend validate on submit to allow validation with schema
def validate_on_submit ( self ) : # validate form valid = FlaskWtf . validate_on_submit ( self ) # return in case no schema or not submitted if not self . _schema or not self . is_submitted ( ) : return valid # validate data with schema if got one and form was submitted data = dict ( ) for field in self . _fields : data [ field ] = self . _fields [ field ] . data result = self . schema . process ( data , context = self . _force_context ) self . set_errors ( result ) # set filtered data back to form for field in data : self . _fields [ field ] . data = data [ field ] return valid and not bool ( self . errors )
8,005
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/ext/flask_wtf.py#L13-L35
[ "def", "profile", "(", "fun", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "timer_name", "=", "kwargs", ".", "pop", "(", "\"prof_name\"", ",", "None", ")", "if", "not", "timer_name", ":", "module", "=", "inspect", ".", "getmodule", "(", "fun", ")", "c", "=", "[", "module", ".", "__name__", "]", "parentclass", "=", "labtypes", ".", "get_class_that_defined_method", "(", "fun", ")", "if", "parentclass", ":", "c", ".", "append", "(", "parentclass", ".", "__name__", ")", "c", ".", "append", "(", "fun", ".", "__name__", ")", "timer_name", "=", "\".\"", ".", "join", "(", "c", ")", "start", "(", "timer_name", ")", "ret", "=", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", "stop", "(", "timer_name", ")", "return", "ret" ]
Populate field errors with errors from schema validation
def set_errors ( self , result ) : # todo: use wtf locale errors = result . get_messages ( ) for property_name in errors : if not hasattr ( self , property_name ) : continue # ignore errors for missing fields prop_errors = errors [ property_name ] if type ( prop_errors ) is not list : prop_errors = [ '<Nested schema result following...>' ] if property_name in self . errors : self . errors [ property_name ] . extend ( prop_errors ) else : self . errors [ property_name ] = prop_errors
8,006
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/ext/flask_wtf.py#L40-L56
[ "def", "GetEntries", "(", "self", ",", "parser_mediator", ",", "data", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "# Walk through one of the torrent keys to ensure it's from a valid file.", "for", "key", ",", "value", "in", "iter", "(", "data", ".", "items", "(", ")", ")", ":", "if", "not", "'.torrent'", "in", "key", ":", "continue", "caption", "=", "value", ".", "get", "(", "'caption'", ")", "path", "=", "value", ".", "get", "(", "'path'", ")", "seedtime", "=", "value", ".", "get", "(", "'seedtime'", ")", "if", "not", "caption", "or", "not", "path", "or", "seedtime", "<", "0", ":", "raise", "errors", ".", "WrongBencodePlugin", "(", "self", ".", "NAME", ")", "for", "torrent", ",", "value", "in", "iter", "(", "data", ".", "items", "(", ")", ")", ":", "if", "not", "'.torrent'", "in", "torrent", ":", "continue", "event_data", "=", "UTorrentEventData", "(", ")", "event_data", ".", "caption", "=", "value", ".", "get", "(", "'caption'", ",", "None", ")", "event_data", ".", "path", "=", "value", ".", "get", "(", "'path'", ",", "None", ")", "# Convert seconds to minutes.", "seedtime", "=", "value", ".", "get", "(", "'seedtime'", ",", "None", ")", "event_data", ".", "seedtime", ",", "_", "=", "divmod", "(", "seedtime", ",", "60", ")", "# Create timeline events based on extracted values.", "for", "event_key", ",", "event_value", "in", "iter", "(", "value", ".", "items", "(", ")", ")", ":", "if", "event_key", "==", "'added_on'", ":", "date_time", "=", "dfdatetime_posix_time", ".", "PosixTime", "(", "timestamp", "=", "event_value", ")", "event", "=", "time_events", ".", "DateTimeValuesEvent", "(", "date_time", ",", "definitions", ".", "TIME_DESCRIPTION_ADDED", ")", "parser_mediator", ".", "ProduceEventWithEventData", "(", "event", ",", "event_data", ")", "elif", "event_key", "==", "'completed_on'", ":", "date_time", "=", "dfdatetime_posix_time", ".", "PosixTime", "(", "timestamp", "=", "event_value", ")", "event", "=", "time_events", ".", "DateTimeValuesEvent", "(", "date_time", ",", "definitions", ".", "TIME_DESCRIPTION_FILE_DOWNLOADED", ")", "parser_mediator", ".", "ProduceEventWithEventData", "(", "event", ",", "event_data", ")", "elif", "event_key", "==", "'modtimes'", ":", "for", "modtime", "in", "event_value", ":", "# Some values are stored as 0, skip those.", "if", "not", "modtime", ":", "continue", "date_time", "=", "dfdatetime_posix_time", ".", "PosixTime", "(", "timestamp", "=", "modtime", ")", "event", "=", "time_events", ".", "DateTimeValuesEvent", "(", "date_time", ",", "definitions", ".", "TIME_DESCRIPTION_MODIFICATION", ")", "parser_mediator", ".", "ProduceEventWithEventData", "(", "event", ",", "event_data", ")" ]
Processes a sorted and page - partitioned sequence of revision documents into and adds a persistence field to them containing statistics about how each token added in the revision persisted through future revisions .
def diffs2persistence ( rev_docs , window_size = 50 , revert_radius = 15 , sunset = None , verbose = False ) : rev_docs = mwxml . utilities . normalize ( rev_docs ) window_size = int ( window_size ) revert_radius = int ( revert_radius ) sunset = Timestamp ( sunset ) if sunset is not None else Timestamp ( time . time ( ) ) # Group the docs by page page_docs = groupby ( rev_docs , key = lambda d : d [ 'page' ] [ 'title' ] ) for page_title , rev_docs in page_docs : if verbose : sys . stderr . write ( page_title + ": " ) # We need a look-ahead to know how long this revision was visible rev_docs = peekable ( rev_docs ) # The window allows us to manage memory window = deque ( maxlen = window_size ) # The state does the actual processing work state = DiffState ( revert_radius = revert_radius ) while rev_docs : rev_doc = next ( rev_docs ) next_doc = rev_docs . peek ( None ) if next_doc is not None : seconds_visible = Timestamp ( next_doc [ 'timestamp' ] ) - Timestamp ( rev_doc [ 'timestamp' ] ) else : seconds_visible = sunset - Timestamp ( rev_doc [ 'timestamp' ] ) if seconds_visible < 0 : logger . warn ( "Seconds visible {0} is less than zero." . format ( seconds_visible ) ) seconds_visible = 0 _ , tokens_added , _ = state . update_opdocs ( rev_doc [ 'sha1' ] , rev_doc [ 'diff' ] [ 'ops' ] , ( rev_doc [ 'user' ] , seconds_visible ) ) if len ( window ) == window_size : # Time to start writing some stats old_doc , old_added = window [ 0 ] window . append ( ( rev_doc , tokens_added ) ) persistence = token_persistence ( old_doc , old_added , window , None ) old_doc [ 'persistence' ] = persistence yield old_doc if verbose : sys . stderr . write ( "." ) sys . stderr . flush ( ) else : window . append ( ( rev_doc , tokens_added ) ) while len ( window ) > 0 : old_doc , old_added = window . popleft ( ) persistence = token_persistence ( old_doc , old_added , window , sunset ) old_doc [ 'persistence' ] = persistence yield old_doc if verbose : sys . stderr . write ( "_" ) sys . stderr . flush ( ) if verbose : sys . stderr . write ( "\n" )
8,007
https://github.com/mediawiki-utilities/python-mwpersistence/blob/2b98847fb8acaca38b3cbf94bde3fd7e27d2b67d/mwpersistence/utilities/diffs2persistence.py#L100-L197
[ "def", "_get_window_list", "(", "self", ")", ":", "window_list", "=", "Quartz", ".", "CGWindowListCopyWindowInfo", "(", "Quartz", ".", "kCGWindowListExcludeDesktopElements", ",", "Quartz", ".", "kCGNullWindowID", ")", "return", "window_list" ]
Return generator by its name
def generator ( name ) : name = name . upper ( ) if name not in WHash . __hash_map__ . keys ( ) : raise ValueError ( 'Hash generator "%s" not available' % name ) return WHash . __hash_map__ [ name ]
8,008
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/hash.py#L241-L251
[ "def", "initialize_schema", "(", "connection", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"PRAGMA application_id={}\"", ".", "format", "(", "_TENSORBOARD_APPLICATION_ID", ")", ")", "cursor", ".", "execute", "(", "\"PRAGMA user_version={}\"", ".", "format", "(", "_TENSORBOARD_USER_VERSION", ")", ")", "with", "connection", ":", "for", "statement", "in", "_SCHEMA_STATEMENTS", ":", "lines", "=", "statement", ".", "strip", "(", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "message", "=", "lines", "[", "0", "]", "+", "(", "'...'", "if", "len", "(", "lines", ")", ">", "1", "else", "''", ")", "logger", ".", "debug", "(", "'Running DB init statement: %s'", ",", "message", ")", "cursor", ".", "execute", "(", "statement", ")" ]
Return generator by hash generator family name and digest size
def generator_by_digest ( family , digest_size ) : for generator_name in WHash . available_generators ( family = family ) : generator = WHash . generator ( generator_name ) if generator . generator_digest_size ( ) == digest_size : return generator raise ValueError ( 'Hash generator is not available' )
8,009
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/hash.py#L254-L265
[ "def", "_index_audio_cmu", "(", "self", ",", "basename", "=", "None", ",", "replace_already_indexed", "=", "False", ")", ":", "self", ".", "_prepare_audio", "(", "basename", "=", "basename", ",", "replace_already_indexed", "=", "replace_already_indexed", ")", "for", "staging_audio_basename", "in", "self", ".", "_list_audio_files", "(", "sub_dir", "=", "\"staging\"", ")", ":", "original_audio_name", "=", "''", ".", "join", "(", "staging_audio_basename", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "[", ":", "-", "3", "]", "pocketsphinx_command", "=", "''", ".", "join", "(", "[", "\"pocketsphinx_continuous\"", ",", "\"-infile\"", ",", "str", "(", "\"{}/staging/{}\"", ".", "format", "(", "self", ".", "src_dir", ",", "staging_audio_basename", ")", ")", ",", "\"-time\"", ",", "\"yes\"", ",", "\"-logfn\"", ",", "\"/dev/null\"", "]", ")", "try", ":", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Now indexing {}\"", ".", "format", "(", "staging_audio_basename", ")", ")", "output", "=", "subprocess", ".", "check_output", "(", "[", "\"pocketsphinx_continuous\"", ",", "\"-infile\"", ",", "str", "(", "\"{}/staging/{}\"", ".", "format", "(", "self", ".", "src_dir", ",", "staging_audio_basename", ")", ")", ",", "\"-time\"", ",", "\"yes\"", ",", "\"-logfn\"", ",", "\"/dev/null\"", "]", ",", "universal_newlines", "=", "True", ")", ".", "split", "(", "'\\n'", ")", "str_timestamps_with_sil_conf", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", ".", "split", "(", "\" \"", ")", ",", "filter", "(", "None", ",", "output", "[", "1", ":", "]", ")", ")", ")", "# Timestamps are putted in a list of a single element. To match", "# Watson's output.", "self", ".", "__timestamps_unregulated", "[", "original_audio_name", "+", "\".wav\"", "]", "=", "[", "(", "self", ".", "_timestamp_extractor_cmu", "(", "staging_audio_basename", ",", "str_timestamps_with_sil_conf", ")", ")", "]", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Done indexing {}\"", ".", "format", "(", "staging_audio_basename", ")", ")", "except", "OSError", "as", "e", ":", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "e", ",", "\"The command was: {}\"", ".", "format", "(", "pocketsphinx_command", ")", ")", "self", ".", "__errors", "[", "(", "time", "(", ")", ",", "staging_audio_basename", ")", "]", "=", "e", "self", ".", "_timestamp_regulator", "(", ")", "if", "self", ".", "get_verbosity", "(", ")", ":", "print", "(", "\"Finished indexing procedure\"", ")" ]
Useful method to generate iterator . It is generated by chaining the given info . If no info is specified then None is returned
def sequence ( cls , * info ) : if len ( info ) == 0 : return info = list ( info ) info . reverse ( ) result = WMessengerOnionSessionFlowProto . Iterator ( info [ 0 ] . layer_name ( ) , * * info [ 0 ] . layer_args ( ) ) for i in range ( 1 , len ( info ) ) : result = WMessengerOnionSessionFlowProto . Iterator ( info [ i ] . layer_name ( ) , next_iterator = result , * * info [ i ] . layer_args ( ) ) return result
8,010
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/messenger/session.py#L58-L80
[ "def", "replace_text", "(", "filepath", ",", "to_replace", ",", "replacement", ")", ":", "with", "open", "(", "filepath", ")", "as", "file", ":", "s", "=", "file", ".", "read", "(", ")", "s", "=", "s", ".", "replace", "(", "to_replace", ",", "replacement", ")", "with", "open", "(", "filepath", ",", "'w'", ")", "as", "file", ":", "file", ".", "write", "(", "s", ")" ]
Return new object by the given MAC - address
def from_string ( address ) : str_address = None if WMACAddress . re_dash_format . match ( address ) : str_address = "" . join ( address . split ( "-" ) ) elif WMACAddress . re_colon_format . match ( address ) : str_address = "" . join ( address . split ( ":" ) ) elif WMACAddress . re_cisco_format . match ( address ) : str_address = "" . join ( address . split ( "." ) ) elif WMACAddress . re_spaceless_format . match ( address ) : str_address = address if str_address is None : raise ValueError ( "Invalid MAC address format: " + address ) result = WMACAddress ( ) for octet_index in range ( WMACAddress . octet_count ) : octet = str_address [ : 2 ] result . __address [ octet_index ] = int ( octet , 16 ) str_address = str_address [ 2 : ] return result
8,011
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L87-L113
[ "def", "replace", "(", "self", ",", "episodes", ",", "length", ",", "rows", "=", "None", ")", ":", "rows", "=", "tf", ".", "range", "(", "self", ".", "_capacity", ")", "if", "rows", "is", "None", "else", "rows", "assert", "rows", ".", "shape", ".", "ndims", "==", "1", "assert_capacity", "=", "tf", ".", "assert_less", "(", "rows", ",", "self", ".", "_capacity", ",", "message", "=", "'capacity exceeded'", ")", "with", "tf", ".", "control_dependencies", "(", "[", "assert_capacity", "]", ")", ":", "assert_max_length", "=", "tf", ".", "assert_less_equal", "(", "length", ",", "self", ".", "_max_length", ",", "message", "=", "'max length exceeded'", ")", "with", "tf", ".", "control_dependencies", "(", "[", "assert_max_length", "]", ")", ":", "replace_ops", "=", "tools", ".", "nested", ".", "map", "(", "lambda", "var", ",", "val", ":", "tf", ".", "scatter_update", "(", "var", ",", "rows", ",", "val", ")", ",", "self", ".", "_buffers", ",", "episodes", ",", "flatten", "=", "True", ")", "with", "tf", ".", "control_dependencies", "(", "replace_ops", ")", ":", "return", "tf", ".", "scatter_update", "(", "self", ".", "_length", ",", "rows", ",", "length", ")" ]
Parse string for IPv4 address
def from_string ( address ) : address = address . split ( '.' ) if len ( address ) != WIPV4Address . octet_count : raise ValueError ( 'Invalid ip address: %s' % address ) result = WIPV4Address ( ) for i in range ( WIPV4Address . octet_count ) : result . __address [ i ] = WBinArray ( int ( address [ i ] ) , WFixedSizeByteArray . byte_size ) return result
8,012
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L173-L186
[ "def", "_create_download_failed_message", "(", "exception", ",", "url", ")", ":", "message", "=", "'Failed to download from:\\n{}\\nwith {}:\\n{}'", ".", "format", "(", "url", ",", "exception", ".", "__class__", ".", "__name__", ",", "exception", ")", "if", "_is_temporal_problem", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "requests", ".", "ConnectionError", ")", ":", "message", "+=", "'\\nPlease check your internet connection and try again.'", "else", ":", "message", "+=", "'\\nThere might be a problem in connection or the server failed to process '", "'your request. Please try again.'", "elif", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", ":", "try", ":", "server_message", "=", "''", "for", "elem", "in", "decode_data", "(", "exception", ".", "response", ".", "content", ",", "MimeType", ".", "XML", ")", ":", "if", "'ServiceException'", "in", "elem", ".", "tag", "or", "'Message'", "in", "elem", ".", "tag", ":", "server_message", "+=", "elem", ".", "text", ".", "strip", "(", "'\\n\\t '", ")", "except", "ElementTree", ".", "ParseError", ":", "server_message", "=", "exception", ".", "response", ".", "text", "message", "+=", "'\\nServer response: \"{}\"'", ".", "format", "(", "server_message", ")", "return", "message" ]
Convert address to string
def to_string ( address , dns_format = False ) : if isinstance ( address , WIPV4Address ) is False : raise TypeError ( 'Invalid address type' ) address = [ str ( int ( x ) ) for x in address . __address ] if dns_format is False : return '.' . join ( address ) address . reverse ( ) return ( '.' . join ( address ) + '.in-addr.arpa' )
8,013
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L190-L204
[ "def", "parse_flash_log", "(", "self", ",", "logf", ")", ":", "data", "=", "OrderedDict", "(", ")", "samplelogs", "=", "self", ".", "split_log", "(", "logf", "[", "'f'", "]", ")", "for", "slog", "in", "samplelogs", ":", "try", ":", "sample", "=", "dict", "(", ")", "## Sample name ##", "s_name", "=", "self", ".", "clean_pe_name", "(", "slog", ",", "logf", "[", "'root'", "]", ")", "if", "s_name", "is", "None", ":", "continue", "sample", "[", "'s_name'", "]", "=", "s_name", "## Log attributes ##", "sample", "[", "'totalpairs'", "]", "=", "self", ".", "get_field", "(", "'Total pairs'", ",", "slog", ")", "sample", "[", "'discardpairs'", "]", "=", "self", ".", "get_field", "(", "'Discarded pairs'", ",", "slog", ")", "sample", "[", "'percdiscard'", "]", "=", "self", ".", "get_field", "(", "'Percent Discarded'", ",", "slog", ",", "fl", "=", "True", ")", "sample", "[", "'combopairs'", "]", "=", "self", ".", "get_field", "(", "'Combined pairs'", ",", "slog", ")", "sample", "[", "'inniepairs'", "]", "=", "self", ".", "get_field", "(", "'Innie pairs'", ",", "slog", ")", "sample", "[", "'outiepairs'", "]", "=", "self", ".", "get_field", "(", "'Outie pairs'", ",", "slog", ")", "sample", "[", "'uncombopairs'", "]", "=", "self", ".", "get_field", "(", "'Uncombined pairs'", ",", "slog", ")", "sample", "[", "'perccombo'", "]", "=", "self", ".", "get_field", "(", "'Percent combined'", ",", "slog", ",", "fl", "=", "True", ")", "data", "[", "s_name", "]", "=", "sample", "except", "Exception", "as", "err", ":", "log", ".", "warning", "(", "\"Error parsing record in {}. {}\"", ".", "format", "(", "logf", "[", "'fn'", "]", ",", "err", ")", ")", "log", ".", "debug", "(", "traceback", ".", "format_exc", "(", ")", ")", "continue", "return", "data" ]
Return the first IP address of this network
def first_address ( self , skip_network_address = True ) : bin_address = self . __address . bin_address ( ) bin_address_length = len ( bin_address ) if self . __mask > ( bin_address_length - 2 ) : skip_network_address = False for i in range ( bin_address_length - self . __mask ) : bin_address [ self . __mask + i ] = 0 if skip_network_address : bin_address [ bin_address_length - 1 ] = 1 return WIPV4Address ( bin_address )
8,014
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L269-L287
[ "def", "_unscramble_regressor_columns", "(", "parent_data", ",", "data", ")", ":", "matches", "=", "[", "'_power[0-9]+'", ",", "'_derivative[0-9]+'", "]", "var", "=", "OrderedDict", "(", "(", "c", ",", "deque", "(", ")", ")", "for", "c", "in", "parent_data", ".", "columns", ")", "for", "c", "in", "data", ".", "columns", ":", "col", "=", "c", "for", "m", "in", "matches", ":", "col", "=", "re", ".", "sub", "(", "m", ",", "''", ",", "col", ")", "if", "col", "==", "c", ":", "var", "[", "col", "]", ".", "appendleft", "(", "c", ")", "else", ":", "var", "[", "col", "]", ".", "append", "(", "c", ")", "unscrambled", "=", "reduce", "(", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ")", ",", "var", ".", "values", "(", ")", ")", "return", "data", "[", "[", "*", "unscrambled", "]", "]" ]
Return the last IP address of this network
def last_address ( self , skip_broadcast_address = True ) : bin_address = self . __address . bin_address ( ) bin_address_length = len ( bin_address ) if self . __mask > ( bin_address_length - 2 ) : skip_broadcast_address = False for i in range ( bin_address_length - self . __mask ) : bin_address [ self . __mask + i ] = 1 if skip_broadcast_address : bin_address [ bin_address_length - 1 ] = 0 return WIPV4Address ( bin_address )
8,015
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L290-L308
[ "def", "_unscramble_regressor_columns", "(", "parent_data", ",", "data", ")", ":", "matches", "=", "[", "'_power[0-9]+'", ",", "'_derivative[0-9]+'", "]", "var", "=", "OrderedDict", "(", "(", "c", ",", "deque", "(", ")", ")", "for", "c", "in", "parent_data", ".", "columns", ")", "for", "c", "in", "data", ".", "columns", ":", "col", "=", "c", "for", "m", "in", "matches", ":", "col", "=", "re", ".", "sub", "(", "m", ",", "''", ",", "col", ")", "if", "col", "==", "c", ":", "var", "[", "col", "]", ".", "appendleft", "(", "c", ")", "else", ":", "var", "[", "col", "]", ".", "append", "(", "c", ")", "unscrambled", "=", "reduce", "(", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ")", ",", "var", ".", "values", "(", ")", ")", "return", "data", "[", "[", "*", "unscrambled", "]", "]" ]
Return iterator that can iterate over network addresses
def iterator ( self , skip_network_address = True , skip_broadcast_address = True ) : return WNetworkIPV4Iterator ( self , skip_network_address , skip_broadcast_address )
8,016
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L310-L318
[ "def", "unregisterHandler", "(", "self", ",", "fh", ")", ":", "try", ":", "self", ".", "fds", ".", "remove", "(", "fh", ")", "except", "KeyError", ":", "pass", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "data", ".", "rollover", "(", ")", "# rollover data on close.", "finally", ":", "self", ".", "lock", ".", "release", "(", ")", "if", "self", ".", "closing", "and", "not", "self", ".", "fds", ":", "self", ".", "data", ".", "close", "(", ")" ]
Convert doted - written FQDN address to WFQDN object
def from_string ( address ) : if len ( address ) == 0 : return WFQDN ( ) if address [ - 1 ] == '.' : address = address [ : - 1 ] if len ( address ) > WFQDN . maximum_fqdn_length : raise ValueError ( 'Invalid address' ) result = WFQDN ( ) for label in address . split ( '.' ) : if isinstance ( label , str ) and WFQDN . re_label . match ( label ) : result . _labels . append ( label ) else : raise ValueError ( 'Invalid address' ) return result
8,017
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L443-L465
[ "def", "load_config_file", "(", "self", ")", ":", "config_parser", "=", "SafeConfigParser", "(", ")", "config_parser", ".", "read", "(", "self", ".", "CONFIG_FILE", ")", "if", "config_parser", ".", "has_section", "(", "'handlers'", ")", ":", "self", ".", "_config", "[", "'handlers_package'", "]", "=", "config_parser", ".", "get", "(", "'handlers'", ",", "'package'", ")", "if", "config_parser", ".", "has_section", "(", "'auth'", ")", ":", "self", ".", "_config", "[", "'consumer_key'", "]", "=", "config_parser", ".", "get", "(", "'auth'", ",", "'consumer_key'", ")", "self", ".", "_config", "[", "'consumer_secret'", "]", "=", "config_parser", ".", "get", "(", "'auth'", ",", "'consumer_secret'", ")", "self", ".", "_config", "[", "'token_key'", "]", "=", "config_parser", ".", "get", "(", "'auth'", ",", "'token_key'", ")", "self", ".", "_config", "[", "'token_secret'", "]", "=", "config_parser", ".", "get", "(", "'auth'", ",", "'token_secret'", ")", "if", "config_parser", ".", "has_section", "(", "'stream'", ")", ":", "self", ".", "_config", "[", "'user_stream'", "]", "=", "config_parser", ".", "get", "(", "'stream'", ",", "'user_stream'", ")", ".", "lower", "(", ")", "==", "'true'", "else", ":", "self", ".", "_config", "[", "'user_stream'", "]", "=", "False", "if", "config_parser", ".", "has_option", "(", "'general'", ",", "'min_seconds_between_errors'", ")", ":", "self", ".", "_config", "[", "'min_seconds_between_errors'", "]", "=", "config_parser", ".", "get", "(", "'general'", ",", "'min_seconds_between_errors'", ")", "if", "config_parser", ".", "has_option", "(", "'general'", ",", "'sleep_seconds_on_consecutive_errors'", ")", ":", "self", ".", "_config", "[", "'sleep_seconds_on_consecutive_errors'", "]", "=", "config_parser", ".", "get", "(", "'general'", ",", "'sleep_seconds_on_consecutive_errors'", ")" ]
Return doted - written address by the given WFQDN object
def to_string ( address , leading_dot = False ) : if isinstance ( address , WFQDN ) is False : raise TypeError ( 'Invalid type for FQDN address' ) result = '.' . join ( address . _labels ) return result if leading_dot is False else ( result + '.' )
8,018
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/primitives.py#L469-L481
[ "def", "recover_and_supervise", "(", "recovery_file", ")", ":", "try", ":", "logging", ".", "info", "(", "\"Attempting to recover Supervisor data from \"", "+", "recovery_file", ")", "with", "open", "(", "recovery_file", ")", "as", "rf", ":", "recovery_data", "=", "json", ".", "load", "(", "rf", ")", "monitor_data", "=", "recovery_data", "[", "'monitor_data'", "]", "dependencies", "=", "recovery_data", "[", "'dependencies'", "]", "args", "=", "recovery_data", "[", "'args'", "]", "except", ":", "logging", ".", "error", "(", "\"Could not recover monitor data, exiting...\"", ")", "return", "1", "logging", ".", "info", "(", "\"Data successfully loaded, resuming Supervisor\"", ")", "supervise_until_complete", "(", "monitor_data", ",", "dependencies", ",", "args", ",", "recovery_file", ")" ]
Re - parent the applet .
def qteReparent ( self , parent ) : # Set the new parent. self . setParent ( parent ) # If this parent has a Qtmacs structure then query it for the # parent window, otherwise set the parent to None. try : self . _qteAdmin . parentWindow = parent . qteParentWindow ( ) except AttributeError : self . _qteAdmin . parentWindow = None # Sanity check: if parent : msg = 'Parent is neither None, nor does it have a' msg += 'qteParentWindow field --> bug' print ( msg )
8,019
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L222-L257
[ "def", "describe_topic", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "topics", "=", "list_topics", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "ret", "=", "{", "}", "for", "topic", ",", "arn", "in", "topics", ".", "items", "(", ")", ":", "if", "name", "in", "(", "topic", ",", "arn", ")", ":", "ret", "=", "{", "'TopicArn'", ":", "arn", "}", "ret", "[", "'Attributes'", "]", "=", "get_topic_attributes", "(", "arn", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "ret", "[", "'Subscriptions'", "]", "=", "list_subscriptions_by_topic", "(", "arn", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "# Grab extended attributes for the above subscriptions", "for", "sub", "in", "range", "(", "len", "(", "ret", "[", "'Subscriptions'", "]", ")", ")", ":", "sub_arn", "=", "ret", "[", "'Subscriptions'", "]", "[", "sub", "]", "[", "'SubscriptionArn'", "]", "if", "not", "sub_arn", ".", "startswith", "(", "'arn:aws:sns:'", ")", ":", "# Sometimes a sub is in e.g. PendingAccept or other", "# wierd states and doesn't have an ARN yet", "log", ".", "debug", "(", "'Subscription with invalid ARN %s skipped...'", ",", "sub_arn", ")", "continue", "deets", "=", "get_subscription_attributes", "(", "SubscriptionArn", "=", "sub_arn", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "ret", "[", "'Subscriptions'", "]", "[", "sub", "]", ".", "update", "(", "deets", ")", "return", "ret" ]
Augment the standard Qt widgetObj with Qtmacs specific fields .
def qteAddWidget ( self , widgetObj : QtGui . QWidget , isFocusable : bool = True , widgetSignature : str = None , autoBind : bool = True ) : # Add a Qtmacs data structure to the widget to allow their # event administration. Note that, in all likelihood, the # widget is an arbitrary Qt widget (eg. QLineEdit, # QPushButton, etc). widgetObj . _qteAdmin = QtmacsAdminStructure ( self , isFocusable = isFocusable ) widgetObj . _qteAdmin . appletID = self . _qteAdmin . appletID # Specify that this widget is not a QtmacsApplet. widgetObj . _qteAdmin . isQtmacsApplet = False # Remember the signature of the applet containing this widget. widgetObj . _qteAdmin . appletSignature = self . qteAppletSignature ( ) # Set the widget signature. If none was specified, use the # class name (eg. QLineEdit). if widgetSignature is None : widgetObj . _qteAdmin . widgetSignature = widgetObj . __class__ . __name__ else : widgetObj . _qteAdmin . widgetSignature = widgetSignature # For convenience, as it is otherwise difficult for the macro # programmer to determine the widget signature used by Qtmacs. # Note: the "wo" is only a shorthand to avoid too long lines. wo = widgetObj wo . qteSignature = wo . _qteAdmin . widgetSignature wo . qteSetKeyFilterPolicy = wo . _qteAdmin . qteSetKeyFilterPolicy del wo # Add the widget to the widgetList of this QtmacsApplet. # Important: this MUST happen before macros and key-bindings are loaded # and bound automatically (see code below) because the method to # bind the keys will verify that the widget exists in ``widgetList``. self . _qteAdmin . widgetList . append ( widgetObj ) # If a widget has a default key-bindings file then the global # dictionary ``default_widget_keybindings`` will contain its # name. default_bind = qte_global . default_widget_keybindings if autoBind and ( widgetObj . qteSignature in default_bind ) : # Shorthand. module_name = default_bind [ widgetObj . qteSignature ] # Import the module with the default key-bindings for the # current widget type. try : mod = importlib . import_module ( module_name ) except ImportError : msg = ( 'Module <b>{}</b> could not be imported.' . format ( module_name ) ) self . qteLogger . exception ( msg , stack_info = True ) return if hasattr ( mod , 'install_macros_and_bindings' ) : # By convention, the module has an # install_macros_and_bindings method. If an error # occurs intercept it, but do not abort the method # since the error only relates to a failed attempt to # apply default key-bindings, not to register the # widget (the main purpose of this method). try : mod . install_macros_and_bindings ( widgetObj ) except Exception : msg = ( '<b>install_macros_and_bindings</b> function' ' in <b>{}</b> did not execute properly.' ) msg = msg . format ( module_name ) self . qteLogger . error ( msg , stack_info = True ) else : msg = ( 'Module <b>{}</b> has no ' '<b>install_macros_and_bindings</b>' ' method' . format ( module_name ) ) self . qteLogger . error ( msg ) return widgetObj
8,020
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L260-L383
[ "def", "get_chapter", "(", "self", ",", "book_name", ",", "book_chapter", ",", "cache_chapter", "=", "True", ")", ":", "try", ":", "logging", ".", "debug", "(", "\"Attempting to read chapter from disk\"", ")", "verses_list", "=", "self", ".", "_get_ondisk_chapter", "(", "book_name", ",", "book_chapter", ")", "except", "Exception", "as", "e", ":", "logging", ".", "debug", "(", "\"Could not read file from disk. Attempting the internet..\"", ")", "logging", ".", "debug", "(", "e", ".", "message", ")", "verses_list", "=", "self", ".", "_get_online_chapter", "(", "book_name", ",", "book_chapter", ",", "cache_chapter", "=", "cache_chapter", ")", "return", "verses_list" ]
Specify the applet signature .
def qteSetAppletSignature ( self , signature : str ) : if '*' in signature : raise QtmacsOtherError ( 'The applet signature must not contain "*"' ) if signature == '' : raise QtmacsOtherError ( 'The applet signature must be non-empty' ) self . _qteAdmin . appletSignature = signature
8,021
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L386-L425
[ "def", "to_json", "(", "self", ")", ":", "web_resp", "=", "collections", ".", "OrderedDict", "(", ")", "web_resp", "[", "'status_code'", "]", "=", "self", ".", "status_code", "web_resp", "[", "'status_text'", "]", "=", "dict", "(", "HTTP_CODES", ")", ".", "get", "(", "self", ".", "status_code", ")", "web_resp", "[", "'data'", "]", "=", "self", ".", "data", "if", "self", ".", "data", "is", "not", "None", "else", "{", "}", "web_resp", "[", "'errors'", "]", "=", "self", ".", "errors", "or", "[", "]", "return", "web_resp" ]
Remove all widgets from the internal widget list that do not exist anymore according to SIP .
def qteAutoremoveDeletedWidgets ( self ) : widget_list = self . _qteAdmin . widgetList deleted_widgets = [ _ for _ in widget_list if sip . isdeleted ( _ ) ] for widgetObj in deleted_widgets : self . _qteAdmin . widgetList . remove ( widgetObj )
8,022
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L446-L466
[ "def", "configure", "(", "self", ",", "organization", ",", "base_url", "=", "''", ",", "ttl", "=", "''", ",", "max_ttl", "=", "''", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'organization'", ":", "organization", ",", "'base_url'", ":", "base_url", ",", "'ttl'", ":", "ttl", ",", "'max_ttl'", ":", "max_ttl", ",", "}", "api_path", "=", "'/v1/auth/{mount_point}/config'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Change the focus order of the widgets in this applet .
def qteSetWidgetFocusOrder ( self , widList : tuple ) : # A list with less than two entries cannot be re-ordered. if len ( widList ) < 2 : return # Housekeeping: remove non-existing widgets from the admin structure. self . qteAutoremoveDeletedWidgets ( ) # Remove all **None** widgets. widList = [ _ for _ in widList if _ is not None ] # Ensure that all widgets exist in the current applet. for wid in widList : if wid not in self . _qteAdmin . widgetList : msg = 'Cannot change focus order because some ' msg += 'widgets do not exist.' self . qteLogger . warning ( msg ) return # Remove all duplicates from the user supplied list. newList = [ widList [ 0 ] ] for wid in widList [ 1 : ] : if wid not in newList : newList . append ( wid ) # If the duplicate free list has only one entry then there is # nothing left to reorder. if len ( newList ) < 2 : return # The purpose of the code is the following: suppose # _qteAdmin.widgetList = [0,1,2,3,4,5] and newList=[2,5,1]. # Then change _qteAdmin.widgetList to [0,1,2,5,1,3,4]. Step # 1: remove all but the first widget in newList from # _qteAdmin.widgetList. for wid in newList [ 1 : ] : self . _qteAdmin . widgetList . remove ( wid ) # 2: re-insert the removed elements as a sequence again. startIdx = self . _qteAdmin . widgetList . index ( newList [ 0 ] ) + 1 for idx , wid in enumerate ( newList [ 1 : ] ) : self . _qteAdmin . widgetList . insert ( startIdx + idx , wid )
8,023
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L469-L529
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "REG_VALIDATION_STR", "not", "in", "request", ".", "session", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "try", ":", "self", ".", "temporaryRegistration", "=", "TemporaryRegistration", ".", "objects", ".", "get", "(", "id", "=", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", ".", "get", "(", "'temporaryRegistrationId'", ")", ")", "except", "ObjectDoesNotExist", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "'Invalid registration identifier passed to sign-up form.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "expiry", "=", "parse_datetime", "(", "self", ".", "request", ".", "session", "[", "REG_VALIDATION_STR", "]", ".", "get", "(", "'temporaryRegistrationExpiry'", ",", "''", ")", ",", ")", "if", "not", "expiry", "or", "expiry", "<", "timezone", ".", "now", "(", ")", ":", "messages", ".", "info", "(", "request", ",", "_", "(", "'Your registration session has expired. Please try again.'", ")", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'registration'", ")", ")", "return", "super", "(", "StudentInfoView", ",", "self", ")", ".", "dispatch", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Return the next widget in cyclic order .
def qteNextWidget ( self , numSkip : int = 1 , ofsWidget : QtGui . QWidget = None , skipVisible : bool = False , skipInvisible : bool = True , skipFocusable : bool = False , skipUnfocusable : bool = True ) : # Check type of input arguments. if not hasattr ( ofsWidget , '_qteAdmin' ) and ( ofsWidget is not None ) : msg = '<ofsWidget> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Housekeeping: remove non-existing widgets from the admin structure. self . qteAutoremoveDeletedWidgets ( ) # Make a copy of the widget list. widList = list ( self . _qteAdmin . widgetList ) # Return immediately if the widget list is empty. The actual # return value is either self._qteActiveWidget (if it points # to a child widget of the current applet), or None. if not len ( widList ) : if qteGetAppletFromWidget ( self . _qteActiveWidget ) is self : return self . _qteActiveWidget else : return None if skipInvisible : # Remove all invisible widgets. widList = [ wid for wid in widList if wid . isVisible ( ) ] if skipVisible : # Remove all visible widgets. widList = [ wid for wid in widList if not wid . isVisible ( ) ] if skipFocusable : # Remove all visible widgets. widList = [ wid for wid in widList if not wid . _qteAdmin . isFocusable ] if skipUnfocusable : # Remove all unfocusable widgets. widList = [ wid for wid in widList if wid . _qteAdmin . isFocusable ] # Return immediately if the list is empty. This is typically # the case at startup before any applet has been added. if not len ( widList ) : return None # If no offset widget was given then use the currently active one. if ofsWidget is None : ofsWidget = self . _qteActiveWidget if ( ofsWidget is not None ) and ( numSkip == 0 ) : if qteIsQtmacsWidget ( ofsWidget ) : return ofsWidget # Determine the index of the offset widget; assume it is zero # if the widget does not exist, eg. if the currently active # applet is not part of the pruned widList list. try : ofsIdx = widList . index ( ofsWidget ) except ValueError : ofsIdx = 0 # Compute the index of the next widget and wrap around the # list if necessary. ofsIdx = ( ofsIdx + numSkip ) % len ( widList ) # Return the widget. return widList [ ofsIdx ]
8,024
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L532-L638
[ "def", "_add_credits_grade_to_section", "(", "url", ",", "section", ")", ":", "section_reg_data", "=", "get_resource", "(", "url", ")", "if", "section_reg_data", "is", "not", "None", ":", "section", ".", "student_grade", "=", "section_reg_data", "[", "'Grade'", "]", "section", ".", "is_auditor", "=", "section_reg_data", "[", "'Auditor'", "]", "if", "len", "(", "section_reg_data", "[", "'GradeDate'", "]", ")", ">", "0", ":", "section", ".", "grade_date", "=", "parse", "(", "section_reg_data", "[", "\"GradeDate\"", "]", ")", ".", "date", "(", ")", "try", ":", "raw_credits", "=", "section_reg_data", "[", "'Credits'", "]", ".", "strip", "(", ")", "section", ".", "student_credits", "=", "Decimal", "(", "raw_credits", ")", "except", "InvalidOperation", ":", "pass" ]
Give keyboard focus to widgetObj .
def qteMakeWidgetActive ( self , widgetObj : QtGui . QWidget ) : # Void the active widget information. if widgetObj is None : self . _qteActiveWidget = None return # Ensure that this applet is an ancestor of ``widgetObj`` # inside the Qt hierarchy. if qteGetAppletFromWidget ( widgetObj ) is not self : msg = 'The specified widget is not inside the current applet.' raise QtmacsOtherError ( msg ) # If widgetObj is not registered with Qtmacs then simply declare # it active and return. if not hasattr ( widgetObj , '_qteAdmin' ) : self . _qteActiveWidget = widgetObj return # Do nothing if widgetObj refers to an applet. if widgetObj . _qteAdmin . isQtmacsApplet : self . _qteActiveWidget = None return # Housekeeping: remove non-existing widgets from the admin structure. self . qteAutoremoveDeletedWidgets ( ) # Verify the widget is registered for this applet. if widgetObj not in self . _qteAdmin . widgetList : msg = 'Widget is not registered for this applet.' self . qteLogger . error ( msg , stack_info = True ) self . _qteActiveWidget = None return # The focus manager in QtmacsMain will hand the focus to # whatever the _qteActiveWidget variable of the active applet # points to. self . qteSetWidgetFocusOrder ( ( self . _qteActiveWidget , widgetObj ) ) self . _qteActiveWidget = widgetObj
8,025
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_applet.py#L641-L698
[ "def", "_get_filename", "(", "self", ")", ":", "self", ".", "filename", "=", "expanduser", "(", "os", ".", "path", ".", "join", "(", "self", ".", "rsr_dir", ",", "'rsr_{0}_{1}.h5'", ".", "format", "(", "self", ".", "instrument", ",", "self", ".", "platform_name", ")", ")", ")", "LOG", ".", "debug", "(", "'Filename: %s'", ",", "str", "(", "self", ".", "filename", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "filename", ")", "or", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "filename", ")", ":", "LOG", ".", "warning", "(", "\"No rsr file %s on disk\"", ",", "self", ".", "filename", ")", "if", "self", ".", "_rsr_data_version_uptodate", ":", "LOG", ".", "info", "(", "\"RSR data up to date, so seems there is no support for this platform and sensor\"", ")", "else", ":", "# Try download from the internet!", "if", "self", ".", "do_download", ":", "LOG", ".", "info", "(", "\"Will download from internet...\"", ")", "download_rsr", "(", ")", "if", "self", ".", "_get_rsr_data_version", "(", ")", "==", "RSR_DATA_VERSION", ":", "self", ".", "_rsr_data_version_uptodate", "=", "True", "if", "not", "self", ".", "_rsr_data_version_uptodate", ":", "LOG", ".", "warning", "(", "\"rsr data may not be up to date: %s\"", ",", "self", ".", "filename", ")", "if", "self", ".", "do_download", ":", "LOG", ".", "info", "(", "\"Will download from internet...\"", ")", "download_rsr", "(", ")" ]
Splits a node key .
def split_key ( key ) : if key == KEY_SEP : return ( ) key_chunks = tuple ( key . strip ( KEY_SEP ) . split ( KEY_SEP ) ) if key_chunks [ 0 ] . startswith ( KEY_SEP ) : return ( key_chunks [ 0 ] [ len ( KEY_SEP ) : ] , ) + key_chunks [ 1 : ] else : return key_chunks
8,026
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L32-L40
[ "def", "replace_postgres_db", "(", "self", ",", "file_url", ")", ":", "self", ".", "print_message", "(", "\"Replacing postgres database\"", ")", "if", "file_url", ":", "self", ".", "print_message", "(", "\"Sourcing data from online backup file '%s'\"", "%", "file_url", ")", "source_file", "=", "self", ".", "download_file_from_url", "(", "self", ".", "args", ".", "source_app", ",", "file_url", ")", "elif", "self", ".", "databases", "[", "'source'", "]", "[", "'name'", "]", ":", "self", ".", "print_message", "(", "\"Sourcing data from database '%s'\"", "%", "self", ".", "databases", "[", "'source'", "]", "[", "'name'", "]", ")", "source_file", "=", "self", ".", "dump_database", "(", ")", "else", ":", "self", ".", "print_message", "(", "\"Sourcing data from local backup file %s\"", "%", "self", ".", "args", ".", "file", ")", "source_file", "=", "self", ".", "args", ".", "file", "self", ".", "drop_database", "(", ")", "self", ".", "create_database", "(", ")", "source_file", "=", "self", ".", "unzip_file_if_necessary", "(", "source_file", ")", "self", ".", "print_message", "(", "\"Importing '%s' into database '%s'\"", "%", "(", "source_file", ",", "self", ".", "databases", "[", "'destination'", "]", "[", "'name'", "]", ")", ")", "args", "=", "[", "\"pg_restore\"", ",", "\"--no-acl\"", ",", "\"--no-owner\"", ",", "\"--dbname=%s\"", "%", "self", ".", "databases", "[", "'destination'", "]", "[", "'name'", "]", ",", "source_file", ",", "]", "args", ".", "extend", "(", "self", ".", "databases", "[", "'destination'", "]", "[", "'args'", "]", ")", "subprocess", ".", "check_call", "(", "args", ")" ]
Updates the node data .
def set ( self , index , value = None , dir = False , ttl = None , expiration = None ) : if bool ( dir ) is ( value is not None ) : raise TypeError ( 'Choose one of value or directory' ) if ( ttl is not None ) is ( expiration is None ) : raise TypeError ( 'Both of ttl and expiration required' ) self . value = value if self . dir != dir : self . dir = dir self . nodes = { } if dir else None self . ttl = ttl self . expiration = expiration self . modified_index = index
8,027
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L54-L66
[ "def", "merged", "(", "self", ",", "other", ")", ":", "if", "self", ".", "name_", "!=", "other", ".", "name_", ":", "return", "None", "# cannot merge across object names", "def", "_r", "(", "r_", ")", ":", "r", "=", "Requirement", "(", "None", ")", "r", ".", "name_", "=", "r_", ".", "name_", "r", ".", "negate_", "=", "r_", ".", "negate_", "r", ".", "conflict_", "=", "r_", ".", "conflict_", "r", ".", "sep_", "=", "r_", ".", "sep_", "return", "r", "if", "self", ".", "range", "is", "None", ":", "return", "other", "elif", "other", ".", "range", "is", "None", ":", "return", "self", "elif", "self", ".", "conflict", ":", "if", "other", ".", "conflict", ":", "r", "=", "_r", "(", "self", ")", "r", ".", "range_", "=", "self", ".", "range_", "|", "other", ".", "range_", "r", ".", "negate_", "=", "(", "self", ".", "negate_", "and", "other", ".", "negate_", "and", "not", "r", ".", "range_", ".", "is_any", "(", ")", ")", "return", "r", "else", ":", "range_", "=", "other", ".", "range", "-", "self", ".", "range", "if", "range_", "is", "None", ":", "return", "None", "else", ":", "r", "=", "_r", "(", "other", ")", "r", ".", "range_", "=", "range_", "return", "r", "elif", "other", ".", "conflict", ":", "range_", "=", "self", ".", "range_", "-", "other", ".", "range_", "if", "range_", "is", "None", ":", "return", "None", "else", ":", "r", "=", "_r", "(", "self", ")", "r", ".", "range_", "=", "range_", "return", "r", "else", ":", "range_", "=", "self", ".", "range_", "&", "other", ".", "range_", "if", "range_", "is", "None", ":", "return", "None", "else", ":", "r", "=", "_r", "(", "self", ")", "r", ".", "range_", "=", "range_", "return", "r" ]
Makes an etcd result .
def make_result ( self , result_class , node = None , prev_node = None , remember = True , key_chunks = None , notify = True , * * kwargs ) : def canonicalize ( node , * * kwargs ) : return None if node is None else node . canonicalize ( * * kwargs ) index = self . index result = result_class ( canonicalize ( node , * * kwargs ) , canonicalize ( prev_node , * * kwargs ) , index ) if not remember : return result self . history [ index ] = result_class ( canonicalize ( node , include_nodes = False ) , canonicalize ( prev_node , include_nodes = False ) , index ) key_chunks = key_chunks or split_key ( node . key ) asymptotic_key_chunks = ( key_chunks [ : x + 1 ] for x in xrange ( len ( key_chunks ) ) ) event_keys = [ ( False , key_chunks ) ] for _key_chunks in asymptotic_key_chunks : exact = _key_chunks == key_chunks self . indices . setdefault ( _key_chunks , [ ] ) . append ( ( index , exact ) ) event_keys . append ( ( True , _key_chunks ) ) if notify : for event_key in event_keys : try : event = self . events . pop ( event_key ) except KeyError : pass else : event . set ( ) return result
8,028
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/mock.py#L124-L161
[ "def", "prepareToCalcEndOfPrdvP", "(", "self", ")", ":", "# We define aNrmNow all the way from BoroCnstNat up to max(self.aXtraGrid)", "# even if BoroCnstNat < BoroCnstArt, so we can construct the consumption", "# function as the lower envelope of the (by the artificial borrowing con-", "# straint) uconstrained consumption function, and the artificially con-", "# strained consumption function.", "aNrmNow", "=", "np", ".", "asarray", "(", "self", ".", "aXtraGrid", ")", "+", "self", ".", "BoroCnstNat", "ShkCount", "=", "self", ".", "TranShkValsNext", ".", "size", "aNrm_temp", "=", "np", ".", "tile", "(", "aNrmNow", ",", "(", "ShkCount", ",", "1", ")", ")", "# Tile arrays of the income shocks and put them into useful shapes", "aNrmCount", "=", "aNrmNow", ".", "shape", "[", "0", "]", "PermShkVals_temp", "=", "(", "np", ".", "tile", "(", "self", ".", "PermShkValsNext", ",", "(", "aNrmCount", ",", "1", ")", ")", ")", ".", "transpose", "(", ")", "TranShkVals_temp", "=", "(", "np", ".", "tile", "(", "self", ".", "TranShkValsNext", ",", "(", "aNrmCount", ",", "1", ")", ")", ")", ".", "transpose", "(", ")", "ShkPrbs_temp", "=", "(", "np", ".", "tile", "(", "self", ".", "ShkPrbsNext", ",", "(", "aNrmCount", ",", "1", ")", ")", ")", ".", "transpose", "(", ")", "# Get cash on hand next period", "mNrmNext", "=", "self", ".", "Rfree", "/", "(", "self", ".", "PermGroFac", "*", "PermShkVals_temp", ")", "*", "aNrm_temp", "+", "TranShkVals_temp", "# Store and report the results", "self", ".", "PermShkVals_temp", "=", "PermShkVals_temp", "self", ".", "ShkPrbs_temp", "=", "ShkPrbs_temp", "self", ".", "mNrmNext", "=", "mNrmNext", "self", ".", "aNrmNow", "=", "aNrmNow", "return", "aNrmNow" ]
Connect to the server and set everything up .
def connect ( self , host = 'localhost' ) : # Connect get_logger ( ) . info ( "Connecting to RabbitMQ server..." ) self . _conn = pika . BlockingConnection ( pika . ConnectionParameters ( host = host ) ) self . _channel = self . _conn . channel ( ) # Exchanger get_logger ( ) . info ( "Declaring topic exchanger {}..." . format ( self . exchange ) ) self . _channel . exchange_declare ( exchange = self . exchange , type = 'topic' ) # Create queue get_logger ( ) . info ( "Creating RabbitMQ queue..." ) result = self . _channel . queue_declare ( exclusive = True ) self . _queue_name = result . method . queue # Binding if self . listen_all : get_logger ( ) . info ( "Binding queue to exchanger {} (listen all)..." . format ( self . exchange ) ) self . _channel . queue_bind ( exchange = self . exchange , queue = self . _queue_name , routing_key = '*' ) else : for routing_key in self . topics : get_logger ( ) . info ( "Binding queue to exchanger {} " "with routing key {}..." . format ( self . exchange , routing_key ) ) self . _channel . queue_bind ( exchange = self . exchange , queue = self . _queue_name , routing_key = routing_key ) # Callback get_logger ( ) . info ( "Binding callback..." ) self . _channel . basic_consume ( self . _callback , queue = self . _queue_name , no_ack = True )
8,029
https://github.com/haum/hms_base/blob/7c0aed961b43cba043c703102e503cb40db81f58/hms_base/client.py#L45-L106
[ "def", "setOverlayTextureBounds", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTextureBounds", "pOverlayTextureBounds", "=", "VRTextureBounds_t", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "byref", "(", "pOverlayTextureBounds", ")", ")", "return", "result", ",", "pOverlayTextureBounds" ]
Send a dict with internal routing key to the exchange .
def publish ( self , topic , dct ) : get_logger ( ) . info ( "Publishing message {} on routing key " "{}..." . format ( dct , topic ) ) self . _channel . basic_publish ( exchange = self . exchange , routing_key = topic , body = json . dumps ( dct ) )
8,030
https://github.com/haum/hms_base/blob/7c0aed961b43cba043c703102e503cb40db81f58/hms_base/client.py#L108-L123
[ "def", "update_time_login", "(", "u_name", ")", ":", "entry", "=", "TabMember", ".", "update", "(", "time_login", "=", "tools", ".", "timestamp", "(", ")", ")", ".", "where", "(", "TabMember", ".", "user_name", "==", "u_name", ")", "entry", ".", "execute", "(", ")" ]
Internal method that will be called when receiving message .
def _callback ( self , ch , method , properties , body ) : get_logger ( ) . info ( "Message received! Calling listeners..." ) topic = method . routing_key dct = json . loads ( body . decode ( 'utf-8' ) ) for listener in self . listeners : listener ( self , topic , dct )
8,031
https://github.com/haum/hms_base/blob/7c0aed961b43cba043c703102e503cb40db81f58/hms_base/client.py#L140-L149
[ "def", "_database", "(", "self", ",", "writable", "=", "False", ")", ":", "if", "self", ".", "path", "==", "MEMORY_DB_NAME", ":", "if", "not", "self", ".", "inmemory_db", ":", "self", ".", "inmemory_db", "=", "xapian", ".", "inmemory_open", "(", ")", "return", "self", ".", "inmemory_db", "if", "writable", ":", "database", "=", "xapian", ".", "WritableDatabase", "(", "self", ".", "path", ",", "xapian", ".", "DB_CREATE_OR_OPEN", ")", "else", ":", "try", ":", "database", "=", "xapian", ".", "Database", "(", "self", ".", "path", ")", "except", "xapian", ".", "DatabaseOpeningError", ":", "raise", "InvalidIndexError", "(", "'Unable to open index at %s'", "%", "self", ".", "path", ")", "return", "database" ]
Internal method that will be called when receiving ping message .
def _handle_ping ( client , topic , dct ) : if dct [ 'type' ] == 'request' : resp = { 'type' : 'answer' , 'name' : client . name , 'source' : dct } client . publish ( 'ping' , resp )
8,032
https://github.com/haum/hms_base/blob/7c0aed961b43cba043c703102e503cb40db81f58/hms_base/client.py#L153-L162
[ "def", "read_ascii_spec", "(", "filename", ",", "wave_unit", "=", "u", ".", "AA", ",", "flux_unit", "=", "units", ".", "FLAM", ",", "*", "*", "kwargs", ")", ":", "header", "=", "{", "}", "dat", "=", "ascii", ".", "read", "(", "filename", ",", "*", "*", "kwargs", ")", "wave_unit", "=", "units", ".", "validate_unit", "(", "wave_unit", ")", "flux_unit", "=", "units", ".", "validate_unit", "(", "flux_unit", ")", "wavelengths", "=", "dat", ".", "columns", "[", "0", "]", ".", "data", ".", "astype", "(", "np", ".", "float64", ")", "*", "wave_unit", "fluxes", "=", "dat", ".", "columns", "[", "1", "]", ".", "data", ".", "astype", "(", "np", ".", "float64", ")", "*", "flux_unit", "return", "header", ",", "wavelengths", ",", "fluxes" ]
Create dictionary with argument names as keys and their passed values as values .
def _create_argument_value_pairs ( func , * args , * * kwargs ) : # Capture parameters that have been explicitly specified in function call try : arg_dict = signature ( func ) . bind_partial ( * args , * * kwargs ) . arguments except TypeError : return dict ( ) # Capture parameters that have not been explicitly specified # but have default values arguments = signature ( func ) . parameters for arg_name in arguments : if ( arguments [ arg_name ] . default != Parameter . empty ) and ( arguments [ arg_name ] . name not in arg_dict ) : arg_dict [ arguments [ arg_name ] . name ] = arguments [ arg_name ] . default return arg_dict
8,033
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/pcontracts.py#L48-L69
[ "def", "update", "(", "self", ",", "data", ")", ":", "self", ".", "_md", ".", "update", "(", "data", ")", "bufpos", "=", "self", ".", "_nbytes", "&", "63", "self", ".", "_nbytes", "+=", "len", "(", "data", ")", "if", "self", ".", "_rarbug", "and", "len", "(", "data", ")", ">", "64", ":", "dpos", "=", "self", ".", "block_size", "-", "bufpos", "while", "dpos", "+", "self", ".", "block_size", "<=", "len", "(", "data", ")", ":", "self", ".", "_corrupt", "(", "data", ",", "dpos", ")", "dpos", "+=", "self", ".", "block_size" ]
Generate message for exception .
def _get_contract_exception_dict ( contract_msg ) : # A pcontract-defined custom exception message is wrapped in a string # that starts with '[START CONTRACT MSG:' and ends with # '[STOP CONTRACT MSG]'. This is done to easily detect if an # exception raised is from a custom contract and thus be able # to easily retrieve the actual exception message start_token = "[START CONTRACT MSG: " stop_token = "[STOP CONTRACT MSG]" # No custom contract if contract_msg . find ( start_token ) == - 1 : return { "num" : 0 , "msg" : "Argument `*[argument_name]*` is not valid" , "type" : RuntimeError , "field" : "argument_name" , } # Custom contract msg_start = contract_msg . find ( start_token ) + len ( start_token ) contract_msg = contract_msg [ msg_start : ] contract_name = contract_msg [ : contract_msg . find ( "]" ) ] contract_msg = contract_msg [ contract_msg . find ( "]" ) + 1 : contract_msg . find ( stop_token ) ] exdict = _CUSTOM_CONTRACTS [ contract_name ] for exvalue in exdict . values ( ) : # pragma: no branch if exvalue [ "msg" ] == contract_msg : return exvalue
8,034
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/pcontracts.py#L134-L161
[ "def", "minion_config", "(", "opts", ",", "vm_", ")", ":", "# Don't start with a copy of the default minion opts; they're not always", "# what we need. Some default options are Null, let's set a reasonable default", "minion", "=", "{", "'master'", ":", "'salt'", ",", "'log_level'", ":", "'info'", ",", "'hash_type'", ":", "'sha256'", ",", "}", "# Now, let's update it to our needs", "minion", "[", "'id'", "]", "=", "vm_", "[", "'name'", "]", "master_finger", "=", "salt", ".", "config", ".", "get_cloud_config_value", "(", "'master_finger'", ",", "vm_", ",", "opts", ")", "if", "master_finger", "is", "not", "None", ":", "minion", "[", "'master_finger'", "]", "=", "master_finger", "minion", ".", "update", "(", "# Get ANY defined minion settings, merging data, in the following order", "# 1. VM config", "# 2. Profile config", "# 3. Global configuration", "salt", ".", "config", ".", "get_cloud_config_value", "(", "'minion'", ",", "vm_", ",", "opts", ",", "default", "=", "{", "}", ",", "search_global", "=", "True", ")", ")", "make_master", "=", "salt", ".", "config", ".", "get_cloud_config_value", "(", "'make_master'", ",", "vm_", ",", "opts", ")", "if", "'master'", "not", "in", "minion", "and", "make_master", "is", "not", "True", ":", "raise", "SaltCloudConfigError", "(", "'A master setting was not defined in the minion\\'s configuration.'", ")", "# Get ANY defined grains settings, merging data, in the following order", "# 1. VM config", "# 2. Profile config", "# 3. Global configuration", "minion", ".", "setdefault", "(", "'grains'", ",", "{", "}", ")", ".", "update", "(", "salt", ".", "config", ".", "get_cloud_config_value", "(", "'grains'", ",", "vm_", ",", "opts", ",", "default", "=", "{", "}", ",", "search_global", "=", "True", ")", ")", "return", "minion" ]
Return True if parameter contract is a custom contract False otherwise .
def _get_custom_contract ( param_contract ) : if not isinstance ( param_contract , str ) : return None for custom_contract in _CUSTOM_CONTRACTS : if re . search ( r"\b{0}\b" . format ( custom_contract ) , param_contract ) : return custom_contract return None
8,035
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/pcontracts.py#L164-L171
[ "def", "sqlite_dump_string", "(", "self", ",", "progress", ")", ":", "# First the schema #", "mdb_schema", "=", "sh", ".", "Command", "(", "\"mdb-schema\"", ")", "yield", "mdb_schema", "(", "self", ".", "path", ",", "\"sqlite\"", ")", ".", "encode", "(", "'utf8'", ")", "# Start a transaction, speeds things up when importing #", "yield", "\"BEGIN TRANSACTION;\\n\"", "# Then export every table #", "mdb_export", "=", "sh", ".", "Command", "(", "\"mdb-export\"", ")", "for", "table", "in", "progress", "(", "self", ".", "tables", ")", ":", "yield", "mdb_export", "(", "'-I'", ",", "'sqlite'", ",", "self", ".", "path", ",", "table", ")", ".", "encode", "(", "'utf8'", ")", "# End the transaction", "yield", "\"END TRANSACTION;\\n\"" ]
Extract replacement token from exception message .
def _get_replacement_token ( msg ) : return ( None if not re . search ( r"\*\[[\w|\W]+\]\*" , msg ) else re . search ( r"\*\[[\w|\W]+\]\*" , msg ) . group ( ) [ 2 : - 2 ] )
8,036
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/pcontracts.py#L304-L310
[ "def", "generate_ctrlptsw2d_file", "(", "file_in", "=", "''", ",", "file_out", "=", "'ctrlptsw.txt'", ")", ":", "# Read control points", "ctrlpts2d", ",", "size_u", ",", "size_v", "=", "_read_ctrltps2d_file", "(", "file_in", ")", "# Multiply control points by weight", "new_ctrlpts2d", "=", "generate_ctrlptsw2d", "(", "ctrlpts2d", ")", "# Save new control points", "_save_ctrlpts2d_file", "(", "new_ctrlpts2d", ",", "size_u", ",", "size_v", ",", "file_out", ")" ]
Return a displayable name for the type .
def _get_type_name ( type_ ) : # type: (type) -> str name = repr ( type_ ) if name . startswith ( "<" ) : name = getattr ( type_ , "__qualname__" , getattr ( type_ , "__name__" , "" ) ) return name . rsplit ( "." , 1 ) [ - 1 ] or repr ( type_ )
8,037
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/objects.py#L46-L60
[ "def", "delete_subscription", "(", "self", ",", "subscription_id", ",", "client_id", ",", "client_secret", ")", ":", "self", ".", "protocol", ".", "delete", "(", "'/push_subscriptions/{id}'", ",", "id", "=", "subscription_id", ",", "client_id", "=", "client_id", ",", "client_secret", "=", "client_secret", ",", "use_webhook_server", "=", "True", ")" ]
Return the source code for a class by checking the frame stack .
def _get_class_frame_source ( class_name ) : # type: (str) -> Optional[str] for frame_info in inspect . stack ( ) : try : with open ( frame_info [ 1 ] ) as fp : src = "" . join ( fp . readlines ( ) [ frame_info [ 2 ] - 1 : ] ) except IOError : continue if re . search ( r"\bclass\b\s+\b{}\b" . format ( class_name ) , src ) : reader = six . StringIO ( src ) . readline tokens = tokenize . generate_tokens ( reader ) source_tokens = [ ] indent_level = 0 base_indent_level = 0 has_base_level = False for token , value , _ , _ , _ in tokens : # type: ignore source_tokens . append ( ( token , value ) ) if token == tokenize . INDENT : indent_level += 1 elif token == tokenize . DEDENT : indent_level -= 1 if has_base_level and indent_level <= base_indent_level : return ( tokenize . untokenize ( source_tokens ) , frame_info [ 0 ] . f_globals , frame_info [ 0 ] . f_locals , ) elif not has_base_level : has_base_level = True base_indent_level = indent_level raise TypeError ( 'Unable to retrieve source for class "{}"' . format ( class_name ) )
8,038
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/objects.py#L63-L107
[ "def", "percent_initiated_conversations", "(", "records", ")", ":", "interactions", "=", "defaultdict", "(", "list", ")", "for", "r", "in", "records", ":", "interactions", "[", "r", ".", "correspondent_id", "]", ".", "append", "(", "r", ")", "def", "_percent_initiated", "(", "grouped", ")", ":", "mapped", "=", "[", "(", "1", "if", "conv", "[", "0", "]", ".", "direction", "==", "'out'", "else", "0", ",", "1", ")", "for", "conv", "in", "_conversations", "(", "grouped", ")", "]", "return", "mapped", "all_couples", "=", "[", "sublist", "for", "i", "in", "interactions", ".", "values", "(", ")", "for", "sublist", "in", "_percent_initiated", "(", "i", ")", "]", "if", "len", "(", "all_couples", ")", "==", "0", ":", "init", ",", "total", "=", "0", ",", "0", "else", ":", "init", ",", "total", "=", "list", "(", "map", "(", "sum", ",", "list", "(", "zip", "(", "*", "all_couples", ")", ")", ")", ")", "return", "init", "/", "total", "if", "total", "!=", "0", "else", "0" ]
Determine if an attribute can be replaced with a property .
def _is_propertyable ( names , # type: List[str] attrs , # type: Dict[str, Any] annotations , # type: Dict[str, type] attr , # Dict[str, Any] ) : # type: (...) -> bool return ( attr in annotations and not attr . startswith ( "_" ) and not attr . isupper ( ) and "__{}" . format ( attr ) not in names and not isinstance ( getattr ( attrs , attr , None ) , types . MethodType ) )
8,039
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/objects.py#L110-L134
[ "def", "parse_journal", "(", "journal", ")", ":", "events", "=", "[", "e", "for", "e", "in", "journal", "if", "not", "isinstance", "(", "e", ",", "CorruptedUsnRecord", ")", "]", "keyfunc", "=", "lambda", "e", ":", "str", "(", "e", ".", "file_reference_number", ")", "+", "e", ".", "file_name", "+", "e", ".", "timestamp", "event_groups", "=", "(", "tuple", "(", "g", ")", "for", "k", ",", "g", "in", "groupby", "(", "events", ",", "key", "=", "keyfunc", ")", ")", "if", "len", "(", "events", ")", "<", "len", "(", "list", "(", "journal", ")", ")", ":", "LOGGER", ".", "debug", "(", "\"Corrupted records in UsnJrnl, some events might be missing.\"", ")", "return", "[", "journal_event", "(", "g", ")", "for", "g", "in", "event_groups", "]" ]
Create a metaclass for typed objects .
def _create_typed_object_meta ( get_fset ) : # type: (Callable[[str, str, Type[_T]], Callable[[_T], None]]) -> type def _get_fget ( attr , private_attr , type_ ) : # type: (str, str, Type[_T]) -> Callable[[], Any] """Create a property getter method for an attribute. Args: attr: The name of the attribute that will be retrieved. private_attr: The name of the attribute that will store any data related to the attribute. type_: The annotated type defining what values can be stored in the attribute. Returns: A function that takes self and retrieves the private attribute from self. """ def _fget ( self ) : # type: (...) -> Any """Get attribute from self without revealing the private name.""" try : return getattr ( self , private_attr ) except AttributeError : raise AttributeError ( "'{}' object has no attribute '{}'" . format ( _get_type_name ( type_ ) , attr ) ) return _fget class _AnnotatedObjectMeta ( type ) : """A metaclass that reads annotations from a class definition.""" def __new__ ( mcs , # type: Type[_AnnotatedObjectMeta] name , # type: str bases , # type: List[type] attrs , # type: Dict[str, Any] * * kwargs # type: Dict[str, Any] ) : # type: (...) -> type """Create class objs that replaces annotated attrs with properties. Args: mcs: The class object being created. name: The name of the class to create. bases: The list of all base classes for the new class. attrs: The list of all attributes for the new class from the definition. Returns: A new class instance with the expected base classes and attributes, but with annotated, public, non-constant, non-method attributes replaced by property objects that validate against the annotated type. """ annotations = attrs . get ( "__annotations__" , { } ) use_comment_type_hints = ( not annotations and attrs . get ( "__module__" ) != __name__ ) if use_comment_type_hints : frame_source = _get_class_frame_source ( name ) annotations = get_type_hints ( * frame_source ) names = list ( attrs ) + list ( annotations ) typed_attrs = { } for attr in names : typed_attrs [ attr ] = attrs . get ( attr ) if _is_propertyable ( names , attrs , annotations , attr ) : private_attr = "__{}" . format ( attr ) if attr in attrs : typed_attrs [ private_attr ] = attrs [ attr ] type_ = ( Optional [ annotations [ attr ] ] if not use_comment_type_hints and attr in attrs and attrs [ attr ] is None else annotations [ attr ] ) typed_attrs [ attr ] = property ( _get_fget ( attr , private_attr , type_ ) , get_fset ( attr , private_attr , type_ ) , ) properties = [ attr for attr in annotations if _is_propertyable ( names , attrs , annotations , attr ) ] typed_attrs [ "_tp__typed_properties" ] = properties typed_attrs [ "_tp__required_typed_properties" ] = [ attr for attr in properties if ( attr not in attrs or attrs [ attr ] is None and use_comment_type_hints ) and NoneType not in getattr ( annotations [ attr ] , "__args__" , ( ) ) ] return super ( _AnnotatedObjectMeta , mcs ) . __new__ ( # type: ignore mcs , name , bases , typed_attrs , * * kwargs ) return _AnnotatedObjectMeta
8,040
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/objects.py#L137-L256
[ "def", "on_exit", "(", "self", ")", ":", "answer", "=", "messagebox", ".", "askyesnocancel", "(", "\"Exit\"", ",", "\"Do you want to save as you quit the application?\"", ")", "if", "answer", ":", "self", ".", "save", "(", ")", "self", ".", "quit", "(", ")", "self", ".", "destroy", "(", ")", "elif", "answer", "is", "None", ":", "pass", "# the cancel action", "else", ":", "self", ".", "quit", "(", ")", "self", ".", "destroy", "(", ")" ]
Return a tuple of typed attrs that can be used for comparisons .
def _tp__get_typed_properties ( self ) : try : return tuple ( getattr ( self , p ) for p in self . _tp__typed_properties ) except AttributeError : raise NotImplementedError
8,041
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/objects.py#L398-L408
[ "def", "_post_tags", "(", "self", ",", "fileobj", ")", ":", "page", "=", "OggPage", ".", "find_last", "(", "fileobj", ",", "self", ".", "serial", ",", "finishing", "=", "True", ")", "if", "page", "is", "None", ":", "raise", "OggVorbisHeaderError", "self", ".", "length", "=", "page", ".", "position", "/", "float", "(", "self", ".", "sample_rate", ")" ]
Run a web application .
def run ( cls , routes , * args , * * kwargs ) : # pragma: no cover app = init ( cls , routes , * args , * * kwargs ) HOST = os . getenv ( 'HOST' , '0.0.0.0' ) PORT = int ( os . getenv ( 'PORT' , 8000 ) ) aiohttp . web . run_app ( app , port = PORT , host = HOST )
8,042
https://github.com/dmonroy/chilero/blob/8f1118a60cb7eab3f9ad31cb8a14b30bc102893d/chilero/web/__init__.py#L25-L41
[ "def", "with_timestamps", "(", "self", ",", "created_at", "=", "None", ",", "updated_at", "=", "None", ")", ":", "if", "not", "created_at", ":", "created_at", "=", "self", ".", "created_at", "(", ")", "if", "not", "updated_at", ":", "updated_at", "=", "self", ".", "updated_at", "(", ")", "return", "self", ".", "with_pivot", "(", "created_at", ",", "updated_at", ")" ]
Add a vector to entomology section . vector is either ElementTree or xml snippet
def add ( self , vector , InterventionAnophelesParams = None ) : # TODO # 1. If there are GVI interventions, for every GVI, add anophelesParams section. # (gvi_anophelesParams field in AnophelesSnippets models) # 2. If there are ITN interventions, for every ITN, add anophelesParams section # (itn_anophelesParams field in AnophelesSnippets models) # 3. If there are IRS interventions, for every IRS section add anophelesParams section # (irs_anophelesParams field in AnophelesSnippets models) assert isinstance ( vector , six . string_types ) et = ElementTree . fromstring ( vector ) # check if it is valid vector mosquito = Vector ( et ) assert isinstance ( mosquito . mosquito , str ) assert isinstance ( mosquito . propInfected , float ) assert len ( mosquito . seasonality . monthlyValues ) == 12 index = len ( self . et . findall ( "anopheles" ) ) self . et . insert ( index , et )
8,043
https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/scenario/entomology.py#L197-L222
[ "def", "_get_billing_cycle_number", "(", "self", ",", "billing_cycle", ")", ":", "begins_before_initial_date", "=", "billing_cycle", ".", "date_range", ".", "lower", "<", "self", ".", "initial_billing_cycle", ".", "date_range", ".", "lower", "if", "begins_before_initial_date", ":", "raise", "ProvidedBillingCycleBeginsBeforeInitialBillingCycle", "(", "'{} precedes initial cycle {}'", ".", "format", "(", "billing_cycle", ",", "self", ".", "initial_billing_cycle", ")", ")", "billing_cycle_number", "=", "BillingCycle", ".", "objects", ".", "filter", "(", "date_range__contained_by", "=", "DateRange", "(", "self", ".", "initial_billing_cycle", ".", "date_range", ".", "lower", ",", "billing_cycle", ".", "date_range", ".", "upper", ",", "bounds", "=", "'[]'", ",", ")", ",", ")", ".", "count", "(", ")", "return", "billing_cycle_number" ]
r Format exception message .
def _format_msg ( text , width , indent = 0 , prefix = "" ) : text = repr ( text ) . replace ( "`" , "\\`" ) . replace ( "\\n" , " ``\\n`` " ) sindent = " " * indent if not prefix else prefix wrapped_text = textwrap . wrap ( text , width , subsequent_indent = sindent ) # [1:-1] eliminates quotes generated by repr in first line return ( "\n" . join ( wrapped_text ) ) [ 1 : - 1 ] . rstrip ( )
8,044
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L44-L55
[ "def", "gfposc", "(", "target", ",", "inframe", ",", "abcorr", ",", "obsrvr", ",", "crdsys", ",", "coord", ",", "relate", ",", "refval", ",", "adjust", ",", "step", ",", "nintvals", ",", "cnfine", ",", "result", "=", "None", ")", ":", "assert", "isinstance", "(", "cnfine", ",", "stypes", ".", "SpiceCell", ")", "assert", "cnfine", ".", "is_double", "(", ")", "if", "result", "is", "None", ":", "result", "=", "stypes", ".", "SPICEDOUBLE_CELL", "(", "2000", ")", "else", ":", "assert", "isinstance", "(", "result", ",", "stypes", ".", "SpiceCell", ")", "assert", "result", ".", "is_double", "(", ")", "target", "=", "stypes", ".", "stringToCharP", "(", "target", ")", "inframe", "=", "stypes", ".", "stringToCharP", "(", "inframe", ")", "abcorr", "=", "stypes", ".", "stringToCharP", "(", "abcorr", ")", "obsrvr", "=", "stypes", ".", "stringToCharP", "(", "obsrvr", ")", "crdsys", "=", "stypes", ".", "stringToCharP", "(", "crdsys", ")", "coord", "=", "stypes", ".", "stringToCharP", "(", "coord", ")", "relate", "=", "stypes", ".", "stringToCharP", "(", "relate", ")", "refval", "=", "ctypes", ".", "c_double", "(", "refval", ")", "adjust", "=", "ctypes", ".", "c_double", "(", "adjust", ")", "step", "=", "ctypes", ".", "c_double", "(", "step", ")", "nintvals", "=", "ctypes", ".", "c_int", "(", "nintvals", ")", "libspice", ".", "gfposc_c", "(", "target", ",", "inframe", ",", "abcorr", ",", "obsrvr", ",", "crdsys", ",", "coord", ",", "relate", ",", "refval", ",", "adjust", ",", "step", ",", "nintvals", ",", "ctypes", ".", "byref", "(", "cnfine", ")", ",", "ctypes", ".", "byref", "(", "result", ")", ")", "return", "result" ]
Validate that a string is a valid file name .
def _validate_fname ( fname , arg_name ) : if fname is not None : msg = "Argument `{0}` is not valid" . format ( arg_name ) if ( not isinstance ( fname , str ) ) or ( isinstance ( fname , str ) and ( "\0" in fname ) ) : raise RuntimeError ( msg ) try : if not os . path . exists ( fname ) : os . access ( fname , os . W_OK ) except ( TypeError , ValueError ) : # pragma: no cover raise RuntimeError ( msg )
8,045
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L58-L68
[ "def", "create_or_update", "(", "cls", ",", "bucket", ",", "key", ",", "value", ")", ":", "obj", "=", "cls", ".", "get", "(", "bucket", ",", "key", ")", "if", "obj", ":", "obj", ".", "value", "=", "value", "db", ".", "session", ".", "merge", "(", "obj", ")", "else", ":", "obj", "=", "cls", ".", "create", "(", "bucket", ",", "key", ",", "value", ")", "return", "obj" ]
Construct exception tree from trace .
def _build_ex_tree ( self ) : # Load exception data into tree structure sep = self . _exh_obj . callables_separator data = self . _exh_obj . exceptions_db if not data : raise RuntimeError ( "Exceptions database is empty" ) # Add root node to exceptions, needed when tracing done # through test runner which is excluded from callable path for item in data : item [ "name" ] = "root{sep}{name}" . format ( sep = sep , name = item [ "name" ] ) self . _tobj = ptrie . Trie ( sep ) try : self . _tobj . add_nodes ( data ) except ValueError as eobj : if str ( eobj ) . startswith ( "Illegal node name" ) : raise RuntimeError ( "Exceptions do not have a common callable" ) raise # Find closest root node to first multi-leaf branching or first # callable with exceptions and make that the root node node = self . _tobj . root_name while ( len ( self . _tobj . get_children ( node ) ) == 1 ) and ( not self . _tobj . get_data ( node ) ) : node = self . _tobj . get_children ( node ) [ 0 ] if not self . _tobj . is_root ( node ) : # pragma: no branch self . _tobj . make_root ( node ) nsep = self . _tobj . node_separator prefix = nsep . join ( node . split ( self . _tobj . node_separator ) [ : - 1 ] ) self . _tobj . delete_prefix ( prefix ) self . _print_ex_tree ( )
8,046
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L324-L354
[ "def", "checkIfAvailable", "(", "self", ",", "dateTime", "=", "timezone", ".", "now", "(", ")", ")", ":", "return", "(", "self", ".", "startTime", ">=", "dateTime", "+", "timedelta", "(", "days", "=", "getConstant", "(", "'privateLessons__closeBookingDays'", ")", ")", "and", "self", ".", "startTime", "<=", "dateTime", "+", "timedelta", "(", "days", "=", "getConstant", "(", "'privateLessons__openBookingDays'", ")", ")", "and", "not", "self", ".", "eventRegistration", "and", "(", "self", ".", "status", "==", "self", ".", "SlotStatus", ".", "available", "or", "(", "self", ".", "status", "==", "self", ".", "SlotStatus", ".", "tentative", "and", "getattr", "(", "getattr", "(", "self", ".", "temporaryEventRegistration", ",", "'registration'", ",", "None", ")", ",", "'expirationDate'", ",", "timezone", ".", "now", "(", ")", ")", "<=", "timezone", ".", "now", "(", ")", ")", ")", ")" ]
Build database of module callables sorted by line number .
def _build_module_db ( self ) : tdict = collections . defaultdict ( lambda : [ ] ) for callable_name , callable_dict in self . _exh_obj . callables_db . items ( ) : fname , line_no = callable_dict [ "code_id" ] cname = ( "{cls_name}.__init__" . format ( cls_name = callable_name ) if callable_dict [ "type" ] == "class" else callable_name ) tdict [ fname ] . append ( { "name" : cname , "line" : line_no } ) for fname in tdict . keys ( ) : self . _module_obj_db [ fname ] = sorted ( tdict [ fname ] , key = lambda idict : idict [ "line" ] )
8,047
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L356-L376
[ "def", "DeleteGroupTags", "(", "r", ",", "group", ",", "tags", ",", "dry_run", "=", "False", ")", ":", "query", "=", "{", "\"dry-run\"", ":", "dry_run", ",", "\"tag\"", ":", "tags", ",", "}", "return", "r", ".", "request", "(", "\"delete\"", ",", "\"/2/groups/%s/tags\"", "%", "group", ",", "query", "=", "query", ")" ]
Remove raised info from exception message and create separate list for it .
def _process_exlist ( self , exc , raised ) : if ( not raised ) or ( raised and exc . endswith ( "*" ) ) : return exc [ : - 1 ] if exc . endswith ( "*" ) else exc return None
8,048
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L391-L395
[ "def", "get_best_dataset_key", "(", "key", ",", "choices", ")", ":", "# Choose the wavelength closest to the choice", "if", "key", ".", "wavelength", "is", "not", "None", "and", "choices", ":", "# find the dataset with a central wavelength nearest to the", "# requested wavelength", "nearest_wl", "=", "min", "(", "[", "_wl_dist", "(", "key", ".", "wavelength", ",", "x", ".", "wavelength", ")", "for", "x", "in", "choices", "if", "x", ".", "wavelength", "is", "not", "None", "]", ")", "choices", "=", "[", "c", "for", "c", "in", "choices", "if", "_wl_dist", "(", "key", ".", "wavelength", ",", "c", ".", "wavelength", ")", "==", "nearest_wl", "]", "if", "key", ".", "modifiers", "is", "None", "and", "choices", ":", "num_modifiers", "=", "min", "(", "len", "(", "x", ".", "modifiers", "or", "tuple", "(", ")", ")", "for", "x", "in", "choices", ")", "choices", "=", "[", "c", "for", "c", "in", "choices", "if", "len", "(", "c", ".", "modifiers", "or", "tuple", "(", ")", ")", "==", "num_modifiers", "]", "if", "key", ".", "calibration", "is", "None", "and", "choices", ":", "best_cal", "=", "[", "x", ".", "calibration", "for", "x", "in", "choices", "if", "x", ".", "calibration", "]", "if", "best_cal", ":", "best_cal", "=", "min", "(", "best_cal", ",", "key", "=", "lambda", "x", ":", "CALIBRATION_ORDER", "[", "x", "]", ")", "choices", "=", "[", "c", "for", "c", "in", "choices", "if", "c", ".", "calibration", "==", "best_cal", "]", "if", "key", ".", "resolution", "is", "None", "and", "choices", ":", "low_res", "=", "[", "x", ".", "resolution", "for", "x", "in", "choices", "if", "x", ".", "resolution", "]", "if", "low_res", ":", "low_res", "=", "min", "(", "low_res", ")", "choices", "=", "[", "c", "for", "c", "in", "choices", "if", "c", ".", "resolution", "==", "low_res", "]", "if", "key", ".", "level", "is", "None", "and", "choices", ":", "low_level", "=", "[", "x", ".", "level", "for", "x", "in", "choices", "if", "x", ".", "level", "]", "if", "low_level", ":", "low_level", "=", "max", "(", "low_level", ")", "choices", "=", "[", "c", "for", "c", "in", "choices", "if", "c", ".", "level", "==", "low_level", "]", "return", "choices" ]
Depth setter .
def _set_depth ( self , depth ) : if depth and ( ( not isinstance ( depth , int ) ) or ( isinstance ( depth , int ) and ( depth < 0 ) ) ) : raise RuntimeError ( "Argument `depth` is not valid" ) self . _depth = depth
8,049
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L397-L403
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
Exclude setter .
def _set_exclude ( self , exclude ) : if exclude and ( ( not isinstance ( exclude , list ) ) or ( isinstance ( exclude , list ) and any ( [ not isinstance ( item , str ) for item in exclude ] ) ) ) : raise RuntimeError ( "Argument `exclude` is not valid" ) self . _exclude = exclude
8,050
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L405-L415
[ "def", "_add_dependency", "(", "self", ",", "dependency", ",", "var_name", "=", "None", ")", ":", "if", "var_name", "is", "None", ":", "var_name", "=", "next", "(", "self", ".", "temp_var_names", ")", "# Don't add duplicate dependencies", "if", "(", "dependency", ",", "var_name", ")", "not", "in", "self", ".", "dependencies", ":", "self", ".", "dependencies", ".", "append", "(", "(", "dependency", ",", "var_name", ")", ")", "return", "var_name" ]
r Return exception list in reStructuredText _ auto - determining callable name .
def get_sphinx_autodoc ( self , depth = None , exclude = None , width = 72 , error = False , raised = False , no_comment = False , ) : # This code is cog-specific: cog code file name is the module # file name, a plus (+), and then the line number where the # cog function is frame = sys . _getframe ( 1 ) index = frame . f_code . co_filename . rfind ( "+" ) fname = os . path . abspath ( frame . f_code . co_filename [ : index ] ) # Find name of callable based on module name and line number # within that module, then get the exceptions by using the # get_sphinx_doc() method with this information line_num = int ( frame . f_code . co_filename [ index + 1 : ] ) module_db = self . _module_obj_db [ fname ] names = [ callable_dict [ "name" ] for callable_dict in module_db ] line_nums = [ callable_dict [ "line" ] for callable_dict in module_db ] name = names [ bisect . bisect ( line_nums , line_num ) - 1 ] return self . get_sphinx_doc ( name = name , depth = depth , exclude = exclude , width = width , error = error , raised = raised , no_comment = no_comment , )
8,051
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exdoc.py#L417-L503
[ "def", "set_option", "(", "self", ",", "key", ",", "value", ")", ":", "akey", "=", "AVal", "(", "key", ")", "aval", "=", "AVal", "(", "value", ")", "res", "=", "librtmp", ".", "RTMP_SetOpt", "(", "self", ".", "rtmp", ",", "akey", ".", "aval", ",", "aval", ".", "aval", ")", "if", "res", "<", "1", ":", "raise", "ValueError", "(", "\"Unable to set option {0}\"", ".", "format", "(", "key", ")", ")", "self", ".", "_options", "[", "akey", "]", "=", "aval" ]
Grow this array to specified length . This array can t be shrinked
def resize ( self , size ) : if size < len ( self ) : raise ValueError ( "Value is out of bound. Array can't be shrinked" ) current_size = self . __size for i in range ( size - current_size ) : self . __array . append ( WBinArray ( 0 , self . __class__ . byte_size ) ) self . __size = size
8,052
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/types/bytearray.py#L83-L94
[ "def", "_display_status", "(", "normalized_data", ",", "stream", ")", ":", "if", "'Pull complete'", "in", "normalized_data", "[", "'status'", "]", "or", "'Download complete'", "in", "normalized_data", "[", "'status'", "]", ":", "stream", ".", "write", "(", "\"\\n\"", ")", "if", "'id'", "in", "normalized_data", ":", "stream", ".", "write", "(", "\"%s - \"", "%", "normalized_data", "[", "'id'", "]", ")", "stream", ".", "write", "(", "\"{0}\\n\"", ".", "format", "(", "normalized_data", "[", "'status'", "]", ")", ")" ]
Mirror current array value in reverse . Bytes that had greater index will have lesser index and vice - versa . This method doesn t change this array . It creates a new one and return it as a result .
def swipe ( self ) : result = WFixedSizeByteArray ( len ( self ) ) for i in range ( len ( self ) ) : result [ len ( self ) - i - 1 ] = self [ i ] return result
8,053
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/types/bytearray.py#L140-L149
[ "def", "_pvalues_all", "(", "self", ")", ":", "return", "2.0", "*", "(", "1.0", "-", "scs", ".", "t", ".", "cdf", "(", "np", ".", "abs", "(", "self", ".", "_tstat_all", ")", ",", "self", ".", "df_err", ")", ")" ]
Guess mime type for the given file name
def mime_type ( filename ) : # TODO: write lock-free mime_type function try : __mime_lock . acquire ( ) extension = filename . split ( "." ) extension = extension [ len ( extension ) - 1 ] if extension == "woff2" : return "application/font-woff2" if extension == "css" : return "text/css" m = magic . from_file ( filename , mime = True ) m = m . decode ( ) if isinstance ( m , bytes ) else m # compatibility fix, some versions return bytes some - str if m == "text/plain" : guessed_type = mimetypes . guess_type ( filename ) [ 0 ] # for js-detection if guessed_type : return guessed_type return m finally : __mime_lock . release ( )
8,054
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/mime.py#L36-L65
[ "def", "reset_subscriptions", "(", "self", ",", "accounts", "=", "[", "]", ",", "markets", "=", "[", "]", ",", "objects", "=", "[", "]", ")", ":", "self", ".", "websocket", ".", "reset_subscriptions", "(", "accounts", ",", "self", ".", "get_market_ids", "(", "markets", ")", ",", "objects", ")" ]
Validate the item against allowed_types .
def _validate_type ( self , item , name ) : if item is None : # don't validate None items, since they'll be caught by the portion # of the validator responsible for handling `required`ness return if not isinstance ( item , self . allowed_types ) : item_class_name = item . __class__ . __name__ raise ArgumentError ( name , "Expected one of %s, but got `%s`" % ( self . allowed_types , item_class_name ) )
8,055
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/arguments/base.py#L59-L70
[ "def", "_restart_session", "(", "self", ",", "session", ")", ":", "# remove old session key, if socket is None, that means the", "# session was closed by user and there is no need to restart.", "if", "session", ".", "socket", "is", "not", "None", ":", "self", ".", "log", ".", "info", "(", "\"Attempting restart session for Monitor Id %s.\"", "%", "session", ".", "monitor_id", ")", "del", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "session", ".", "stop", "(", ")", "session", ".", "start", "(", ")", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "=", "session" ]
Validate that the item is present if it s required .
def _validate_required ( self , item , name ) : if self . required is True and item is None : raise ArgumentError ( name , "This argument is required." )
8,056
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/arguments/base.py#L73-L76
[ "def", "detach_from_all", "(", "self", ",", "bIgnoreExceptions", "=", "False", ")", ":", "for", "pid", "in", "self", ".", "get_debugee_pids", "(", ")", ":", "self", ".", "detach", "(", "pid", ",", "bIgnoreExceptions", "=", "bIgnoreExceptions", ")" ]
Returns the documentation dictionary for this argument .
def doc_dict ( self ) : doc = { 'type' : self . __class__ . __name__ , 'description' : self . description , 'default' : self . default , 'required' : self . required } if hasattr ( self , 'details' ) : doc [ 'detailed_description' ] = self . details return doc
8,057
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/arguments/base.py#L79-L89
[ "def", "_getNearestMappingIndexList", "(", "fromValList", ",", "toValList", ")", ":", "indexList", "=", "[", "]", "for", "fromTimestamp", "in", "fromValList", ":", "smallestDiff", "=", "_getSmallestDifference", "(", "toValList", ",", "fromTimestamp", ")", "i", "=", "toValList", ".", "index", "(", "smallestDiff", ")", "indexList", ".", "append", "(", "i", ")", "return", "indexList" ]
Validates that items in the list are of the type specified .
def validate_items ( self , input_list ) : output_list = [ ] for item in input_list : valid = self . list_item_type . validate ( item , self . item_name ) output_list . append ( valid ) # this might lead to confusing error messages. tbh, we need to # figure out a better way to do validation and error handling here, # but i'm brute forcing this a bit so that we have something # workable return output_list
8,058
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/arguments/base.py#L114-L128
[ "def", "strip_wsgi", "(", "request", ")", ":", "meta", "=", "copy", "(", "request", ".", "META", ")", "for", "key", "in", "meta", ":", "if", "key", "[", ":", "4", "]", "==", "'wsgi'", ":", "meta", "[", "key", "]", "=", "None", "return", "meta" ]
Start json - rpc service .
def startserver ( self , hostname = "localhost" , port = 8080 , daemon = False , handle_sigint = True ) : if daemon : print ( "Sorry daemon server not supported just yet." ) # TODO start as daemon similar to bitcoind else : print ( "Starting %s json-rpc service at http://%s:%s" % ( self . __class__ . __name__ , hostname , port ) ) self . _http_server = HTTPServer ( server_address = ( hostname , int ( port ) ) , RequestHandlerClass = self . get_http_request_handler ( ) ) if handle_sigint : def sigint_handler ( signum , frame ) : self . _post_shutdown ( ) sys . exit ( 0 ) signal . signal ( signal . SIGINT , sigint_handler ) self . _http_server . serve_forever ( )
8,059
https://github.com/F483/apigen/blob/f05ce1509030764721cc3393410fa12b609e88f2/apigen/apigen.py#L118-L138
[ "def", "mergeDQarray", "(", "maskname", ",", "dqarr", ")", ":", "maskarr", "=", "None", "if", "maskname", "is", "not", "None", ":", "if", "isinstance", "(", "maskname", ",", "str", ")", ":", "# working with file on disk (default case)", "if", "os", ".", "path", ".", "exists", "(", "maskname", ")", ":", "mask", "=", "fileutil", ".", "openImage", "(", "maskname", ",", "memmap", "=", "False", ")", "maskarr", "=", "mask", "[", "0", "]", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", "mask", ".", "close", "(", ")", "else", ":", "if", "isinstance", "(", "maskname", ",", "fits", ".", "HDUList", ")", ":", "# working with a virtual input file", "maskarr", "=", "maskname", "[", "0", "]", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", "else", ":", "maskarr", "=", "maskname", ".", "data", ".", "astype", "(", "np", ".", "bool", ")", "if", "maskarr", "is", "not", "None", ":", "# merge array with dqarr now", "np", ".", "bitwise_and", "(", "dqarr", ",", "maskarr", ",", "dqarr", ")" ]
Find the asymmetry of each helicity .
def _get_asym_hel ( self , d ) : # get data 1+ 2+ 1- 2- d0 = d [ 0 ] d1 = d [ 2 ] d2 = d [ 1 ] d3 = d [ 3 ] # pre-calcs denom1 = d0 + d1 denom2 = d2 + d3 # check for div by zero denom1 [ denom1 == 0 ] = np . nan denom2 [ denom2 == 0 ] = np . nan # asymmetries in both helicities asym_hel = [ ( d0 - d1 ) / denom1 , ( d2 - d3 ) / denom2 ] # errors # https://www.wolframalpha.com/input/?i=%E2%88%9A(F*(derivative+of+((F-B)%2F(F%2BB))+with+respect+to+F)%5E2+%2B+B*(derivative+of+((F-B)%2F(F%2BB))+with+respect+to+B)%5E2) asym_hel_err = [ 2 * np . sqrt ( d0 * d1 / np . power ( denom1 , 3 ) ) , 2 * np . sqrt ( d2 * d3 / np . power ( denom2 , 3 ) ) ] # remove nan for i in range ( 2 ) : asym_hel [ i ] [ np . isnan ( asym_hel [ i ] ) ] = 0. asym_hel_err [ i ] [ np . isnan ( asym_hel_err [ i ] ) ] = 0. # exit return [ [ asym_hel [ 1 ] , asym_hel_err [ 1 ] ] , # something wrong with file? [ asym_hel [ 0 ] , asym_hel_err [ 0 ] ] ]
8,060
https://github.com/dfujim/bdata/blob/86af7b091e5cc167d2b9a3146953da347cc38614/bdata/bdata.py#L545-L577
[ "def", "_preprocess_movie_lens", "(", "ratings_df", ")", ":", "ratings_df", "[", "\"data\"", "]", "=", "1.0", "num_timestamps", "=", "ratings_df", "[", "[", "\"userId\"", ",", "\"timestamp\"", "]", "]", ".", "groupby", "(", "\"userId\"", ")", ".", "nunique", "(", ")", "last_user_timestamp", "=", "ratings_df", "[", "[", "\"userId\"", ",", "\"timestamp\"", "]", "]", ".", "groupby", "(", "\"userId\"", ")", ".", "max", "(", ")", "ratings_df", "[", "\"numberOfTimestamps\"", "]", "=", "ratings_df", "[", "\"userId\"", "]", ".", "apply", "(", "lambda", "x", ":", "num_timestamps", "[", "\"timestamp\"", "]", "[", "x", "]", ")", "ratings_df", "[", "\"lastTimestamp\"", "]", "=", "ratings_df", "[", "\"userId\"", "]", ".", "apply", "(", "lambda", "x", ":", "last_user_timestamp", "[", "\"timestamp\"", "]", "[", "x", "]", ")", "ratings_df", "=", "ratings_df", "[", "ratings_df", "[", "\"numberOfTimestamps\"", "]", ">", "2", "]", "ratings_df", "=", "_create_row_col_indices", "(", "ratings_df", ")", "train_ratings_df", "=", "ratings_df", "[", "ratings_df", "[", "\"timestamp\"", "]", "<", "ratings_df", "[", "\"lastTimestamp\"", "]", "]", "test_ratings_df", "=", "ratings_df", "[", "ratings_df", "[", "\"timestamp\"", "]", "==", "ratings_df", "[", "\"lastTimestamp\"", "]", "]", "return", "ratings_df", ",", "train_ratings_df", ",", "test_ratings_df" ]
Find the combined asymmetry for slr runs . Elegant 4 - counter method .
def _get_asym_comb ( self , d ) : # get data d0 = d [ 0 ] d1 = d [ 2 ] d2 = d [ 1 ] d3 = d [ 3 ] # pre-calcs r_denom = d0 * d3 r_denom [ r_denom == 0 ] = np . nan r = np . sqrt ( ( d1 * d2 / r_denom ) ) r [ r == - 1 ] = np . nan # combined asymmetry asym_comb = ( r - 1 ) / ( r + 1 ) # check for div by zero d0 [ d0 == 0 ] = np . nan d1 [ d1 == 0 ] = np . nan d2 [ d2 == 0 ] = np . nan d3 [ d3 == 0 ] = np . nan # error in combined asymmetry asym_comb_err = r * np . sqrt ( 1 / d1 + 1 / d0 + 1 / d3 + 1 / d2 ) / np . square ( r + 1 ) # replace nan with zero asym_comb [ np . isnan ( asym_comb ) ] = 0. asym_comb_err [ np . isnan ( asym_comb_err ) ] = 0. return [ asym_comb , asym_comb_err ]
8,061
https://github.com/dfujim/bdata/blob/86af7b091e5cc167d2b9a3146953da347cc38614/bdata/bdata.py#L580-L610
[ "def", "parse_registries", "(", "filesystem", ",", "registries", ")", ":", "results", "=", "{", "}", "for", "path", "in", "registries", ":", "with", "NamedTemporaryFile", "(", "buffering", "=", "0", ")", "as", "tempfile", ":", "filesystem", ".", "download", "(", "path", ",", "tempfile", ".", "name", ")", "registry", "=", "RegistryHive", "(", "tempfile", ".", "name", ")", "registry", ".", "rootkey", "=", "registry_root", "(", "path", ")", "results", ".", "update", "(", "{", "k", ".", "path", ":", "(", "k", ".", "timestamp", ",", "k", ".", "values", ")", "for", "k", "in", "registry", ".", "keys", "(", ")", "}", ")", "return", "results" ]
Sum counts in each frequency bin over 1f scans .
def _get_1f_sum_scans ( self , d , freq ) : # combine scans: values with same frequency unique_freq = np . unique ( freq ) sum_scans = [ [ ] for i in range ( len ( d ) ) ] for f in unique_freq : tag = freq == f for i in range ( len ( d ) ) : sum_scans [ i ] . append ( np . sum ( d [ i ] [ tag ] ) ) return ( np . array ( unique_freq ) , np . array ( sum_scans ) )
8,062
https://github.com/dfujim/bdata/blob/86af7b091e5cc167d2b9a3146953da347cc38614/bdata/bdata.py#L672-L687
[ "def", "_create_download_failed_message", "(", "exception", ",", "url", ")", ":", "message", "=", "'Failed to download from:\\n{}\\nwith {}:\\n{}'", ".", "format", "(", "url", ",", "exception", ".", "__class__", ".", "__name__", ",", "exception", ")", "if", "_is_temporal_problem", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "requests", ".", "ConnectionError", ")", ":", "message", "+=", "'\\nPlease check your internet connection and try again.'", "else", ":", "message", "+=", "'\\nThere might be a problem in connection or the server failed to process '", "'your request. Please try again.'", "elif", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", ":", "try", ":", "server_message", "=", "''", "for", "elem", "in", "decode_data", "(", "exception", ".", "response", ".", "content", ",", "MimeType", ".", "XML", ")", ":", "if", "'ServiceException'", "in", "elem", ".", "tag", "or", "'Message'", "in", "elem", ".", "tag", ":", "server_message", "+=", "elem", ".", "text", ".", "strip", "(", "'\\n\\t '", ")", "except", "ElementTree", ".", "ParseError", ":", "server_message", "=", "exception", ".", "response", ".", "text", "message", "+=", "'\\nServer response: \"{}\"'", ".", "format", "(", "server_message", ")", "return", "message" ]
Get pulse duration in seconds for pulsed measurements .
def get_pulse_s ( self ) : try : dwelltime = self . ppg . dwelltime . mean beam_on = self . ppg . beam_on . mean except AttributeError : raise AttributeError ( "Missing logged ppg parameter: dwelltime " + "or beam_on" ) return dwelltime * beam_on / 1000.
8,063
https://github.com/dfujim/bdata/blob/86af7b091e5cc167d2b9a3146953da347cc38614/bdata/bdata.py#L1334-L1343
[ "def", "remove_thumbnail", "(", "self", ",", "thumbnail", ")", ":", "if", "thumbnail", "in", "self", ".", "_thumbnails", ":", "index", "=", "self", ".", "_thumbnails", ".", "index", "(", "thumbnail", ")", "self", ".", "_thumbnails", ".", "remove", "(", "thumbnail", ")", "self", ".", "layout", "(", ")", ".", "removeWidget", "(", "thumbnail", ")", "thumbnail", ".", "deleteLater", "(", ")", "thumbnail", ".", "sig_canvas_clicked", ".", "disconnect", "(", ")", "thumbnail", ".", "sig_remove_figure", ".", "disconnect", "(", ")", "thumbnail", ".", "sig_save_figure", ".", "disconnect", "(", ")", "# Select a new thumbnail if any :", "if", "thumbnail", "==", "self", ".", "current_thumbnail", ":", "if", "len", "(", "self", ".", "_thumbnails", ")", ">", "0", ":", "self", ".", "set_current_index", "(", "min", "(", "index", ",", "len", "(", "self", ".", "_thumbnails", ")", "-", "1", ")", ")", "else", ":", "self", ".", "current_thumbnail", "=", "None", "self", ".", "figure_viewer", ".", "figcanvas", ".", "clear_canvas", "(", ")" ]
Return the endpoints from an API implementation module .
def extract_endpoints ( api_module ) : if not hasattr ( api_module , 'endpoints' ) : raise ValueError ( ( "pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!" ) ) endpoints = api_module . endpoints if isinstance ( endpoints , types . ModuleType ) : classes = [ v for ( k , v ) in inspect . getmembers ( endpoints , inspect . isclass ) ] elif isinstance ( endpoints , ( list , tuple ) ) : classes = endpoints else : raise ValueError ( "Endpoints is not a module or list type!" ) instances = [ ] for cls in classes : if cls not in ( Endpoint , PatchEndpoint , PutResourceEndpoint ) and Endpoint in inspect . getmro ( cls ) : source_code = inspect . getsource ( cls ) if "@requires_permission" in source_code : permission_match = re . search ( r"@requires_permission\(\[?[\'\"]+(\w+)[\'\"]+" , source_code ) if permission_match != None : cls . _requires_permission = permission_match . group ( 1 ) instances . append ( cls ( ) ) return instances
8,064
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/__init__.py#L44-L74
[ "def", "crc", "(", "self", ")", ":", "# will make sure everything has been transferred", "# to datastore that needs to be before returning crc", "result", "=", "self", ".", "_data", ".", "fast_hash", "(", ")", "if", "hasattr", "(", "self", ".", "mesh", ",", "'crc'", ")", ":", "# bitwise xor combines hashes better than a sum", "result", "^=", "self", ".", "mesh", ".", "crc", "(", ")", "return", "result" ]
Return the resources from an API implementation module .
def extract_resources ( api_module ) : endpoints = extract_endpoints ( api_module ) resource_classes = [ e . _returns . __class__ for e in endpoints ] return list ( set ( resource_classes ) )
8,065
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/__init__.py#L76-L85
[ "def", "_read_console_output", "(", "self", ",", "ws", ",", "out", ")", ":", "while", "True", ":", "msg", "=", "yield", "from", "ws", ".", "receive", "(", ")", "if", "msg", ".", "tp", "==", "aiohttp", ".", "WSMsgType", ".", "text", ":", "out", ".", "feed_data", "(", "msg", ".", "data", ".", "encode", "(", ")", ")", "elif", "msg", ".", "tp", "==", "aiohttp", ".", "WSMsgType", ".", "BINARY", ":", "out", ".", "feed_data", "(", "msg", ".", "data", ")", "elif", "msg", ".", "tp", "==", "aiohttp", ".", "WSMsgType", ".", "ERROR", ":", "log", ".", "critical", "(", "\"Docker WebSocket Error: {}\"", ".", "format", "(", "msg", ".", "data", ")", ")", "else", ":", "out", ".", "feed_eof", "(", ")", "ws", ".", "close", "(", ")", "break", "yield", "from", "self", ".", "stop", "(", ")" ]
Template loader that loads templates from zipped modules .
def load_template_source ( self , template_name , template_dirs = None ) : #Get every app's folder log . error ( "Calling zip loader" ) for folder in app_template_dirs : if ".zip/" in folder . replace ( "\\" , "/" ) : lib_file , relative_folder = get_zip_file_and_relative_path ( folder ) log . error ( lib_file , relative_folder ) try : z = zipfile . ZipFile ( lib_file ) log . error ( relative_folder + template_name ) template_path_in_zip = os . path . join ( relative_folder , template_name ) . replace ( "\\" , "/" ) source = z . read ( template_path_in_zip ) except ( IOError , KeyError ) as e : import traceback log . error ( traceback . format_exc ( ) ) try : z . close ( ) except : pass continue z . close ( ) # We found a template, so return the source. template_path = "%s:%s" % ( lib_file , template_path_in_zip ) return ( source , template_path ) # If we reach here, the template couldn't be loaded raise TemplateDoesNotExist ( template_name )
8,066
https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/django_adv_zip_template_loader.py#L44-L71
[ "def", "v6_nd_suppress_ra", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "str", "(", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", ")", "name", "=", "str", "(", "kwargs", ".", "pop", "(", "'name'", ")", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "int_types", "=", "[", "'gigabitethernet'", ",", "'tengigabitethernet'", ",", "'fortygigabitethernet'", ",", "'hundredgigabitethernet'", ",", "'ve'", "]", "if", "int_type", "not", "in", "int_types", ":", "raise", "ValueError", "(", "\"`int_type` must be one of: %s\"", "%", "repr", "(", "int_types", ")", ")", "if", "int_type", "==", "\"ve\"", ":", "if", "not", "pynos", ".", "utilities", ".", "valid_vlan_id", "(", "name", ")", ":", "raise", "ValueError", "(", "\"`name` must be between `1` and `8191`\"", ")", "rbridge_id", "=", "kwargs", ".", "pop", "(", "'rbridge_id'", ",", "\"1\"", ")", "nd_suppress_args", "=", "dict", "(", "name", "=", "name", ",", "rbridge_id", "=", "rbridge_id", ")", "nd_suppress", "=", "getattr", "(", "self", ".", "_rbridge", ",", "'rbridge_id_interface_ve_ipv6_'", "'ipv6_nd_ra_ipv6_intf_cmds_'", "'nd_suppress_ra_suppress_ra_all'", ")", "config", "=", "nd_suppress", "(", "*", "*", "nd_suppress_args", ")", "else", ":", "if", "not", "pynos", ".", "utilities", ".", "valid_interface", "(", "int_type", ",", "name", ")", ":", "raise", "ValueError", "(", "\"`name` must match \"", "\"`^[0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3}$`\"", ")", "nd_suppress_args", "=", "dict", "(", "name", "=", "name", ")", "nd_suppress", "=", "getattr", "(", "self", ".", "_interface", ",", "'interface_%s_ipv6_ipv6_nd_ra_'", "'ipv6_intf_cmds_nd_suppress_ra_'", "'suppress_ra_all'", "%", "int_type", ")", "config", "=", "nd_suppress", "(", "*", "*", "nd_suppress_args", ")", "return", "callback", "(", "config", ")" ]
Fetch log records and return them as a list .
def fetch ( self , start = None , stop = None ) : # Set defaults if no explicit indices were provided. if not start : start = 0 if not stop : stop = len ( self . log ) # Sanity check: indices must be valid. if start < 0 : start = 0 if stop > len ( self . log ) : stop = len ( self . log ) # Clear the fetch flag. It will be set again in the emit() # method once new data arrives. self . waitForFetch = False # Return the specified range of log records. return self . log [ start : stop ]
8,067
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/logging_handler.py#L127-L165
[ "def", "cublasSgbmv", "(", "handle", ",", "trans", ",", "m", ",", "n", ",", "kl", ",", "ku", ",", "alpha", ",", "A", ",", "lda", ",", "x", ",", "incx", ",", "beta", ",", "y", ",", "incy", ")", ":", "status", "=", "_libcublas", ".", "cublasSgbmv_v2", "(", "handle", ",", "trans", ",", "m", ",", "n", ",", "kl", ",", "ku", ",", "ctypes", ".", "byref", "(", "ctypes", ".", "c_float", "(", "alpha", ")", ")", ",", "int", "(", "A", ")", ",", "lda", ",", "int", "(", "x", ")", ",", "incx", ",", "ctypes", ".", "byref", "(", "ctypes", ".", "c_float", "(", "beta", ")", ")", ",", "int", "(", "y", ")", ",", "incy", ")", "cublasCheckStatus", "(", "status", ")" ]
Binds an implemented pale API module to a Flask Blueprint .
def bind_blueprint ( pale_api_module , flask_blueprint ) : if not isinstance ( flask_blueprint , Blueprint ) : raise TypeError ( ( "pale.flask_adapter.bind_blueprint expected the " "passed in flask_blueprint to be an instance of " "Blueprint, but it was an instance of %s instead." ) % ( type ( flask_blueprint ) , ) ) if not pale . is_pale_module ( pale_api_module ) : raise TypeError ( ( "pale.flask_adapter.bind_blueprint expected the " "passed in pale_api_module to be a module, and to " "have a _module_type defined to equal " "pale.ImplementationModule, but it was an instance of " "%s instead." ) % ( type ( pale_api_module ) , ) ) endpoints = pale . extract_endpoints ( pale_api_module ) for endpoint in endpoints : endpoint . _set_response_class ( RESPONSE_CLASS ) method = [ endpoint . _http_method ] name = endpoint . _route_name handler = endpoint . _execute flask_blueprint . add_url_rule ( endpoint . _uri , name , view_func = ContextualizedHandler ( handler ) , methods = method )
8,068
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/adapters/flask.py#L29-L58
[ "def", "diff", "(", "local_path", ",", "remote_path", ")", ":", "with", "hide", "(", "'commands'", ")", ":", "if", "isinstance", "(", "local_path", ",", "basestring", ")", ":", "with", "open", "(", "local_path", ")", "as", "stream", ":", "local_content", "=", "stream", ".", "read", "(", ")", "else", ":", "pos", "=", "local_path", ".", "tell", "(", ")", "local_content", "=", "local_path", ".", "read", "(", ")", "local_path", ".", "seek", "(", "pos", ")", "remote_content", "=", "StringIO", "(", ")", "with", "settings", "(", "hide", "(", "'warnings'", ")", ",", "warn_only", "=", "True", ")", ":", "if", "get", "(", "remote_path", ",", "remote_content", ")", ".", "failed", ":", "return", "True", "return", "local_content", ".", "strip", "(", ")", "!=", "remote_content", ".", "getvalue", "(", ")", ".", "strip", "(", ")" ]
Check cookie name for validity . Return True if name is valid
def cookie_name_check ( cookie_name ) : cookie_match = WHTTPCookie . cookie_name_non_compliance_re . match ( cookie_name . encode ( 'us-ascii' ) ) return len ( cookie_name ) > 0 and cookie_match is None
8,069
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L66-L73
[ "def", "write_result_stream", "(", "result_stream", ",", "filename_prefix", "=", "None", ",", "results_per_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "result_stream", ",", "types", ".", "GeneratorType", ")", ":", "stream", "=", "result_stream", "else", ":", "stream", "=", "result_stream", ".", "stream", "(", ")", "file_time_formatter", "=", "\"%Y-%m-%dT%H_%M_%S\"", "if", "filename_prefix", "is", "None", ":", "filename_prefix", "=", "\"twitter_search_results\"", "if", "results_per_file", ":", "logger", ".", "info", "(", "\"chunking result stream to files with {} tweets per file\"", ".", "format", "(", "results_per_file", ")", ")", "chunked_stream", "=", "partition", "(", "stream", ",", "results_per_file", ",", "pad_none", "=", "True", ")", "for", "chunk", "in", "chunked_stream", ":", "chunk", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "chunk", ")", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}_{}.json\"", ".", "format", "(", "filename_prefix", ",", "curr_datetime", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "chunk", ")", "else", ":", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}.json\"", ".", "format", "(", "filename_prefix", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "stream", ")" ]
Check cookie attribute value for validity . Return True if value is valid
def cookie_attr_value_check ( attr_name , attr_value ) : attr_value . encode ( 'us-ascii' ) return WHTTPCookie . cookie_attr_value_compliance [ attr_name ] . match ( attr_value ) is not None
8,070
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L85-L93
[ "def", "write_result_stream", "(", "result_stream", ",", "filename_prefix", "=", "None", ",", "results_per_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "result_stream", ",", "types", ".", "GeneratorType", ")", ":", "stream", "=", "result_stream", "else", ":", "stream", "=", "result_stream", ".", "stream", "(", ")", "file_time_formatter", "=", "\"%Y-%m-%dT%H_%M_%S\"", "if", "filename_prefix", "is", "None", ":", "filename_prefix", "=", "\"twitter_search_results\"", "if", "results_per_file", ":", "logger", ".", "info", "(", "\"chunking result stream to files with {} tweets per file\"", ".", "format", "(", "results_per_file", ")", ")", "chunked_stream", "=", "partition", "(", "stream", ",", "results_per_file", ",", "pad_none", "=", "True", ")", "for", "chunk", "in", "chunked_stream", ":", "chunk", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "chunk", ")", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}_{}.json\"", ".", "format", "(", "filename_prefix", ",", "curr_datetime", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "chunk", ")", "else", ":", "curr_datetime", "=", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "file_time_formatter", ")", ")", "_filename", "=", "\"{}.json\"", ".", "format", "(", "filename_prefix", ")", "yield", "from", "write_ndjson", "(", "_filename", ",", "stream", ")" ]
Return suitable and valid attribute name . This method replaces dash char to underscore . If name is invalid ValueError exception is raised
def __attr_name ( self , name ) : if name not in self . cookie_attr_value_compliance . keys ( ) : suggested_name = name . replace ( '_' , '-' ) . lower ( ) if suggested_name not in self . cookie_attr_value_compliance . keys ( ) : raise ValueError ( 'Invalid attribute name is specified' ) name = suggested_name return name
8,071
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L145-L157
[ "def", "_record_offset", "(", "self", ")", ":", "offset", "=", "self", ".", "blob_file", ".", "tell", "(", ")", "self", ".", "event_offsets", ".", "append", "(", "offset", ")" ]
Remove cookie by its name
def remove_cookie ( self , cookie_name ) : if self . __ro_flag : raise RuntimeError ( 'Read-only cookie-jar changing attempt' ) if cookie_name in self . __cookies . keys ( ) : self . __cookies . pop ( cookie_name )
8,072
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L254-L263
[ "def", "initialize_schema", "(", "connection", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"PRAGMA application_id={}\"", ".", "format", "(", "_TENSORBOARD_APPLICATION_ID", ")", ")", "cursor", ".", "execute", "(", "\"PRAGMA user_version={}\"", ".", "format", "(", "_TENSORBOARD_USER_VERSION", ")", ")", "with", "connection", ":", "for", "statement", "in", "_SCHEMA_STATEMENTS", ":", "lines", "=", "statement", ".", "strip", "(", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "message", "=", "lines", "[", "0", "]", "+", "(", "'...'", "if", "len", "(", "lines", ")", ">", "1", "else", "''", ")", "logger", ".", "debug", "(", "'Running DB init statement: %s'", ",", "message", ")", "cursor", ".", "execute", "(", "statement", ")" ]
Return read - only copy
def ro ( self ) : ro_jar = WHTTPCookieJar ( ) for cookie in self . __cookies . values ( ) : ro_jar . add_cookie ( cookie . ro ( ) ) ro_jar . __ro_flag = True return ro_jar
8,073
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L282-L291
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Create cookie jar from SimpleCookie object
def import_simple_cookie ( cls , simple_cookie ) : cookie_jar = WHTTPCookieJar ( ) for cookie_name in simple_cookie . keys ( ) : cookie_attrs = { } for attr_name in WHTTPCookie . cookie_attr_value_compliance . keys ( ) : attr_value = simple_cookie [ cookie_name ] [ attr_name ] if attr_value != '' : cookie_attrs [ attr_name ] = attr_value cookie_jar . add_cookie ( WHTTPCookie ( cookie_name , simple_cookie [ cookie_name ] . value , * * cookie_attrs ) ) return cookie_jar
8,074
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/cookies.py#L295-L312
[ "def", "_find_rtd_version", "(", ")", ":", "vstr", "=", "'latest'", "try", ":", "import", "ginga", "from", "bs4", "import", "BeautifulSoup", "except", "ImportError", ":", "return", "vstr", "# No active doc build before this release, just use latest.", "if", "not", "minversion", "(", "ginga", ",", "'2.6.0'", ")", ":", "return", "vstr", "# Get RTD download listing.", "url", "=", "'https://readthedocs.org/projects/ginga/downloads/'", "with", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "as", "r", ":", "soup", "=", "BeautifulSoup", "(", "r", ",", "'html.parser'", ")", "# Compile a list of available HTML doc versions for download.", "all_rtd_vernums", "=", "[", "]", "for", "link", "in", "soup", ".", "find_all", "(", "'a'", ")", ":", "href", "=", "link", ".", "get", "(", "'href'", ")", "if", "'htmlzip'", "not", "in", "href", ":", "continue", "s", "=", "href", ".", "split", "(", "'/'", ")", "[", "-", "2", "]", "if", "s", ".", "startswith", "(", "'v'", ")", ":", "# Ignore latest and stable", "all_rtd_vernums", ".", "append", "(", "s", ")", "all_rtd_vernums", ".", "sort", "(", "reverse", "=", "True", ")", "# Find closest match.", "ginga_ver", "=", "ginga", ".", "__version__", "for", "rtd_ver", "in", "all_rtd_vernums", ":", "if", "ginga_ver", ">", "rtd_ver", "[", "1", ":", "]", ":", "# Ignore \"v\" in comparison", "break", "else", ":", "vstr", "=", "rtd_ver", "return", "vstr" ]
Check if n is a prime number
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
8,075
https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/helpers.py#L15-L21
[ "def", "find_steam_location", "(", ")", ":", "if", "registry", "is", "None", ":", "return", "None", "key", "=", "registry", ".", "CreateKey", "(", "registry", ".", "HKEY_CURRENT_USER", ",", "\"Software\\Valve\\Steam\"", ")", "return", "registry", ".", "QueryValueEx", "(", "key", ",", "\"SteamPath\"", ")", "[", "0", "]" ]
Display the file associated with the appletID .
def loadFile ( self , fileName ) : # Assign QFile object with the current name. self . file = QtCore . QFile ( fileName ) if self . file . exists ( ) : self . qteText . append ( open ( fileName ) . read ( ) ) else : msg = "File <b>{}</b> does not exist" . format ( self . qteAppletID ( ) ) self . qteLogger . info ( msg )
8,076
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/richeditor.py#L67-L78
[ "def", "_generate_noise_system", "(", "dimensions_tr", ",", "spatial_sd", ",", "temporal_sd", ",", "spatial_noise_type", "=", "'gaussian'", ",", "temporal_noise_type", "=", "'gaussian'", ",", ")", ":", "def", "noise_volume", "(", "dimensions", ",", "noise_type", ",", ")", ":", "if", "noise_type", "==", "'rician'", ":", "# Generate the Rician noise (has an SD of 1)", "noise", "=", "stats", ".", "rice", ".", "rvs", "(", "b", "=", "0", ",", "loc", "=", "0", ",", "scale", "=", "1.527", ",", "size", "=", "dimensions", ")", "elif", "noise_type", "==", "'exponential'", ":", "# Make an exponential distribution (has an SD of 1)", "noise", "=", "stats", ".", "expon", ".", "rvs", "(", "0", ",", "scale", "=", "1", ",", "size", "=", "dimensions", ")", "elif", "noise_type", "==", "'gaussian'", ":", "noise", "=", "np", ".", "random", ".", "randn", "(", "np", ".", "prod", "(", "dimensions", ")", ")", ".", "reshape", "(", "dimensions", ")", "# Return the noise", "return", "noise", "# Get just the xyz coordinates", "dimensions", "=", "np", ".", "asarray", "(", "[", "dimensions_tr", "[", "0", "]", ",", "dimensions_tr", "[", "1", "]", ",", "dimensions_tr", "[", "2", "]", ",", "1", "]", ")", "# Generate noise", "spatial_noise", "=", "noise_volume", "(", "dimensions", ",", "spatial_noise_type", ")", "temporal_noise", "=", "noise_volume", "(", "dimensions_tr", ",", "temporal_noise_type", ")", "# Make the system noise have a specific spatial variability", "spatial_noise", "*=", "spatial_sd", "# Set the size of the noise", "temporal_noise", "*=", "temporal_sd", "# The mean in time of system noise needs to be zero, so subtract the", "# means of the temporal noise in time", "temporal_noise_mean", "=", "np", ".", "mean", "(", "temporal_noise", ",", "3", ")", ".", "reshape", "(", "dimensions", "[", "0", "]", ",", "dimensions", "[", "1", "]", ",", "dimensions", "[", "2", "]", ",", "1", ")", "temporal_noise", "=", "temporal_noise", "-", "temporal_noise_mean", "# Save the combination", "system_noise", "=", "spatial_noise", "+", "temporal_noise", "return", "system_noise" ]
Generate a recursive JSON representation of the ent .
def _encode ( self ) : obj = { k : v for k , v in self . __dict__ . items ( ) if not k . startswith ( '_' ) and type ( v ) in SAFE_TYPES } obj . update ( { k : v . _encode ( ) for k , v in self . __dict__ . items ( ) if isinstance ( v , Ent ) } ) return obj
8,077
https://github.com/jreese/ent/blob/65f7c6498536c551ee1fdb43c3c429f24aa0f755/ent/ent.py#L81-L87
[ "def", "get_fileset", "(", "self", ",", "fileset", ")", ":", "# Don't need to cache fileset as it is already local as long", "# as the path is set", "if", "fileset", ".", "_path", "is", "None", ":", "primary_path", "=", "self", ".", "fileset_path", "(", "fileset", ")", "aux_files", "=", "fileset", ".", "format", ".", "default_aux_file_paths", "(", "primary_path", ")", "if", "not", "op", ".", "exists", "(", "primary_path", ")", ":", "raise", "ArcanaMissingDataException", "(", "\"{} does not exist in {}\"", ".", "format", "(", "fileset", ",", "self", ")", ")", "for", "aux_name", ",", "aux_path", "in", "aux_files", ".", "items", "(", ")", ":", "if", "not", "op", ".", "exists", "(", "aux_path", ")", ":", "raise", "ArcanaMissingDataException", "(", "\"{} is missing '{}' side car in {}\"", ".", "format", "(", "fileset", ",", "aux_name", ",", "self", ")", ")", "else", ":", "primary_path", "=", "fileset", ".", "path", "aux_files", "=", "fileset", ".", "aux_files", "return", "primary_path", ",", "aux_files" ]
Create a new Ent from one or more existing Ents . Keys in the later Ent objects will overwrite the keys of the previous Ents . Later keys of different type than in earlier Ents will be bravely ignored .
def merge ( cls , * args , * * kwargs ) : newkeys = bool ( kwargs . get ( 'newkeys' , False ) ) ignore = kwargs . get ( 'ignore' , list ( ) ) if len ( args ) < 1 : raise ValueError ( 'no ents given to Ent.merge()' ) elif not all ( isinstance ( s , Ent ) for s in args ) : raise ValueError ( 'all positional arguments to Ent.merge() must ' 'be instances of Ent' ) ent = args [ 0 ] data = cls . load ( ent ) for ent in args [ 1 : ] : for key , value in ent . __dict__ . items ( ) : if key in ignore : continue if key in data . __dict__ : v1 = data . __dict__ [ key ] if type ( value ) == type ( v1 ) : if isinstance ( v1 , Ent ) : data . __dict__ [ key ] = cls . merge ( v1 , value , * * kwargs ) else : data . __dict__ [ key ] = cls . load ( value ) elif newkeys : data . __dict__ [ key ] = value return data
8,078
https://github.com/jreese/ent/blob/65f7c6498536c551ee1fdb43c3c429f24aa0f755/ent/ent.py#L133-L176
[ "def", "onSync", "(", "self", ",", "event", ")", ":", "SETUP", "=", "self", ".", "statement", "(", "'SETUP'", ")", "if", "SETUP", ":", "sql", ",", "data", "=", "SETUP", "(", "self", ".", "database", "(", ")", ")", "if", "event", ".", "context", ".", "dryRun", ":", "print", "sql", "%", "data", "else", ":", "self", ".", "execute", "(", "sql", ",", "data", ",", "writeAccess", "=", "True", ")" ]
Create a new Ent representing the differences in two or more existing Ents . Keys in the later Ents with values that differ from the earlier Ents will be present in the final Ent with the latest value seen for that key . Later keys of different type than in earlier Ents will be bravely ignored .
def diff ( cls , * args , * * kwargs ) : newkeys = bool ( kwargs . get ( 'newkeys' , False ) ) ignore = kwargs . get ( 'ignore' , list ( ) ) if len ( args ) < 2 : raise ValueError ( 'less than two ents given to Ent.diff()' ) elif not all ( isinstance ( s , Ent ) for s in args ) : raise ValueError ( 'all positional arguments to Ent.diff() must ' 'be instances of Ent' ) s1 = args [ 0 ] differences = Ent ( ) for s2 in args [ 1 : ] : for key , value in s2 . __dict__ . items ( ) : if key in ignore : continue if key in s1 . __dict__ : v1 = s1 . __dict__ [ key ] if type ( value ) == type ( v1 ) : if isinstance ( v1 , Ent ) : delta = cls . diff ( v1 , value , * * kwargs ) if len ( delta . __dict__ ) : differences . __dict__ [ key ] = delta elif v1 != value : differences . __dict__ [ key ] = cls . load ( value ) elif newkeys : differences . __dict__ [ key ] = cls . load ( value ) s1 = s2 return differences
8,079
https://github.com/jreese/ent/blob/65f7c6498536c551ee1fdb43c3c429f24aa0f755/ent/ent.py#L179-L226
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_access", "is", "not", "None", ":", "_logger", ".", "debug", "(", "\"Cleaning up\"", ")", "pci_cleanup", "(", "self", ".", "_access", ")", "self", ".", "_access", "=", "None" ]
Return a set of all Ent subclasses recursively .
def subclasses ( cls ) : seen = set ( ) queue = set ( [ cls ] ) while queue : c = queue . pop ( ) seen . add ( c ) sc = c . __subclasses__ ( ) for c in sc : if c not in seen : queue . add ( c ) seen . remove ( cls ) return seen
8,080
https://github.com/jreese/ent/blob/65f7c6498536c551ee1fdb43c3c429f24aa0f755/ent/ent.py#L229-L244
[ "def", "insert_recording", "(", "hw", ")", ":", "mysql", "=", "utils", ".", "get_mysql_cfg", "(", ")", "connection", "=", "pymysql", ".", "connect", "(", "host", "=", "mysql", "[", "'host'", "]", ",", "user", "=", "mysql", "[", "'user'", "]", ",", "passwd", "=", "mysql", "[", "'passwd'", "]", ",", "db", "=", "mysql", "[", "'db'", "]", ",", "charset", "=", "'utf8mb4'", ",", "cursorclass", "=", "pymysql", ".", "cursors", ".", "DictCursor", ")", "try", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "sql", "=", "(", "\"INSERT INTO `wm_raw_draw_data` (\"", "\"`user_id`, \"", "\"`data`, \"", "\"`md5data`, \"", "\"`creation_date`, \"", "\"`device_type`, \"", "\"`accepted_formula_id`, \"", "\"`secret`, \"", "\"`ip`, \"", "\"`segmentation`, \"", "\"`internal_id`, \"", "\"`description` \"", "\") VALUES (%s, %s, MD5(data), \"", "\"%s, %s, %s, %s, %s, %s, %s, %s);\"", ")", "data", "=", "(", "hw", ".", "user_id", ",", "hw", ".", "raw_data_json", ",", "getattr", "(", "hw", ",", "'creation_date'", ",", "None", ")", ",", "getattr", "(", "hw", ",", "'device_type'", ",", "''", ")", ",", "getattr", "(", "hw", ",", "'formula_id'", ",", "None", ")", ",", "getattr", "(", "hw", ",", "'secret'", ",", "''", ")", ",", "getattr", "(", "hw", ",", "'ip'", ",", "None", ")", ",", "str", "(", "getattr", "(", "hw", ",", "'segmentation'", ",", "''", ")", ")", ",", "getattr", "(", "hw", ",", "'internal_id'", ",", "''", ")", ",", "getattr", "(", "hw", ",", "'description'", ",", "''", ")", ")", "cursor", ".", "execute", "(", "sql", ",", "data", ")", "connection", ".", "commit", "(", ")", "for", "symbol_id", ",", "strokes", "in", "zip", "(", "hw", ".", "symbol_stream", ",", "hw", ".", "segmentation", ")", ":", "insert_symbol_mapping", "(", "cursor", ".", "lastrowid", ",", "symbol_id", ",", "hw", ".", "user_id", ",", "strokes", ")", "logging", ".", "info", "(", "\"Insert raw data.\"", ")", "except", "pymysql", ".", "err", ".", "IntegrityError", "as", "e", ":", "print", "(", "\"Error: {} (can probably be ignored)\"", ".", "format", "(", "e", ")", ")" ]
Protocol + hostname
def base_url ( self ) : if self . location in self . known_locations : return self . known_locations [ self . location ] elif '.' in self . location or self . location == 'localhost' : return 'https://' + self . location else : return 'https://' + self . location + API_HOST_SUFFIX
8,081
https://github.com/atl/py-smartdc/blob/cc5cd5910e19004cc46e376ce035affe28fc798e/smartdc/datacenter.py#L201-L208
[ "def", "delete", "(", "table", ",", "session", ",", "conds", ")", ":", "with", "session", ".", "begin_nested", "(", ")", ":", "archive_conds_list", "=", "_get_conditions_list", "(", "table", ",", "conds", ")", "session", ".", "execute", "(", "sa", ".", "delete", "(", "table", ".", "ArchiveTable", ",", "whereclause", "=", "_get_conditions", "(", "archive_conds_list", ")", ")", ")", "conds_list", "=", "_get_conditions_list", "(", "table", ",", "conds", ",", "archive", "=", "False", ")", "session", ".", "execute", "(", "sa", ".", "delete", "(", "table", ",", "whereclause", "=", "_get_conditions", "(", "conds_list", ")", ")", ")" ]
Build file names list of modules to exclude from exception handling .
def _build_exclusion_list ( exclude ) : mod_files = [ ] if exclude : for mod in exclude : mdir = None mod_file = None for token in mod . split ( "." ) : try : mfile , mdir , _ = imp . find_module ( token , mdir and [ mdir ] ) if mfile : mod_file = mfile . name mfile . close ( ) except ImportError : msg = "Source for module {mod_name} could not be found" raise ValueError ( msg . format ( mod_name = mod ) ) if mod_file : mod_files . append ( mod_file . replace ( ".pyc" , ".py" ) ) return mod_files
8,082
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L42-L60
[ "def", "read_avro", "(", "file_path_or_buffer", ",", "schema", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "file_path_or_buffer", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "file_path_or_buffer", ",", "'rb'", ")", "as", "f", ":", "return", "__file_to_dataframe", "(", "f", ",", "schema", ",", "*", "*", "kwargs", ")", "else", ":", "return", "__file_to_dataframe", "(", "file_path_or_buffer", ",", "schema", ",", "*", "*", "kwargs", ")" ]
Select valid stack frame to process .
def _invalid_frame ( fobj ) : fin = fobj . f_code . co_filename invalid_module = any ( [ fin . endswith ( item ) for item in _INVALID_MODULES_LIST ] ) return invalid_module or ( not os . path . isfile ( fin ) )
8,083
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L63-L67
[ "def", "bucket_create", "(", "self", ",", "name", ",", "bucket_type", "=", "'couchbase'", ",", "bucket_password", "=", "''", ",", "replicas", "=", "0", ",", "ram_quota", "=", "1024", ",", "flush_enabled", "=", "False", ")", ":", "params", "=", "{", "'name'", ":", "name", ",", "'bucketType'", ":", "bucket_type", ",", "'authType'", ":", "'sasl'", ",", "'saslPassword'", ":", "bucket_password", "if", "bucket_password", "else", "''", ",", "'flushEnabled'", ":", "int", "(", "flush_enabled", ")", ",", "'ramQuotaMB'", ":", "ram_quota", "}", "if", "bucket_type", "in", "(", "'couchbase'", ",", "'membase'", ",", "'ephemeral'", ")", ":", "params", "[", "'replicaNumber'", "]", "=", "replicas", "return", "self", ".", "http_request", "(", "path", "=", "'/pools/default/buckets'", ",", "method", "=", "'POST'", ",", "content", "=", "self", ".", "_mk_formstr", "(", "params", ")", ",", "content_type", "=", "'application/x-www-form-urlencoded'", ")" ]
Return dictionary items sorted by key .
def _sorted_keys_items ( dobj ) : keys = sorted ( dobj . keys ( ) ) for key in keys : yield key , dobj [ key ]
8,084
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L150-L154
[ "def", "mock_xray_client", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "_wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", "(", "\"Starting X-Ray Patch\"", ")", "old_xray_context_var", "=", "os", ".", "environ", ".", "get", "(", "'AWS_XRAY_CONTEXT_MISSING'", ")", "os", ".", "environ", "[", "'AWS_XRAY_CONTEXT_MISSING'", "]", "=", "'LOG_ERROR'", "old_xray_context", "=", "aws_xray_sdk", ".", "core", ".", "xray_recorder", ".", "_context", "old_xray_emitter", "=", "aws_xray_sdk", ".", "core", ".", "xray_recorder", ".", "_emitter", "aws_xray_sdk", ".", "core", ".", "xray_recorder", ".", "_context", "=", "AWSContext", "(", ")", "aws_xray_sdk", ".", "core", ".", "xray_recorder", ".", "_emitter", "=", "MockEmitter", "(", ")", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "if", "old_xray_context_var", "is", "None", ":", "del", "os", ".", "environ", "[", "'AWS_XRAY_CONTEXT_MISSING'", "]", "else", ":", "os", ".", "environ", "[", "'AWS_XRAY_CONTEXT_MISSING'", "]", "=", "old_xray_context_var", "aws_xray_sdk", ".", "core", ".", "xray_recorder", ".", "_emitter", "=", "old_xray_emitter", "aws_xray_sdk", ".", "core", ".", "xray_recorder", ".", "_context", "=", "old_xray_context", "return", "_wrapped" ]
r Add an exception in the global exception handler .
def addex ( extype , exmsg , condition = None , edata = None ) : return _ExObj ( extype , exmsg , condition , edata ) . craise
8,085
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L157-L207
[ "def", "approxQuantile", "(", "self", ",", "col", ",", "probabilities", ",", "relativeError", ")", ":", "if", "not", "isinstance", "(", "col", ",", "(", "basestring", ",", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"col should be a string, list or tuple, but got %r\"", "%", "type", "(", "col", ")", ")", "isStr", "=", "isinstance", "(", "col", ",", "basestring", ")", "if", "isinstance", "(", "col", ",", "tuple", ")", ":", "col", "=", "list", "(", "col", ")", "elif", "isStr", ":", "col", "=", "[", "col", "]", "for", "c", "in", "col", ":", "if", "not", "isinstance", "(", "c", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"columns should be strings, but got %r\"", "%", "type", "(", "c", ")", ")", "col", "=", "_to_list", "(", "self", ".", "_sc", ",", "col", ")", "if", "not", "isinstance", "(", "probabilities", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"probabilities should be a list or tuple\"", ")", "if", "isinstance", "(", "probabilities", ",", "tuple", ")", ":", "probabilities", "=", "list", "(", "probabilities", ")", "for", "p", "in", "probabilities", ":", "if", "not", "isinstance", "(", "p", ",", "(", "float", ",", "int", ",", "long", ")", ")", "or", "p", "<", "0", "or", "p", ">", "1", ":", "raise", "ValueError", "(", "\"probabilities should be numerical (float, int, long) in [0,1].\"", ")", "probabilities", "=", "_to_list", "(", "self", ".", "_sc", ",", "probabilities", ")", "if", "not", "isinstance", "(", "relativeError", ",", "(", "float", ",", "int", ",", "long", ")", ")", "or", "relativeError", "<", "0", ":", "raise", "ValueError", "(", "\"relativeError should be numerical (float, int, long) >= 0.\"", ")", "relativeError", "=", "float", "(", "relativeError", ")", "jaq", "=", "self", ".", "_jdf", ".", "stat", "(", ")", ".", "approxQuantile", "(", "col", ",", "probabilities", ",", "relativeError", ")", "jaq_list", "=", "[", "list", "(", "j", ")", "for", "j", "in", "jaq", "]", "return", "jaq_list", "[", "0", "]", "if", "isStr", "else", "jaq_list" ]
r Add an AI exception in the global exception handler .
def addai ( argname , condition = None ) : # pylint: disable=C0123 if not isinstance ( argname , str ) : raise RuntimeError ( "Argument `argname` is not valid" ) if ( condition is not None ) and ( type ( condition ) != bool ) : raise RuntimeError ( "Argument `condition` is not valid" ) obj = _ExObj ( RuntimeError , "Argument `{0}` is not valid" . format ( argname ) , condition ) return obj . craise
8,086
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L210-L239
[ "def", "histogram_info", "(", "self", ")", "->", "dict", ":", "return", "{", "'support_atoms'", ":", "self", ".", "support_atoms", ",", "'atom_delta'", ":", "self", ".", "atom_delta", ",", "'vmin'", ":", "self", ".", "vmin", ",", "'vmax'", ":", "self", ".", "vmax", ",", "'num_atoms'", ":", "self", ".", "atoms", "}" ]
r Return global exception handler if set otherwise create a new one and return it .
def get_or_create_exh_obj ( full_cname = False , exclude = None , callables_fname = None ) : if not hasattr ( __builtin__ , "_EXH" ) : set_exh_obj ( ExHandle ( full_cname = full_cname , exclude = exclude , callables_fname = callables_fname ) ) return get_exh_obj ( )
8,087
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L260-L305
[ "async", "def", "services", "(", "self", ",", "*", ",", "dc", "=", "None", ",", "watch", "=", "None", ",", "consistency", "=", "None", ")", ":", "params", "=", "{", "\"dc\"", ":", "dc", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/catalog/services\"", ",", "params", "=", "params", ",", "watch", "=", "watch", ",", "consistency", "=", "consistency", ")", "return", "consul", "(", "response", ")" ]
Flatten structure of exceptions dictionary .
def _flatten_ex_dict ( self ) : odict = { } for _ , fdict in self . _ex_dict . items ( ) : for ( extype , exmsg ) , value in fdict . items ( ) : key = value [ "name" ] odict [ key ] = copy . deepcopy ( value ) del odict [ key ] [ "name" ] odict [ key ] [ "type" ] = extype odict [ key ] [ "msg" ] = exmsg return odict
8,088
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L804-L814
[ "def", "move", "(", "self", ",", "partition", ",", "source", ",", "dest", ")", ":", "new_state", "=", "copy", "(", "self", ")", "# Update the partition replica tuple", "source_index", "=", "self", ".", "replicas", "[", "partition", "]", ".", "index", "(", "source", ")", "new_state", ".", "replicas", "=", "tuple_alter", "(", "self", ".", "replicas", ",", "(", "partition", ",", "lambda", "replicas", ":", "tuple_replace", "(", "replicas", ",", "(", "source_index", ",", "dest", ")", ",", ")", ")", ",", ")", "new_state", ".", "pending_partitions", "=", "self", ".", "pending_partitions", "+", "(", "partition", ",", ")", "# Update the broker weights", "partition_weight", "=", "self", ".", "partition_weights", "[", "partition", "]", "new_state", ".", "broker_weights", "=", "tuple_alter", "(", "self", ".", "broker_weights", ",", "(", "source", ",", "lambda", "broker_weight", ":", "broker_weight", "-", "partition_weight", ")", ",", "(", "dest", ",", "lambda", "broker_weight", ":", "broker_weight", "+", "partition_weight", ")", ",", ")", "# Update the broker partition count", "new_state", ".", "broker_partition_counts", "=", "tuple_alter", "(", "self", ".", "broker_partition_counts", ",", "(", "source", ",", "lambda", "partition_count", ":", "partition_count", "-", "1", ")", ",", "(", "dest", ",", "lambda", "partition_count", ":", "partition_count", "+", "1", ")", ",", ")", "# Update the broker leader weights", "if", "source_index", "==", "0", ":", "new_state", ".", "broker_leader_weights", "=", "tuple_alter", "(", "self", ".", "broker_leader_weights", ",", "(", "source", ",", "lambda", "lw", ":", "lw", "-", "partition_weight", ")", ",", "(", "dest", ",", "lambda", "lw", ":", "lw", "+", "partition_weight", ")", ",", ")", "new_state", ".", "broker_leader_counts", "=", "tuple_alter", "(", "self", ".", "broker_leader_counts", ",", "(", "source", ",", "lambda", "leader_count", ":", "leader_count", "-", "1", ")", ",", "(", "dest", ",", "lambda", "leader_count", ":", "leader_count", "+", "1", ")", ",", ")", "new_state", ".", "leader_movement_count", "+=", "1", "# Update the topic broker counts", "topic", "=", "self", ".", "partition_topic", "[", "partition", "]", "new_state", ".", "topic_broker_count", "=", "tuple_alter", "(", "self", ".", "topic_broker_count", ",", "(", "topic", ",", "lambda", "broker_count", ":", "tuple_alter", "(", "broker_count", ",", "(", "source", ",", "lambda", "count", ":", "count", "-", "1", ")", ",", "(", "dest", ",", "lambda", "count", ":", "count", "+", "1", ")", ",", ")", ")", ",", ")", "# Update the topic broker imbalance", "new_state", ".", "topic_broker_imbalance", "=", "tuple_replace", "(", "self", ".", "topic_broker_imbalance", ",", "(", "topic", ",", "new_state", ".", "_calculate_topic_imbalance", "(", "topic", ")", ")", ",", ")", "new_state", ".", "_weighted_topic_broker_imbalance", "=", "(", "self", ".", "_weighted_topic_broker_imbalance", "+", "self", ".", "topic_weights", "[", "topic", "]", "*", "(", "new_state", ".", "topic_broker_imbalance", "[", "topic", "]", "-", "self", ".", "topic_broker_imbalance", "[", "topic", "]", ")", ")", "# Update the replication group replica counts", "source_rg", "=", "self", ".", "broker_rg", "[", "source", "]", "dest_rg", "=", "self", ".", "broker_rg", "[", "dest", "]", "if", "source_rg", "!=", "dest_rg", ":", "new_state", ".", "rg_replicas", "=", "tuple_alter", "(", "self", ".", "rg_replicas", ",", "(", "source_rg", ",", "lambda", "replica_counts", ":", "tuple_alter", "(", "replica_counts", ",", "(", "partition", ",", "lambda", "replica_count", ":", "replica_count", "-", "1", ")", ",", ")", ")", ",", "(", "dest_rg", ",", "lambda", "replica_counts", ":", "tuple_alter", "(", "replica_counts", ",", "(", "partition", ",", "lambda", "replica_count", ":", "replica_count", "+", "1", ")", ",", ")", ")", ",", ")", "# Update the movement sizes", "new_state", ".", "movement_size", "+=", "self", ".", "partition_sizes", "[", "partition", "]", "new_state", ".", "movement_count", "+=", "1", "return", "new_state" ]
Substitute parameters in exception message .
def _format_msg ( self , msg , edata ) : edata = edata if isinstance ( edata , list ) else [ edata ] for fdict in edata : if "*[{token}]*" . format ( token = fdict [ "field" ] ) not in msg : raise RuntimeError ( "Field {token} not in exception message" . format ( token = fdict [ "field" ] ) ) msg = msg . replace ( "*[{token}]*" . format ( token = fdict [ "field" ] ) , "{value}" ) . format ( value = fdict [ "value" ] ) return msg
8,089
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L816-L829
[ "def", "edit", "(", "self", ",", "data_src", ",", "value", ")", ":", "# check if opening file", "if", "'filename'", "in", "value", ":", "items", "=", "[", "k", "for", "k", ",", "v", "in", "self", ".", "reg", ".", "data_source", ".", "iteritems", "(", ")", "if", "v", "==", "data_src", "]", "self", ".", "reg", ".", "unregister", "(", "items", ")", "# remove items from Registry", "# open file and register new data", "self", ".", "open", "(", "data_src", ",", "value", "[", "'filename'", "]", ",", "value", ".", "get", "(", "'path'", ")", ")", "self", ".", "layer", "[", "data_src", "]", ".", "update", "(", "value", ")" ]
Return a list of dictionaries suitable to be used with ptrie module .
def _get_exceptions_db ( self ) : template = "{extype} ({exmsg}){raised}" if not self . _full_cname : # When full callable name is not used the calling path is # irrelevant and there is no function associated with an # exception ret = [ ] for _ , fdict in self . _ex_dict . items ( ) : for key in fdict . keys ( ) : ret . append ( { "name" : fdict [ key ] [ "name" ] , "data" : template . format ( extype = _ex_type_str ( key [ 0 ] ) , exmsg = key [ 1 ] , raised = "*" if fdict [ key ] [ "raised" ] [ 0 ] else "" , ) , } ) return ret # When full callable name is used, all calling paths are saved ret = [ ] for fdict in self . _ex_dict . values ( ) : for key in fdict . keys ( ) : for func_name in fdict [ key ] [ "function" ] : rindex = fdict [ key ] [ "function" ] . index ( func_name ) raised = fdict [ key ] [ "raised" ] [ rindex ] ret . append ( { "name" : self . decode_call ( func_name ) , "data" : template . format ( extype = _ex_type_str ( key [ 0 ] ) , exmsg = key [ 1 ] , raised = "*" if raised else "" , ) , } ) return ret
8,090
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1025-L1063
[ "def", "_clear_interrupt", "(", "self", ",", "intbit", ")", ":", "int_status", "=", "self", ".", "_device", ".", "readU8", "(", "VCNL4010_INTSTAT", ")", "int_status", "&=", "~", "intbit", "self", ".", "_device", ".", "write8", "(", "VCNL4010_INTSTAT", ",", "int_status", ")" ]
Return hierarchical function name .
def _get_ex_data ( self ) : func_id , func_name = self . _get_callable_path ( ) if self . _full_cname : func_name = self . encode_call ( func_name ) return func_id , func_name
8,091
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1065-L1070
[ "def", "clean_blobstore_cache", "(", "self", ")", ":", "url", "=", "self", ".", "api_url", "+", "self", ".", "blobstores_builpack_cache_url", "resp", ",", "rcode", "=", "self", ".", "request", "(", "'DELETE'", ",", "url", ")", "if", "rcode", "!=", "202", ":", "raise", "CFException", "(", "resp", ",", "rcode", ")", "return", "resp" ]
Return full name if object is a class property otherwise return None .
def _property_search ( self , fobj ) : # Get class object scontext = fobj . f_locals . get ( "self" , None ) class_obj = scontext . __class__ if scontext is not None else None if not class_obj : del fobj , scontext , class_obj return None # Get class properties objects class_props = [ ( member_name , member_obj ) for member_name , member_obj in inspect . getmembers ( class_obj ) if isinstance ( member_obj , property ) ] if not class_props : del fobj , scontext , class_obj return None class_file = inspect . getfile ( class_obj ) . replace ( ".pyc" , ".py" ) class_name = self . _callables_obj . get_callable_from_line ( class_file , inspect . getsourcelines ( class_obj ) [ 1 ] ) # Get properties actions prop_actions_dicts = { } for prop_name , prop_obj in class_props : prop_dict = { "fdel" : None , "fget" : None , "fset" : None } for action in prop_dict : action_obj = getattr ( prop_obj , action ) if action_obj : # Unwrap action object. Contracts match the wrapped # code object while exceptions registered in the # body of the function/method which has decorators # match the unwrapped object prev_func_obj , next_func_obj = ( action_obj , getattr ( action_obj , "__wrapped__" , None ) , ) while next_func_obj : prev_func_obj , next_func_obj = ( next_func_obj , getattr ( next_func_obj , "__wrapped__" , None ) , ) prop_dict [ action ] = [ id ( _get_func_code ( action_obj ) ) , id ( _get_func_code ( prev_func_obj ) ) , ] prop_actions_dicts [ prop_name ] = prop_dict # Create properties directory func_id = id ( fobj . f_code ) desc_dict = { "fget" : "getter" , "fset" : "setter" , "fdel" : "deleter" } for prop_name , prop_actions_dict in prop_actions_dicts . items ( ) : for action_name , action_id_list in prop_actions_dict . items ( ) : if action_id_list and ( func_id in action_id_list ) : prop_name = "." . join ( [ class_name , prop_name ] ) del fobj , scontext , class_obj , class_props return "{prop_name}({prop_action})" . format ( prop_name = prop_name , prop_action = desc_dict [ action_name ] ) return None
8,092
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1072-L1129
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Raise exception by name .
def _raise_exception ( self , eobj , edata = None ) : _ , _ , tbobj = sys . exc_info ( ) if edata : emsg = self . _format_msg ( eobj [ "msg" ] , edata ) _rwtb ( eobj [ "type" ] , emsg , tbobj ) else : _rwtb ( eobj [ "type" ] , eobj [ "msg" ] , tbobj )
8,093
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1131-L1138
[ "def", "_get_publish_details", "(", "actions", ",", "app_metadata_template", ")", ":", "if", "actions", "==", "[", "CREATE_APPLICATION", "]", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "app_metadata_template", ".", "items", "(", ")", "if", "v", "}", "include_keys", "=", "[", "ApplicationMetadata", ".", "AUTHOR", ",", "ApplicationMetadata", ".", "DESCRIPTION", ",", "ApplicationMetadata", ".", "HOME_PAGE_URL", ",", "ApplicationMetadata", ".", "LABELS", ",", "ApplicationMetadata", ".", "README_URL", "]", "if", "CREATE_APPLICATION_VERSION", "in", "actions", ":", "# SemanticVersion and SourceCodeUrl can only be updated by creating a new version", "additional_keys", "=", "[", "ApplicationMetadata", ".", "SEMANTIC_VERSION", ",", "ApplicationMetadata", ".", "SOURCE_CODE_URL", "]", "include_keys", ".", "extend", "(", "additional_keys", ")", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "app_metadata_template", ".", "items", "(", ")", "if", "k", "in", "include_keys", "and", "v", "}" ]
Unwrap decorators .
def _unwrap_obj ( self , fobj , fun ) : try : prev_func_obj , next_func_obj = ( fobj . f_globals [ fun ] , getattr ( fobj . f_globals [ fun ] , "__wrapped__" , None ) , ) while next_func_obj : prev_func_obj , next_func_obj = ( next_func_obj , getattr ( next_func_obj , "__wrapped__" , None ) , ) return ( prev_func_obj , inspect . getfile ( prev_func_obj ) . replace ( ".pyc" , "py" ) ) except ( KeyError , AttributeError , TypeError ) : # KeyErrror: fun not in fobj.f_globals # AttributeError: fobj.f_globals does not have # a __wrapped__ attribute # TypeError: pref_func_obj does not have a file associated with it return None , None
8,094
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1140-L1158
[ "def", "on_response", "(", "self", ",", "ch", ",", "method_frame", ",", "props", ",", "body", ")", ":", "LOGGER", ".", "debug", "(", "\"rabbitmq.Requester.on_response\"", ")", "if", "self", ".", "corr_id", "==", "props", ".", "correlation_id", ":", "self", ".", "response", "=", "{", "'props'", ":", "props", ",", "'body'", ":", "body", "}", "else", ":", "LOGGER", ".", "warn", "(", "\"rabbitmq.Requester.on_response - discarded response : \"", "+", "str", "(", "props", ".", "correlation_id", ")", ")", "LOGGER", ".", "debug", "(", "\"natsd.Requester.on_response - discarded response : \"", "+", "str", "(", "{", "'properties'", ":", "props", ",", "'body'", ":", "body", "}", ")", ")" ]
Validate edata argument of raise_exception_if method .
def _validate_edata ( self , edata ) : # pylint: disable=R0916 if edata is None : return True if not ( isinstance ( edata , dict ) or _isiterable ( edata ) ) : return False edata = [ edata ] if isinstance ( edata , dict ) else edata for edict in edata : if ( not isinstance ( edict , dict ) ) or ( isinstance ( edict , dict ) and ( ( "field" not in edict ) or ( "field" in edict and ( not isinstance ( edict [ "field" ] , str ) ) ) or ( "value" not in edict ) ) ) : return False return True
8,095
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1160-L1178
[ "def", "rank_clusters", "(", "cluster_dict", ")", ":", "# Figure out the relative rank of each cluster", "cluster_ranks", "=", "dict", ".", "fromkeys", "(", "cluster_dict", ".", "keys", "(", ")", ")", "for", "key", "in", "cluster_dict", ":", "cluster_ranks", "[", "key", "]", "=", "eval", "(", "string_avg", "(", "cluster_dict", "[", "key", "]", ",", "binary", "=", "True", ")", ")", "i", "=", "len", "(", "cluster_ranks", ")", "for", "key", "in", "sorted", "(", "cluster_ranks", ",", "key", "=", "cluster_ranks", ".", "get", ")", ":", "cluster_ranks", "[", "key", "]", "=", "i", "i", "-=", "1", "return", "cluster_ranks" ]
r Add an exception to the handler .
def add_exception ( self , exname , extype , exmsg ) : if not isinstance ( exname , str ) : raise RuntimeError ( "Argument `exname` is not valid" ) number = True try : int ( exname ) except ValueError : number = False if number : raise RuntimeError ( "Argument `exname` is not valid" ) if not isinstance ( exmsg , str ) : raise RuntimeError ( "Argument `exmsg` is not valid" ) msg = "" try : raise extype ( exmsg ) except Exception as eobj : msg = _get_ex_msg ( eobj ) if msg != exmsg : raise RuntimeError ( "Argument `extype` is not valid" ) # A callable that defines an exception can be accessed by # multiple functions or paths, therefore the callable # dictionary key 'function' is a list func_id , func_name = self . _get_ex_data ( ) if func_id not in self . _ex_dict : self . _ex_dict [ func_id ] = { } key = ( extype , exmsg ) exname = "{0}{1}{2}" . format ( func_id , self . _callables_separator , exname ) entry = self . _ex_dict [ func_id ] . get ( key , { "function" : [ ] , "name" : exname , "raised" : [ ] } ) if func_name not in entry [ "function" ] : entry [ "function" ] . append ( func_name ) entry [ "raised" ] . append ( False ) self . _ex_dict [ func_id ] [ key ] = entry return ( func_id , key , func_name )
8,096
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1180-L1259
[ "def", "get_key_for_schema_and_document_string", "(", "self", ",", "schema", ",", "request_string", ")", ":", "# type: (GraphQLSchema, str) -> int", "if", "self", ".", "use_consistent_hash", ":", "schema_id", "=", "get_unique_schema_id", "(", "schema", ")", "document_id", "=", "get_unique_document_id", "(", "request_string", ")", "return", "hash", "(", "(", "schema_id", ",", "document_id", ")", ")", "return", "hash", "(", "(", "schema", ",", "request_string", ")", ")" ]
Replace callable tokens with callable names .
def decode_call ( self , call ) : # Callable name is None when callable is part of exclude list if call is None : return None itokens = call . split ( self . _callables_separator ) odict = { } for key , value in self . _clut . items ( ) : if value in itokens : odict [ itokens [ itokens . index ( value ) ] ] = key return self . _callables_separator . join ( [ odict [ itoken ] for itoken in itokens ] )
8,097
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1261-L1278
[ "def", "_intersection", "(", "self", ",", "keys", ",", "rows", ")", ":", "# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.", "if", "not", "keys", ":", "return", "rows", "ret", "=", "list", "(", ")", "for", "row", "in", "rows", ":", "start_date", "=", "row", "[", "self", ".", "_key_start_date", "]", "end_date", "=", "row", "[", "self", ".", "_key_end_date", "]", "for", "key_start_date", ",", "key_end_date", "in", "keys", ":", "start_date", ",", "end_date", "=", "Type2JoinHelper", ".", "_intersect", "(", "start_date", ",", "end_date", ",", "row", "[", "key_start_date", "]", ",", "row", "[", "key_end_date", "]", ")", "if", "not", "start_date", ":", "break", "if", "key_start_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_start_date", "]", "if", "key_end_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_end_date", "]", "if", "start_date", ":", "row", "[", "self", ".", "_key_start_date", "]", "=", "start_date", "row", "[", "self", ".", "_key_end_date", "]", "=", "end_date", "ret", ".", "append", "(", "row", ")", "return", "ret" ]
Replace callables with tokens to reduce object memory footprint .
def encode_call ( self , call ) : # Callable name is None when callable is part of exclude list if call is None : return None itokens = call . split ( self . _callables_separator ) otokens = [ ] for itoken in itokens : otoken = self . _clut . get ( itoken , None ) if not otoken : otoken = str ( len ( self . _clut ) ) self . _clut [ itoken ] = otoken otokens . append ( otoken ) return self . _callables_separator . join ( otokens )
8,098
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/pexdoc/exh.py#L1280-L1305
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
Default JSON encoding .
def default ( self , obj ) : try : if isinstance ( obj , datetime . datetime ) : # do the datetime thing, or encoded = arrow . get ( obj ) . isoformat ( ) else : # try the normal encoder encoded = json . JSONEncoder . default ( self , obj ) except TypeError as e : # if that fails, check for the to_dict method, if hasattr ( obj , 'to_dict' ) and callable ( obj . to_dict ) : # and use it! encoded = obj . to_dict ( ) else : raise e return encoded
8,099
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/endpoint.py#L36-L52
[ "def", "destroy_sns_event", "(", "app_name", ",", "env", ",", "region", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ",", "region_name", "=", "region", ")", "sns_client", "=", "session", ".", "client", "(", "'sns'", ")", "lambda_subscriptions", "=", "get_sns_subscriptions", "(", "app_name", "=", "app_name", ",", "env", "=", "env", ",", "region", "=", "region", ")", "for", "subscription_arn", "in", "lambda_subscriptions", ":", "sns_client", ".", "unsubscribe", "(", "SubscriptionArn", "=", "subscription_arn", ")", "LOG", ".", "debug", "(", "\"Lambda SNS event deleted\"", ")", "return", "True" ]