query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Returns all Individuals that have organization as a primary org .
def get_individuals_for_primary_organization ( self , organization ) : if not self . client . session_id : self . client . request_session ( ) object_query = ( "SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'" . format ( organization . membersuite_account_num ) ) result = self . client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] if msql_result [ "Success" ] : membersuite_objects = ( msql_result [ "ResultValue" ] [ "ObjectSearchResult" ] [ "Objects" ] ) else : raise ExecuteMSQLError ( result = result ) individuals = [ ] if membersuite_objects is not None : for membersuite_object in membersuite_objects [ "MemberSuiteObject" ] : individuals . append ( Individual ( membersuite_object_data = membersuite_object ) ) return individuals
7,700
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L109-L140
[ "def", "_get_remote_video_url", "(", "self", ",", "remote_node", ",", "session_id", ")", ":", "url", "=", "'{}/video'", ".", "format", "(", "self", ".", "_get_remote_node_url", "(", "remote_node", ")", ")", "timeout", "=", "time", ".", "time", "(", ")", "+", "5", "# 5 seconds from now", "# Requests videos list until timeout or the video url is found", "video_url", "=", "None", "while", "time", ".", "time", "(", ")", "<", "timeout", ":", "response", "=", "requests", ".", "get", "(", "url", ")", ".", "json", "(", ")", "try", ":", "video_url", "=", "response", "[", "'available_videos'", "]", "[", "session_id", "]", "[", "'download_url'", "]", "break", "except", "KeyError", ":", "time", ".", "sleep", "(", "1", ")", "return", "video_url" ]
Check if the value of this namespace is matched by keys
def match ( self , keys , partial = True ) : if not partial and len ( keys ) != self . length : return False c = 0 for k in keys : if c >= self . length : return False a = self . keys [ c ] if a != "*" and k != "*" and k != a : return False c += 1 return True
7,701
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L81-L113
[ "def", "get_async", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "config", ".", "static_folder", ",", "filename", ")", ")", ":", "return", "flask", ".", "redirect", "(", "flask", ".", "url_for", "(", "'static'", ",", "filename", "=", "filename", ")", ")", "retry_count", "=", "int", "(", "flask", ".", "request", ".", "args", ".", "get", "(", "'retry_count'", ",", "0", ")", ")", "if", "retry_count", "<", "10", ":", "time", ".", "sleep", "(", "0.25", ")", "# ghastly hack to get the client to backoff a bit", "return", "flask", ".", "redirect", "(", "flask", ".", "url_for", "(", "'async'", ",", "filename", "=", "filename", ",", "cb", "=", "random", ".", "randint", "(", "0", ",", "2", "**", "48", ")", ",", "retry_count", "=", "retry_count", "+", "1", ")", ")", "# the image isn't available yet; generate a placeholder and let the", "# client attempt to re-fetch periodically, maybe", "vals", "=", "[", "int", "(", "b", ")", "for", "b", "in", "hashlib", ".", "md5", "(", "filename", ".", "encode", "(", "'utf-8'", ")", ")", ".", "digest", "(", ")", "[", "0", ":", "12", "]", "]", "placeholder", "=", "PIL", ".", "Image", ".", "new", "(", "'RGB'", ",", "(", "2", ",", "2", ")", ")", "placeholder", ".", "putdata", "(", "list", "(", "zip", "(", "vals", "[", "0", ":", ":", "3", "]", ",", "vals", "[", "1", ":", ":", "3", "]", ",", "vals", "[", "2", ":", ":", "3", "]", ")", ")", ")", "outbytes", "=", "io", ".", "BytesIO", "(", ")", "placeholder", ".", "save", "(", "outbytes", ",", "\"PNG\"", ")", "outbytes", ".", "seek", "(", "0", ")", "response", "=", "flask", ".", "make_response", "(", "flask", ".", "send_file", "(", "outbytes", ",", "mimetype", "=", "'image/png'", ")", ")", "response", ".", "headers", "[", "'Refresh'", "]", "=", "5", "return", "response" ]
Creates a dict built from the keys of this namespace
def container ( self , data = None ) : if data is None : data = { } root = p = d = { } j = 0 k = None for k in self : d [ k ] = { } p = d d = d [ k ] if k is not None : p [ k ] = data return ( root , p [ k ] )
7,702
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L115-L144
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
Regenerates the permission index for this set
def update_index ( self ) : # update index idx = { } for _ , p in sorted ( self . permissions . items ( ) , key = lambda x : str ( x [ 0 ] ) ) : branch = idx parent_p = const . PERM_DENY for k in p . namespace . keys : if not k in branch : branch [ k ] = { "__" : parent_p } branch [ k ] . update ( __implicit = True ) branch = branch [ k ] parent_p = branch [ "__" ] branch [ "__" ] = p . value branch [ "__implicit" ] = False self . index = idx # update read access map ramap = { } def update_ramap ( branch_idx ) : r = { "__" : False } for k , v in list ( branch_idx . items ( ) ) : if k != "__" and k != "__implicit" : r [ k ] = update_ramap ( v ) if branch_idx [ "__" ] is not None and ( branch_idx [ "__" ] & const . PERM_READ ) != 0 : r [ "__" ] = True return r for k , v in list ( idx . items ( ) ) : ramap [ k ] = update_ramap ( v ) self . read_access_map = ramap return self . index
7,703
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L274-L319
[ "def", "post_json", "(", "self", ",", "url", ",", "data", ",", "cls", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'data'", "]", "=", "to_json", "(", "data", ",", "cls", "=", "cls", ")", "kwargs", "[", "'headers'", "]", "=", "self", ".", "default_headers", "return", "self", ".", "post", "(", "url", ",", "*", "*", "kwargs", ")", ".", "json", "(", ")" ]
Returns the permissions level for the specified namespace
def get_permissions ( self , namespace , explicit = False ) : if not isinstance ( namespace , Namespace ) : namespace = Namespace ( namespace ) keys = namespace . keys p , _ = self . _check ( keys , self . index , explicit = explicit ) return p
7,704
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L360-L378
[ "def", "upload_index_file", "(", "self", ",", "test_address", ",", "timestamp", ")", ":", "global", "already_uploaded_files", "already_uploaded_files", "=", "list", "(", "set", "(", "already_uploaded_files", ")", ")", "already_uploaded_files", ".", "sort", "(", ")", "file_name", "=", "\"%s/%s/index.html\"", "%", "(", "test_address", ",", "timestamp", ")", "index", "=", "self", ".", "get_key", "(", "file_name", ")", "index_str", "=", "[", "]", "for", "completed_file", "in", "already_uploaded_files", ":", "index_str", ".", "append", "(", "\"<a href='\"", "+", "self", ".", "bucket_url", "+", "\"\"", "\"%s'>%s</a>\"", "%", "(", "completed_file", ",", "completed_file", ")", ")", "index", ".", "set_contents_from_string", "(", "\"<br>\"", ".", "join", "(", "index_str", ")", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"text/html\"", "}", ")", "index", ".", "make_public", "(", ")", "return", "\"%s%s\"", "%", "(", "self", ".", "bucket_url", ",", "file_name", ")" ]
Checks if the permset has permission to the specified namespace at the specified level
def check ( self , namespace , level , explicit = False ) : return ( self . get_permissions ( namespace , explicit = explicit ) & level ) != 0
7,705
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L381-L397
[ "def", "commit", "(", "self", ")", ":", "self", ".", "send_buffered_operations", "(", ")", "retry_until_ok", "(", "self", ".", "elastic", ".", "indices", ".", "refresh", ",", "index", "=", "\"\"", ")" ]
Return digest of the given message and key
def hash ( self , key , message = None ) : hmac_obj = hmac . HMAC ( key , self . __digest_generator , backend = default_backend ( ) ) if message is not None : hmac_obj . update ( message ) return hmac_obj . finalize ( )
7,706
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/hmac.py#L69-L80
[ "def", "sync_blockchain", "(", "working_dir", ",", "bt_opts", ",", "last_block", ",", "server_state", ",", "expected_snapshots", "=", "{", "}", ",", "*", "*", "virtualchain_args", ")", ":", "subdomain_index", "=", "server_state", "[", "'subdomains'", "]", "atlas_state", "=", "server_state", "[", "'atlas'", "]", "# make this usable even if we haven't explicitly configured virtualchain ", "impl", "=", "sys", ".", "modules", "[", "__name__", "]", "log", ".", "info", "(", "\"Synchronizing database {} up to block {}\"", ".", "format", "(", "working_dir", ",", "last_block", ")", ")", "# NOTE: this is the only place where a read-write handle should be created,", "# since this is the only place where the db should be modified.", "new_db", "=", "BlockstackDB", ".", "borrow_readwrite_instance", "(", "working_dir", ",", "last_block", ",", "expected_snapshots", "=", "expected_snapshots", ")", "# propagate runtime state to virtualchain callbacks", "new_db", ".", "subdomain_index", "=", "subdomain_index", "new_db", ".", "atlas_state", "=", "atlas_state", "rc", "=", "virtualchain", ".", "sync_virtualchain", "(", "bt_opts", ",", "last_block", ",", "new_db", ",", "expected_snapshots", "=", "expected_snapshots", ",", "*", "*", "virtualchain_args", ")", "BlockstackDB", ".", "release_readwrite_instance", "(", "new_db", ",", "last_block", ")", "return", "rc" ]
Calls a piece of code with the DOM element that corresponds to a search field of the table .
def call_with_search_field ( self , name , callback ) : done = False while not done : def check ( * _ ) : if name in self . _search_fields : return True # Force a refetch self . _found_fields = None return False self . util . wait ( check ) field = self . _search_fields [ name ] try : callback ( field ) done = True except StaleElementReferenceException : # We force a refetch of the fields self . _found_fields = None
7,707
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/tables.py#L121-L154
[ "def", "create_api_client", "(", "api", "=", "'BatchV1'", ")", ":", "k8s_config", ".", "load_incluster_config", "(", ")", "api_configuration", "=", "client", ".", "Configuration", "(", ")", "api_configuration", ".", "verify_ssl", "=", "False", "if", "api", "==", "'extensions/v1beta1'", ":", "api_client", "=", "client", ".", "ExtensionsV1beta1Api", "(", ")", "elif", "api", "==", "'CoreV1'", ":", "api_client", "=", "client", ".", "CoreV1Api", "(", ")", "elif", "api", "==", "'StorageV1'", ":", "api_client", "=", "client", ".", "StorageV1Api", "(", ")", "else", ":", "api_client", "=", "client", ".", "BatchV1Api", "(", ")", "return", "api_client" ]
Return the conversion from keys and modifiers to Qt constants .
def determine_keymap ( qteMain = None ) : if qteMain is None : # This case should only happen for testing purposes. qte_global . Qt_key_map = default_qt_keymap qte_global . Qt_modifier_map = default_qt_modifier_map else : doc = 'Conversion table from local characters to Qt constants' qteMain . qteDefVar ( "Qt_key_map" , default_qt_keymap , doc = doc ) doc = 'Conversion table from local modifier keys to Qt constants' qteMain . qteDefVar ( "Qt_modifier_map" , default_qt_modifier_map , doc = doc )
7,708
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/platform_setup.py#L158-L178
[ "def", "run", "(", "self", ",", "peer_table", "=", "None", ")", ":", "self", ".", "running", "=", "True", "while", "self", ".", "running", ":", "local_inv", "=", "atlas_get_zonefile_inventory", "(", ")", "t1", "=", "time_now", "(", ")", "self", ".", "step", "(", "peer_table", "=", "peer_table", ",", "local_inv", "=", "local_inv", ",", "path", "=", "self", ".", "atlasdb_path", ")", "t2", "=", "time_now", "(", ")", "# don't go too fast ", "if", "t2", "-", "t1", "<", "PEER_HEALTH_NEIGHBOR_WORK_INTERVAL", ":", "deadline", "=", "time_now", "(", ")", "+", "PEER_HEALTH_NEIGHBOR_WORK_INTERVAL", "-", "(", "t2", "-", "t1", ")", "while", "time_now", "(", ")", "<", "deadline", "and", "self", ".", "running", ":", "time_sleep", "(", "self", ".", "hostport", ",", "self", ".", "__class__", ".", "__name__", ",", "1.0", ")", "if", "not", "self", ".", "running", ":", "break" ]
r Print your name .
def func ( name ) : # Raise condition evaluated in same call as exception addition pexdoc . addex ( TypeError , "Argument `name` is not valid" , not isinstance ( name , str ) ) return "My name is {0}" . format ( name )
7,709
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/docs/support/my_module.py#L20-L33
[ "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" ]
Disable yank - pop .
def disableHook ( self , msgObj ) : # Unpack the data structure. macroName , keysequence = msgObj . data if macroName != self . qteMacroName ( ) : self . qteMain . qtesigKeyseqComplete . disconnect ( self . disableHook ) self . killListIdx = - 1
7,710
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L912-L928
[ "def", "store_contents", "(", "self", ")", ":", "string_buffer", "=", "os", ".", "linesep", ".", "join", "(", "map", "(", "lambda", "x", ":", "os", ".", "linesep", ".", "join", "(", "[", "\"<begin_table>\"", "]", "+", "[", "x", ".", "name", "]", "+", "x", ".", "columns", "+", "[", "\"<end_table>\"", "]", ")", ",", "self", ".", "tables", ")", ")", "with", "open", "(", "METADATA_FILE", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "string_buffer", ")", "for", "i", "in", "self", ".", "tables", ":", "i", ".", "store_contents", "(", ")" ]
Restore the original style properties of all matches .
def clearHighlighting ( self ) : SCI = self . qteWidget self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) # Clear out the match set and reset the match index. self . selMatchIdx = 1 self . matchList = [ ]
7,711
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1449-L1461
[ "def", "aux", "(", "self", ",", "aux", ")", ":", "if", "aux", "==", "self", ".", "_aux", ":", "return", "if", "self", ".", "_aux", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_aux", ",", "self", ".", "_project", ")", "self", ".", "_aux", "=", "None", "if", "aux", "is", "not", "None", ":", "self", ".", "_aux", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "aux", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: aux port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "aux", ")", ")" ]
Select and highlight the next match in the set of matches .
def highlightNextMatch ( self ) : # If this method was called on an empty input field (ie. # if the user hit <ctrl>+s again) then pick the default # selection. if self . qteText . toPlainText ( ) == '' : self . qteText . setText ( self . defaultChoice ) return # If the mathIdx variable is out of bounds (eg. the last possible # match is already selected) then wrap it around. if self . selMatchIdx < 0 : self . selMatchIdx = 0 return if self . selMatchIdx >= len ( self . matchList ) : self . selMatchIdx = 0 return # Shorthand. SCI = self . qteWidget # Undo the highlighting of the previously selected match. start , stop = self . matchList [ self . selMatchIdx - 1 ] line , col = SCI . lineIndexFromPosition ( start ) SCI . SendScintilla ( SCI . SCI_STARTSTYLING , start , 0xFF ) SCI . SendScintilla ( SCI . SCI_SETSTYLING , stop - start , 30 ) # Highlight the next match. start , stop = self . matchList [ self . selMatchIdx ] SCI . SendScintilla ( SCI . SCI_STARTSTYLING , start , 0xFF ) SCI . SendScintilla ( SCI . SCI_SETSTYLING , stop - start , 31 ) # Place the cursor at the start of the currently selected match. line , col = SCI . lineIndexFromPosition ( start ) SCI . setCursorPosition ( line , col ) self . selMatchIdx += 1
7,712
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1463-L1500
[ "def", "remove_organization", "(", "self", ",", "service_desk_id", ",", "organization_id", ")", ":", "log", ".", "warning", "(", "'Removing organization...'", ")", "url", "=", "'rest/servicedeskapi/servicedesk/{}/organization'", ".", "format", "(", "service_desk_id", ")", "data", "=", "{", "'organizationId'", ":", "organization_id", "}", "return", "self", ".", "delete", "(", "url", ",", "headers", "=", "self", ".", "experimental_headers", ",", "data", "=", "data", ")" ]
Put the search - replace macro into the next stage . The first stage is the query stage to ask the user for the string to replace the second stage is to query the string to replace it with and the third allows to replace or skip individual matches or replace them all automatically .
def nextMode ( self ) : # Terminate the replacement procedure if the no match was found. if len ( self . matchList ) == 0 : self . qteAbort ( QtmacsMessage ( ) ) self . qteMain . qteKillMiniApplet ( ) return self . queryMode += 1 if self . queryMode == 1 : # Disconnect the text-changed slot because no real time # highlighting is necessary when entering the replacement # string, unlike when entering the string to replace. self . qteText . textChanged . disconnect ( self . qteTextChanged ) # Store the string to replace and clear out the query field. self . toReplace = self . qteText . toPlainText ( ) self . qteText . clear ( ) self . qteTextPrefix . setText ( 'mode 1' ) elif self . queryMode == 2 : # Mode two is to replace or skip individual matches. For # this purpose rebind the "n", "!", and <space> keys # with the respective macros to facilitate it. register = self . qteMain . qteRegisterMacro bind = self . qteMain . qteBindKeyWidget # Unbind all keys from the input widget. self . qteMain . qteUnbindAllFromWidgetObject ( self . qteText ) macroName = register ( self . ReplaceAll , replaceMacro = True ) bind ( '!' , macroName , self . qteText ) macroName = register ( self . ReplaceNext , replaceMacro = True ) bind ( '<space>' , macroName , self . qteText ) macroName = register ( self . SkipNext , replaceMacro = True ) bind ( 'n' , macroName , self . qteText ) macroName = register ( self . Abort , replaceMacro = True ) bind ( 'q' , macroName , self . qteText ) bind ( '<enter>' , macroName , self . qteText ) self . toReplaceWith = self . qteText . toPlainText ( ) self . qteTextPrefix . setText ( 'mode 2' ) self . qteText . setText ( '<space> to replace, <n> to skip, ' '<!> to replace all.' ) else : self . qteAbort ( QtmacsMessage ( ) ) self . qteMain . qteKillMiniApplet ( )
7,713
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1878-L1932
[ "def", "del_restriction", "(", "self", ",", "command", ",", "user", ",", "event_types", ")", ":", "if", "user", ".", "lower", "(", ")", "in", "self", ".", "commands_rights", "[", "command", "]", ":", "for", "event_type", "in", "event_types", ":", "try", ":", "self", ".", "commands_rights", "[", "command", "]", "[", "user", ".", "lower", "(", ")", "]", ".", "remove", "(", "event_type", ")", "except", "ValueError", ":", "pass", "if", "not", "self", ".", "commands_rights", "[", "command", "]", "[", "user", ".", "lower", "(", ")", "]", ":", "self", ".", "commands_rights", "[", "command", "]", ".", "pop", "(", "user", ".", "lower", "(", ")", ")" ]
Replace all matches after the current cursor position .
def replaceAll ( self ) : while self . replaceSelected ( ) : pass self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) self . qteMain . qteKillMiniApplet ( )
7,714
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L2010-L2021
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Compile the list of spans of every match .
def compileMatchList ( self ) : # Get the new sub-string to search for. self . matchList = [ ] # Return immediately if the input field is empty. numChar = len ( self . toReplace ) if numChar == 0 : return # Compile a list of all sub-string spans. stop = 0 text = self . qteWidget . text ( ) while True : start = text . find ( self . toReplace , stop ) if start == - 1 : break else : stop = start + numChar self . matchList . append ( ( start , stop ) )
7,715
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L2023-L2044
[ "def", "loadInternalSheet", "(", "klass", ",", "p", ",", "*", "*", "kwargs", ")", ":", "vs", "=", "klass", "(", "p", ".", "name", ",", "source", "=", "p", ",", "*", "*", "kwargs", ")", "options", ".", "_set", "(", "'encoding'", ",", "'utf8'", ",", "vs", ")", "if", "p", ".", "exists", "(", ")", ":", "vd", ".", "sheets", ".", "insert", "(", "0", ",", "vs", ")", "vs", ".", "reload", ".", "__wrapped__", "(", "vs", ")", "vd", ".", "sheets", ".", "pop", "(", "0", ")", "return", "vs" ]
Replace the currently selected string with the new one .
def replaceSelected ( self ) : SCI = self . qteWidget # Restore the original styling. self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) # Select the region spanned by the string to replace. start , stop = self . matchList [ self . selMatchIdx ] line1 , col1 = SCI . lineIndexFromPosition ( start ) line2 , col2 = SCI . lineIndexFromPosition ( stop ) SCI . setSelection ( line1 , col1 , line2 , col2 ) text = SCI . selectedText ( ) text = re . sub ( self . toReplace , self . toReplaceWith , text ) # Replace that region with the new string and move the cursor # to the end of that string. SCI . replaceSelectedText ( text ) line , col = SCI . lineIndexFromPosition ( start + len ( text ) ) SCI . setCursorPosition ( line , col ) # Backup the new document style bits. line , col = SCI . getNumLinesAndColumns ( ) text , style = self . qteWidget . SCIGetStyledText ( ( 0 , 0 , line , col ) ) self . styleOrig = style # Determine if this was the last entry in the match list. if len ( self . matchList ) == self . selMatchIdx + 1 : return False else : self . highlightAllMatches ( ) return True
7,716
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L2176-L2214
[ "def", "usnjrnl_timeline", "(", "self", ")", ":", "filesystem_content", "=", "defaultdict", "(", "list", ")", "self", ".", "logger", ".", "debug", "(", "\"Extracting Update Sequence Number journal.\"", ")", "journal", "=", "self", ".", "_read_journal", "(", ")", "for", "dirent", "in", "self", ".", "_visit_filesystem", "(", ")", ":", "filesystem_content", "[", "dirent", ".", "inode", "]", ".", "append", "(", "dirent", ")", "self", ".", "logger", ".", "debug", "(", "\"Generating timeline.\"", ")", "yield", "from", "generate_timeline", "(", "journal", ",", "filesystem_content", ")" ]
Run Kalibrate for a band .
def scan_band ( self , band , * * kwargs ) : kal_run_line = fn . build_kal_scan_band_string ( self . kal_bin , band , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_scan ( raw_output ) return kal_normalized
7,717
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/kal.py#L20-L35
[ "def", "compose", "(", "list_of_files", ",", "destination_file", ",", "files_metadata", "=", "None", ",", "content_type", "=", "None", ",", "retry_params", "=", "None", ",", "_account_id", "=", "None", ")", ":", "api", "=", "storage_api", ".", "_get_storage_api", "(", "retry_params", "=", "retry_params", ",", "account_id", "=", "_account_id", ")", "if", "os", ".", "getenv", "(", "'SERVER_SOFTWARE'", ")", ".", "startswith", "(", "'Dev'", ")", ":", "def", "_temp_func", "(", "file_list", ",", "destination_file", ",", "content_type", ")", ":", "bucket", "=", "'/'", "+", "destination_file", ".", "split", "(", "'/'", ")", "[", "1", "]", "+", "'/'", "with", "open", "(", "destination_file", ",", "'w'", ",", "content_type", "=", "content_type", ")", "as", "gcs_merge", ":", "for", "source_file", "in", "file_list", ":", "with", "open", "(", "bucket", "+", "source_file", "[", "'Name'", "]", ",", "'r'", ")", "as", "gcs_source", ":", "gcs_merge", ".", "write", "(", "gcs_source", ".", "read", "(", ")", ")", "compose_object", "=", "_temp_func", "else", ":", "compose_object", "=", "api", ".", "compose_object", "file_list", ",", "_", "=", "_validate_compose_list", "(", "destination_file", ",", "list_of_files", ",", "files_metadata", ",", "32", ")", "compose_object", "(", "file_list", ",", "destination_file", ",", "content_type", ")" ]
Run Kalibrate .
def scan_channel ( self , channel , * * kwargs ) : kal_run_line = fn . build_kal_scan_channel_string ( self . kal_bin , channel , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_channel ( raw_output ) return kal_normalized
7,718
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/kal.py#L37-L52
[ "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.\"", ")" ]
Parse request path and return GET - vars
def get_vars ( self ) : if self . method ( ) != 'GET' : raise RuntimeError ( 'Unable to return get vars for non-get method' ) re_search = WWebRequestProto . get_vars_re . search ( self . path ( ) ) if re_search is not None : return urllib . parse . parse_qs ( re_search . group ( 1 ) , keep_blank_values = 1 )
7,719
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/proto.py#L139-L148
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Parse request payload and return POST - vars
def post_vars ( self ) : if self . method ( ) != 'POST' : raise RuntimeError ( 'Unable to return post vars for non-get method' ) content_type = self . content_type ( ) if content_type is None or content_type . lower ( ) != 'application/x-www-form-urlencoded' : raise RuntimeError ( 'Unable to return post vars with invalid content-type request' ) request_data = self . request_data ( ) request_data = request_data . decode ( ) if request_data is not None else '' re_search = WWebRequestProto . post_vars_re . search ( request_data ) if re_search is not None : return urllib . parse . parse_qs ( re_search . group ( 1 ) , keep_blank_values = 1 )
7,720
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/proto.py#L150-L166
[ "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" ]
Unite entries to generate a single path
def join_path ( self , * path ) : path = self . directory_sep ( ) . join ( path ) return self . normalize_path ( path )
7,721
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/virtual_dir.py#L77-L85
[ "def", "deserialize_footer", "(", "stream", ",", "verifier", "=", "None", ")", ":", "_LOGGER", ".", "debug", "(", "\"Starting footer deserialization\"", ")", "signature", "=", "b\"\"", "if", "verifier", "is", "None", ":", "return", "MessageFooter", "(", "signature", "=", "signature", ")", "try", ":", "(", "sig_len", ",", ")", "=", "unpack_values", "(", "\">H\"", ",", "stream", ")", "(", "signature", ",", ")", "=", "unpack_values", "(", "\">{sig_len}s\"", ".", "format", "(", "sig_len", "=", "sig_len", ")", ",", "stream", ")", "except", "SerializationError", ":", "raise", "SerializationError", "(", "\"No signature found in message\"", ")", "if", "verifier", ":", "verifier", ".", "verify", "(", "signature", ")", "return", "MessageFooter", "(", "signature", "=", "signature", ")" ]
Return a full path to a current session directory . A result is made by joining a start path with current session directory
def full_path ( self ) : return self . normalize_path ( self . directory_sep ( ) . join ( ( self . start_path ( ) , self . session_path ( ) ) ) )
7,722
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/virtual_dir.py#L105-L111
[ "def", "set_etag", "(", "self", ",", "etag", ",", "weak", "=", "False", ")", ":", "self", ".", "headers", "[", "\"ETag\"", "]", "=", "quote_etag", "(", "etag", ",", "weak", ")" ]
Run the model
def run ( self , * * kwargs ) : from calculate import compute self . app_main ( * * kwargs ) # get the default output name output = osp . join ( self . exp_config [ 'expdir' ] , 'output.dat' ) # save the paths in the configuration self . exp_config [ 'output' ] = output # run the model data = np . loadtxt ( self . exp_config [ 'infile' ] ) out = compute ( data ) # save the output self . logger . info ( 'Saving output data to %s' , osp . relpath ( output ) ) np . savetxt ( output , out ) # store some additional information in the configuration of the # experiment self . exp_config [ 'mean' ] = mean = float ( out . mean ( ) ) self . exp_config [ 'std' ] = std = float ( out . std ( ) ) self . logger . debug ( 'Mean: %s, Standard deviation: %s' , mean , std )
7,723
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/docs/square_full.py#L45-L75
[ "def", "ticks", "(", "self", ",", "security", ",", "start", ",", "end", ")", ":", "period", "=", "1", "# url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (security, interval, period, start)\r", "url", "=", "'http://www.google.com/finance/getprices?q=%s&i=61&p=%sd&f=d,o,h,l,c,v'", "%", "(", "security", ".", "symbol", ",", "period", ")", "LOG", ".", "debug", "(", "'fetching {0}'", ".", "format", "(", "url", ")", ")", "try", ":", "response", "=", "self", ".", "_request", "(", "url", ")", "except", "UfException", "as", "ufExcep", ":", "# if symol is not right, will get 400\r", "if", "Errors", ".", "NETWORK_400_ERROR", "==", "ufExcep", ".", "getCode", ":", "raise", "UfException", "(", "Errors", ".", "STOCK_SYMBOL_ERROR", ",", "\"Can find data for stock %s, security error?\"", "%", "security", ")", "raise", "ufExcep", "# use csv reader here\r", "days", "=", "response", ".", "text", ".", "split", "(", "'\\n'", ")", "[", "7", ":", "]", "# first 7 line is document\r", "# sample values:'a1316784600,31.41,31.5,31.4,31.43,150911'\r", "values", "=", "[", "day", ".", "split", "(", "','", ")", "for", "day", "in", "days", "if", "len", "(", "day", ".", "split", "(", "','", ")", ")", ">=", "6", "]", "for", "value", "in", "values", ":", "yield", "json", ".", "dumps", "(", "{", "'date'", ":", "value", "[", "0", "]", "[", "1", ":", "]", ".", "strip", "(", ")", ",", "'close'", ":", "value", "[", "1", "]", ".", "strip", "(", ")", ",", "'high'", ":", "value", "[", "2", "]", ".", "strip", "(", ")", ",", "'low'", ":", "value", "[", "3", "]", ".", "strip", "(", ")", ",", "'open'", ":", "value", "[", "4", "]", ".", "strip", "(", ")", ",", "'volume'", ":", "value", "[", "5", "]", ".", "strip", "(", ")", "}", ")" ]
Postprocess and visualize the data
def postproc ( self , close = True , * * kwargs ) : import matplotlib . pyplot as plt import seaborn as sns # for nice plot styles self . app_main ( * * kwargs ) # ---- load the data indata = np . loadtxt ( self . exp_config [ 'infile' ] ) outdata = np . loadtxt ( self . exp_config [ 'output' ] ) x_data = np . linspace ( - np . pi , np . pi ) # ---- make the plot fig = plt . figure ( ) # plot input data plt . plot ( x_data , indata , label = 'input' ) # plot output data plt . plot ( x_data , outdata , label = 'squared' ) # draw a legend plt . legend ( ) # use the description of the experiment as title plt . title ( self . exp_config . get ( 'description' ) ) # ---- save the plot self . exp_config [ 'plot' ] = ofile = osp . join ( self . exp_config [ 'expdir' ] , 'plot.png' ) self . logger . info ( 'Saving plot to %s' , osp . relpath ( ofile ) ) fig . savefig ( ofile ) if close : plt . close ( fig )
7,724
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/docs/square_full.py#L77-L116
[ "def", "acme_renew_certificates", "(", ")", ":", "for", "csr", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "CERTIFICATES_PATH", ",", "'*.csr'", ")", ")", ":", "common_name", "=", "os", ".", "path", ".", "basename", "(", "csr", ")", "common_name", "=", "os", ".", "path", ".", "splitext", "(", "common_name", ")", "[", "0", "]", "certificate_path", "=", "\"{}.crt\"", ".", "format", "(", "common_name", ")", "certificate_path", "=", "os", ".", "path", ".", "join", "(", "CERTIFICATES_PATH", ",", "certificate_path", ")", "with", "open", "(", "certificate_path", ")", "as", "file", ":", "crt", "=", "OpenSSL", ".", "crypto", ".", "load_certificate", "(", "OpenSSL", ".", "crypto", ".", "FILETYPE_PEM", ",", "file", ".", "read", "(", ")", ")", "expiration", "=", "crt", ".", "get_notAfter", "(", ")", "expiration", "=", "_parse_asn1_generalized_date", "(", "expiration", ")", "remaining", "=", "expiration", "-", "datetime", ".", "utcnow", "(", ")", "if", "remaining", ">", "timedelta", "(", "days", "=", "30", ")", ":", "print", "\"No need to renew {} ({})\"", ".", "format", "(", "certificate_path", ",", "remaining", ")", "continue", "print", "\"Renewing {} ({})\"", ".", "format", "(", "certificate_path", ",", "remaining", ")", "certificate_request_path", "=", "\"{}.csr\"", ".", "format", "(", "common_name", ")", "certificate_request_path", "=", "os", ".", "path", ".", "join", "(", "CERTIFICATES_PATH", ",", "certificate_request_path", ")", "signed_cert", "=", "\"{}-signed.crt\"", ".", "format", "(", "common_name", ")", "signed_cert", "=", "os", ".", "path", ".", "join", "(", "CERTIFICATES_PATH", ",", "signed_cert", ")", "_internal_sign_certificate", "(", "certificate_path", ",", "certificate_request_path", ",", "signed_cert", ")" ]
The actual method that adds the command object onto the stack .
def _push ( self , undoObj : QtmacsUndoCommand ) : self . _qteStack . append ( undoObj ) if undoObj . nextIsRedo : undoObj . commit ( ) else : undoObj . reverseCommit ( ) undoObj . nextIsRedo = not undoObj . nextIsRedo
7,725
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/undo_stack.py#L208-L230
[ "def", "sample_normal", "(", "mean", ",", "var", ",", "rng", ")", ":", "ret", "=", "numpy", ".", "sqrt", "(", "var", ")", "*", "rng", ".", "randn", "(", "*", "mean", ".", "shape", ")", "+", "mean", "return", "ret" ]
Add undoObj command to stack and run its commit method .
def push ( self , undoObj ) : # Check type of input arguments. if not isinstance ( undoObj , QtmacsUndoCommand ) : raise QtmacsArgumentError ( 'undoObj' , 'QtmacsUndoCommand' , inspect . stack ( ) [ 0 ] [ 3 ] ) # Flag that the last action was not an undo action and push # the command to the stack. self . _wasUndo = False self . _push ( undoObj )
7,726
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/undo_stack.py#L232-L256
[ "def", "build_agency", "(", "pfeed", ")", ":", "return", "pd", ".", "DataFrame", "(", "{", "'agency_name'", ":", "pfeed", ".", "meta", "[", "'agency_name'", "]", ".", "iat", "[", "0", "]", ",", "'agency_url'", ":", "pfeed", ".", "meta", "[", "'agency_url'", "]", ".", "iat", "[", "0", "]", ",", "'agency_timezone'", ":", "pfeed", ".", "meta", "[", "'agency_timezone'", "]", ".", "iat", "[", "0", "]", ",", "}", ",", "index", "=", "[", "0", "]", ")" ]
Undo the last command by adding its inverse action to the stack .
def undo ( self ) : # If it is the first call to this method after a ``push`` then # reset ``qteIndex`` to the last element, otherwise just # decrease it. if not self . _wasUndo : self . _qteIndex = len ( self . _qteStack ) else : self . _qteIndex -= 1 # Flag that the last action was an `undo` operation. self . _wasUndo = True if self . _qteIndex <= 0 : return # Make a copy of the command and push it to the stack. undoObj = self . _qteStack [ self . _qteIndex - 1 ] undoObj = QtmacsUndoCommand ( undoObj ) self . _push ( undoObj ) # If the just pushed undo object restored the last saved state # then trigger the ``qtesigSavedState`` signal and set the # _qteLastSaveUndoIndex variable again. This is necessary # because an undo command will not *remove* any elements from # the undo stack but *add* the inverse operation to the # stack. Therefore, when enough undo operations have been # performed to reach the last saved state that means that the # last addition to the stack is now implicitly the new last # save point. if ( self . _qteIndex - 1 ) == self . _qteLastSavedUndoIndex : self . qtesigSavedState . emit ( QtmacsMessage ( ) ) self . saveState ( )
7,727
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/undo_stack.py#L282-L350
[ "def", "add_etag", "(", "self", ",", "overwrite", "=", "False", ",", "weak", "=", "False", ")", ":", "if", "overwrite", "or", "\"etag\"", "not", "in", "self", ".", "headers", ":", "self", ".", "set_etag", "(", "generate_etag", "(", "self", ".", "get_data", "(", ")", ")", ",", "weak", ")" ]
Try to place the cursor in line at col if possible . If this is not possible then place it at the end .
def placeCursor ( self , pos ) : if pos > len ( self . qteWidget . toPlainText ( ) ) : pos = len ( self . qteWidget . toPlainText ( ) ) tc = self . qteWidget . textCursor ( ) tc . setPosition ( pos ) self . qteWidget . setTextCursor ( tc )
7,728
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L99-L109
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Reverse the document to the original state .
def reverseCommit ( self ) : print ( self . after == self . before ) pos = self . qteWidget . textCursor ( ) . position ( ) self . qteWidget . setHtml ( self . before ) self . placeCursor ( pos )
7,729
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L125-L132
[ "def", "calc_nearest_point", "(", "bus1", ",", "network", ")", ":", "bus1_index", "=", "network", ".", "buses", ".", "index", "[", "network", ".", "buses", ".", "index", "==", "bus1", "]", "forbidden_buses", "=", "np", ".", "append", "(", "bus1_index", ".", "values", ",", "network", ".", "lines", ".", "bus1", "[", "network", ".", "lines", ".", "bus0", "==", "bus1", "]", ".", "values", ")", "forbidden_buses", "=", "np", ".", "append", "(", "forbidden_buses", ",", "network", ".", "lines", ".", "bus0", "[", "network", ".", "lines", ".", "bus1", "==", "bus1", "]", ".", "values", ")", "forbidden_buses", "=", "np", ".", "append", "(", "forbidden_buses", ",", "network", ".", "links", ".", "bus0", "[", "network", ".", "links", ".", "bus1", "==", "bus1", "]", ".", "values", ")", "forbidden_buses", "=", "np", ".", "append", "(", "forbidden_buses", ",", "network", ".", "links", ".", "bus1", "[", "network", ".", "links", ".", "bus0", "==", "bus1", "]", ".", "values", ")", "x0", "=", "network", ".", "buses", ".", "x", "[", "network", ".", "buses", ".", "index", ".", "isin", "(", "bus1_index", ")", "]", "y0", "=", "network", ".", "buses", ".", "y", "[", "network", ".", "buses", ".", "index", ".", "isin", "(", "bus1_index", ")", "]", "comparable_buses", "=", "network", ".", "buses", "[", "~", "network", ".", "buses", ".", "index", ".", "isin", "(", "forbidden_buses", ")", "]", "x1", "=", "comparable_buses", ".", "x", "y1", "=", "comparable_buses", ".", "y", "distance", "=", "(", "x1", ".", "values", "-", "x0", ".", "values", ")", "*", "(", "x1", ".", "values", "-", "x0", ".", "values", ")", "+", "(", "y1", ".", "values", "-", "y0", ".", "values", ")", "*", "(", "y1", ".", "values", "-", "y0", ".", "values", ")", "min_distance", "=", "distance", ".", "min", "(", ")", "bus0", "=", "comparable_buses", "[", "(", "(", "(", "x1", ".", "values", "-", "x0", ".", "values", ")", "*", "(", "x1", ".", "values", "-", "x0", ".", "values", ")", "+", "(", "y1", ".", "values", "-", "y0", ".", "values", ")", "*", "(", "y1", ".", "values", "-", "y0", ".", "values", ")", ")", "==", "min_distance", ")", "]", "bus0", "=", "bus0", ".", "index", "[", "bus0", ".", "index", "==", "bus0", ".", "index", ".", "max", "(", ")", "]", "bus0", "=", "''", ".", "join", "(", "bus0", ".", "values", ")", "return", "bus0" ]
Paste the MIME data at the current cursor position .
def insertFromMimeData ( self , data ) : undoObj = UndoPaste ( self , data , self . pasteCnt ) self . pasteCnt += 1 self . qteUndoStack . push ( undoObj )
7,730
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L322-L330
[ "def", "delete_resource", "(", "self", ",", "resource", ",", "delete", "=", "True", ")", ":", "# type: (Union[hdx.data.resource.Resource,Dict,str], bool) -> bool", "if", "isinstance", "(", "resource", ",", "str", ")", ":", "if", "is_valid_uuid", "(", "resource", ")", "is", "False", ":", "raise", "HDXError", "(", "'%s is not a valid resource id!'", "%", "resource", ")", "return", "self", ".", "_remove_hdxobject", "(", "self", ".", "resources", ",", "resource", ",", "delete", "=", "delete", ")" ]
Insert the character at the current cursor position .
def keyPressEvent ( self , keyEvent ) : undoObj = UndoSelfInsert ( self , keyEvent . text ( ) ) self . qteUndoStack . push ( undoObj )
7,731
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L332-L339
[ "def", "update_swarm", "(", "self", ",", "version", ",", "swarm_spec", "=", "None", ",", "rotate_worker_token", "=", "False", ",", "rotate_manager_token", "=", "False", ")", ":", "url", "=", "self", ".", "_url", "(", "'/swarm/update'", ")", "response", "=", "self", ".", "_post_json", "(", "url", ",", "data", "=", "swarm_spec", ",", "params", "=", "{", "'rotateWorkerToken'", ":", "rotate_worker_token", ",", "'rotateManagerToken'", ":", "rotate_manager_token", ",", "'version'", ":", "version", "}", ")", "self", ".", "_raise_for_status", "(", "response", ")", "return", "True" ]
Get schemaVersion attribute from OpenMalaria scenario file xml - open file or content of xml document to be processed
def get_schema_version_from_xml ( xml ) : if isinstance ( xml , six . string_types ) : xml = StringIO ( xml ) try : tree = ElementTree . parse ( xml ) except ParseError : # Not an XML file return None root = tree . getroot ( ) return root . attrib . get ( 'schemaVersion' , None )
7,732
https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/__init__.py#L38-L50
[ "def", "namedtuple_storable", "(", "namedtuple", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "default_storable", "(", "namedtuple", ",", "namedtuple", ".", "_fields", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Given profile data and the name of a social media service format it for the zone file .
def format_account ( service_name , data ) : if "username" not in data : raise KeyError ( "Account is missing a username" ) account = { "@type" : "Account" , "service" : service_name , "identifier" : data [ "username" ] , "proofType" : "http" } if ( data . has_key ( service_name ) and data [ service_name ] . has_key ( "proof" ) and data [ service_name ] [ "proof" ] . has_key ( "url" ) ) : account [ "proofUrl" ] = data [ service_name ] [ "proof" ] [ "url" ] return account
7,733
https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/legacy_format.py#L63-L91
[ "def", "clean_value", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_clean_value", ":", "return", "self", ".", "_clean_value", "(", "value", ")", "else", ":", "return", "self", ".", "reduce_value", "(", "value", ")" ]
Mirror current array value in reverse . Bits 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 = WBinArray ( 0 , len ( self ) ) for i in range ( len ( self ) ) : result [ len ( self ) - i - 1 ] = self [ i ] return result
7,734
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/types/binarray.py#L233-L242
[ "def", "run_main_error_group", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "setup", "=", "[", "setup_phase", "]", ",", "main", "=", "[", "error_main_phase", ",", "main_phase", "]", ",", "teardown", "=", "[", "teardown_phase", "]", ",", ")", ")", "test", ".", "execute", "(", ")" ]
Creates an etcd client .
def etcd ( url = DEFAULT_URL , mock = False , * * kwargs ) : if mock : from etc . adapters . mock import MockAdapter adapter_class = MockAdapter else : from etc . adapters . etcd import EtcdAdapter adapter_class = EtcdAdapter return Client ( adapter_class ( url , * * kwargs ) )
7,735
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/__init__.py#L60-L68
[ "def", "SetConsoleTextAttribute", "(", "stream_id", ",", "attrs", ")", ":", "handle", "=", "handles", "[", "stream_id", "]", "return", "windll", ".", "kernel32", ".", "SetConsoleTextAttribute", "(", "handle", ",", "attrs", ")" ]
Tries a total of retries times to execute callable before failing .
def repeat_call ( func , retries , * args , * * kwargs ) : retries = max ( 0 , int ( retries ) ) try_num = 0 while True : if try_num == retries : return func ( * args , * * kwargs ) else : try : return func ( * args , * * kwargs ) except Exception as e : if isinstance ( e , KeyboardInterrupt ) : raise e try_num += 1
7,736
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/operators.py#L15-L30
[ "def", "stations", "(", "self", ",", "*", ",", "generated", "=", "True", ",", "library", "=", "True", ")", ":", "station_list", "=", "[", "]", "for", "chunk", "in", "self", ".", "stations_iter", "(", "page_size", "=", "49995", ")", ":", "for", "station", "in", "chunk", ":", "if", "(", "(", "generated", "and", "not", "station", ".", "get", "(", "'inLibrary'", ")", ")", "or", "(", "library", "and", "station", ".", "get", "(", "'inLibrary'", ")", ")", ")", ":", "station_list", ".", "append", "(", "station", ")", "return", "station_list" ]
Ensure arguments have the type specified in the annotation signature .
def type_check ( func_handle ) : def checkType ( var_name , var_val , annot ) : # Retrieve the annotation for this variable and determine # if the type of that variable matches with the annotation. # This annotation is stored in the dictionary ``annot`` # but contains only variables for such an annotation exists, # hence the if/else branch. if var_name in annot : # Fetch the type-annotation of the variable. var_anno = annot [ var_name ] # Skip the type check if the variable is none, otherwise # check if it is a derived class. The only exception from # the latter rule are binary values, because in Python # # >> isinstance(False, int) # True # # and warrants a special check. if var_val is None : type_ok = True elif ( type ( var_val ) is bool ) : type_ok = ( type ( var_val ) in var_anno ) else : type_ok = True in [ isinstance ( var_val , _ ) for _ in var_anno ] else : # Variable without annotation are compatible by assumption. var_anno = 'Unspecified' type_ok = True # If the check failed then raise a QtmacsArgumentError. if not type_ok : args = ( var_name , func_handle . __name__ , var_anno , type ( var_val ) ) raise QtmacsArgumentError ( * args ) @ functools . wraps ( func_handle ) def wrapper ( * args , * * kwds ) : # Retrieve information about all arguments passed to the function, # as well as their annotations in the function signature. argspec = inspect . getfullargspec ( func_handle ) # Convert all variable annotations that were not specified as a # tuple or list into one, eg. str --> will become (str,) annot = { } for key , val in argspec . annotations . items ( ) : if isinstance ( val , tuple ) or isinstance ( val , list ) : annot [ key ] = val else : annot [ key ] = val , # Note the trailing colon! # Prefix the argspec.defaults tuple with **None** elements to make # its length equal to the number of variables (for sanity in the # code below). Since **None** types are always ignored by this # decorator this change is neutral. if argspec . defaults is None : defaults = tuple ( [ None ] * len ( argspec . args ) ) else : num_none = len ( argspec . args ) - len ( argspec . defaults ) defaults = tuple ( [ None ] * num_none ) + argspec . defaults # Shorthand for the number of unnamed arguments. ofs = len ( args ) # Process the unnamed arguments. These are always the first ``ofs`` # elements in argspec.args. for idx , var_name in enumerate ( argspec . args [ : ofs ] ) : # Look up the value in the ``args`` variable. var_val = args [ idx ] checkType ( var_name , var_val , annot ) # Process the named- and default arguments. for idx , var_name in enumerate ( argspec . args [ ofs : ] ) : # Extract the argument value. If it was passed to the # function as a named (ie. keyword) argument then extract # it from ``kwds``, otherwise look it up in the tuple with # the default values. if var_name in kwds : var_val = kwds [ var_name ] else : var_val = defaults [ idx + ofs ] checkType ( var_name , var_val , annot ) return func_handle ( * args , * * kwds ) return wrapper
7,737
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/type_check.py#L41-L158
[ "def", "end_headers", "(", "self", ")", ":", "if", "self", ".", "request_version", "!=", "'HTTP/0.9'", ":", "self", ".", "_headers_buffer", ".", "append", "(", "b\"\\r\\n\"", ")", "self", ".", "flush_headers", "(", ")" ]
Set up handler and start loop
def start ( self ) : timeout = self . timeout ( ) if timeout is not None and timeout > 0 : self . __loop . add_timeout ( timedelta ( 0 , timeout ) , self . stop ) self . handler ( ) . setup_handler ( self . loop ( ) ) self . loop ( ) . start ( ) self . handler ( ) . loop_stopped ( )
7,738
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/service.py#L104-L114
[ "def", "GetAttachmentIdFromMediaId", "(", "media_id", ")", ":", "altchars", "=", "'+-'", "if", "not", "six", ".", "PY2", ":", "altchars", "=", "altchars", ".", "encode", "(", "'utf-8'", ")", "# altchars for '+' and '/'. We keep '+' but replace '/' with '-'", "buffer", "=", "base64", ".", "b64decode", "(", "str", "(", "media_id", ")", ",", "altchars", ")", "resoure_id_length", "=", "20", "attachment_id", "=", "''", "if", "len", "(", "buffer", ")", ">", "resoure_id_length", ":", "# We are cutting off the storage index.", "attachment_id", "=", "base64", ".", "b64encode", "(", "buffer", "[", "0", ":", "resoure_id_length", "]", ",", "altchars", ")", "if", "not", "six", ".", "PY2", ":", "attachment_id", "=", "attachment_id", ".", "decode", "(", "'utf-8'", ")", "else", ":", "attachment_id", "=", "media_id", "return", "attachment_id" ]
Terminate socket connection because of stopping loop
def loop_stopped ( self ) : transport = self . transport ( ) if self . server_mode ( ) is True : transport . close_server_socket ( self . config ( ) ) else : transport . close_client_socket ( self . config ( ) )
7,739
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/service.py#L248-L257
[ "def", "roles_dict", "(", "path", ",", "repo_prefix", "=", "\"\"", ",", "repo_sub_dir", "=", "\"\"", ")", ":", "exit_if_path_not_found", "(", "path", ")", "aggregated_roles", "=", "{", "}", "roles", "=", "os", ".", "walk", "(", "path", ")", ".", "next", "(", ")", "[", "1", "]", "# First scan all directories", "for", "role", "in", "roles", ":", "for", "sub_role", "in", "roles_dict", "(", "path", "+", "\"/\"", "+", "role", ",", "repo_prefix", "=", "\"\"", ",", "repo_sub_dir", "=", "role", "+", "\"/\"", ")", ":", "aggregated_roles", "[", "role", "+", "\"/\"", "+", "sub_role", "]", "=", "role", "+", "\"/\"", "+", "sub_role", "# Then format them", "for", "role", "in", "roles", ":", "if", "is_role", "(", "os", ".", "path", ".", "join", "(", "path", ",", "role", ")", ")", ":", "if", "isinstance", "(", "role", ",", "basestring", ")", ":", "role_repo", "=", "\"{0}{1}\"", ".", "format", "(", "repo_prefix", ",", "role_name", "(", "role", ")", ")", "aggregated_roles", "[", "role", "]", "=", "role_repo", "return", "aggregated_roles" ]
Sometimes it is necessary to drop undelivered messages . These messages may be stored in different caches for example in a zmq socket queue . With different zmq flags we can tweak zmq sockets and contexts no to keep those messages . But inside ZMQStream class there is a queue that can not be cleaned other way then the way it does in this method . So yes it is dirty to access protected members and yes it can be broken at any moment . And yes without correct locking procedure there is a possibility of unpredicted behaviour . But still - there is no other way to drop undelivered messages
def discard_queue_messages ( self ) : zmq_stream_queue = self . handler ( ) . stream ( ) . _send_queue while not zmq_stream_queue . empty ( ) : try : zmq_stream_queue . get ( False ) except queue . Empty : continue zmq_stream_queue . task_done ( )
7,740
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/service.py#L402-L421
[ "def", "_decode_pax_field", "(", "self", ",", "value", ",", "encoding", ",", "fallback_encoding", ",", "fallback_errors", ")", ":", "try", ":", "return", "value", ".", "decode", "(", "encoding", ",", "\"strict\"", ")", "except", "UnicodeDecodeError", ":", "return", "value", ".", "decode", "(", "fallback_encoding", ",", "fallback_errors", ")" ]
If the key completes a valid key sequence then queue the associated macro .
def qteProcessKey ( self , event , targetObj ) : # Announce the key and targeted Qtmacs widget. msgObj = QtmacsMessage ( ( targetObj , event ) , None ) msgObj . setSignalName ( 'qtesigKeypressed' ) self . qteMain . qtesigKeypressed . emit ( msgObj ) # Ignore standalone <Shift>, <Ctrl>, <Win>, <Alt>, and <AltGr> # events. if event . key ( ) in ( QtCore . Qt . Key_Shift , QtCore . Qt . Key_Control , QtCore . Qt . Key_Meta , QtCore . Qt . Key_Alt , QtCore . Qt . Key_AltGr ) : return False # Add the latest key stroke to the current key sequence. self . _keysequence . appendQKeyEvent ( event ) # Determine if the widget was registered with qteAddWidget isRegisteredWidget = hasattr ( targetObj , '_qteAdmin' ) if isRegisteredWidget and hasattr ( targetObj . _qteAdmin , 'keyMap' ) : keyMap = targetObj . _qteAdmin . keyMap else : keyMap = self . qteMain . _qteGlobalKeyMapByReference ( ) # See if there is a match with an entry from the key map of # the current object. If ``isPartialMatch`` is True then the # key sequence is potentially incomplete, but not invalid. # If ``macroName`` is not **None** then it is indeed complete. ( macroName , isPartialMatch ) = keyMap . match ( self . _keysequence ) # Make a convenience copy of the key sequence. keyseq_copy = QtmacsKeysequence ( self . _keysequence ) if isPartialMatch : # Reset the key combination history if a valid macro was # found so that the next key that arrives starts a new key # sequence. if macroName is None : # Report a partially completed key-sequence. msgObj = QtmacsMessage ( keyseq_copy , None ) msgObj . setSignalName ( 'qtesigKeyseqPartial' ) self . qteMain . qtesigKeyseqPartial . emit ( msgObj ) else : # Execute the macro if requested. if self . _qteFlagRunMacro : self . qteMain . qteRunMacro ( macroName , targetObj , keyseq_copy ) # Announce that the key sequence lead to a valid macro. msgObj = QtmacsMessage ( ( macroName , keyseq_copy ) , None ) msgObj . setSignalName ( 'qtesigKeyseqComplete' ) self . qteMain . qtesigKeyseqComplete . emit ( msgObj ) self . _keysequence . reset ( ) else : if isRegisteredWidget : # Announce (and log) that the key sequence is invalid. However, # format the key string to Html first, eg. "<ctrl>-x i" to # "<b>&lt;Ctrl&gt;+x i</b>". tmp = keyseq_copy . toString ( ) tmp = tmp . replace ( '<' , '&lt;' ) tmp = tmp . replace ( '>' , '&gt;' ) msg = 'No macro is bound to <b>{}</b>.' . format ( tmp ) self . qteMain . qteLogger . warning ( msg ) msgObj = QtmacsMessage ( keyseq_copy , None ) msgObj . setSignalName ( 'qtesigKeyseqInvalid' ) self . qteMain . qtesigKeyseqInvalid . emit ( msgObj ) else : # If we are in this branch then the widet is part of the # Qtmacs widget hierachy yet was not registered with # the qteAddWidget method. In this case use the QtDelivery # macro to pass on whatever the event was (assuming # macro processing is enabled). if self . _qteFlagRunMacro : self . qteMain . qteRunMacro ( self . QtDelivery , targetObj , keyseq_copy ) self . _keysequence . reset ( ) # Announce that Qtmacs has processed another key event. The # outcome of this processing is communicated along with the # signal. msgObj = QtmacsMessage ( ( targetObj , keyseq_copy , macroName ) , None ) msgObj . setSignalName ( 'qtesigKeyparsed' ) self . qteMain . qtesigKeyparsed . emit ( msgObj ) return isPartialMatch
7,741
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L345-L447
[ "def", "sample_statements", "(", "stmts", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "numpy", ".", "random", ".", "seed", "(", "seed", ")", "new_stmts", "=", "[", "]", "r", "=", "numpy", ".", "random", ".", "rand", "(", "len", "(", "stmts", ")", ")", "for", "i", ",", "stmt", "in", "enumerate", "(", "stmts", ")", ":", "if", "r", "[", "i", "]", "<", "stmt", ".", "belief", ":", "new_stmts", ".", "append", "(", "stmt", ")", "return", "new_stmts" ]
Adjust the widget size inside the splitter according to handlePos .
def qteAdjustWidgetSizes ( self , handlePos : int = None ) : # Do not adjust anything if there are less than two widgets. if self . count ( ) < 2 : return if self . orientation ( ) == QtCore . Qt . Horizontal : totDim = self . size ( ) . width ( ) - self . handleWidth ( ) else : totDim = self . size ( ) . height ( ) - self . handleWidth ( ) # Assign both widgets the same size if no handle position provided. if handlePos is None : handlePos = ( totDim + self . handleWidth ( ) ) // 2 # Sanity check. if not ( 0 <= handlePos <= totDim ) : return # Compute widget sizes according to handle position. newSize = [ handlePos , totDim - handlePos ] # Assign the widget sizes. self . setSizes ( newSize )
7,742
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L569-L611
[ "def", "_write_cert_to_database", "(", "ca_name", ",", "cert", ",", "cacert_path", "=", "None", ",", "status", "=", "'V'", ")", ":", "set_ca_path", "(", "cacert_path", ")", "ca_dir", "=", "'{0}/{1}'", ".", "format", "(", "cert_base_path", "(", ")", ",", "ca_name", ")", "index_file", ",", "expire_date", ",", "serial_number", ",", "subject", "=", "_get_basic_info", "(", "ca_name", ",", "cert", ",", "ca_dir", ")", "index_data", "=", "'{0}\\t{1}\\t\\t{2}\\tunknown\\t{3}'", ".", "format", "(", "status", ",", "expire_date", ",", "serial_number", ",", "subject", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "index_file", ",", "'a+'", ")", "as", "ofile", ":", "ofile", ".", "write", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "index_data", ")", ")" ]
Add a widget to the splitter and make it visible .
def qteAddWidget ( self , widget ) : # Add ``widget`` to the splitter. self . addWidget ( widget ) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : widget . show ( ) else : widget . show ( True ) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self . qteAdjustWidgetSizes ( )
7,743
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L613-L654
[ "def", "extract_self_cert", "(", "signed_raw", ":", "str", ")", "->", "Identity", ":", "lines", "=", "signed_raw", ".", "splitlines", "(", "True", ")", "n", "=", "0", "version", "=", "int", "(", "Revocation", ".", "parse_field", "(", "\"Version\"", ",", "lines", "[", "n", "]", ")", ")", "n", "+=", "1", "Revocation", ".", "parse_field", "(", "\"Type\"", ",", "lines", "[", "n", "]", ")", "n", "+=", "1", "currency", "=", "Revocation", ".", "parse_field", "(", "\"Currency\"", ",", "lines", "[", "n", "]", ")", "n", "+=", "1", "issuer", "=", "Revocation", ".", "parse_field", "(", "\"Issuer\"", ",", "lines", "[", "n", "]", ")", "n", "+=", "1", "unique_id", "=", "Revocation", ".", "parse_field", "(", "\"IdtyUniqueID\"", ",", "lines", "[", "n", "]", ")", "n", "+=", "1", "timestamp", "=", "Revocation", ".", "parse_field", "(", "\"IdtyTimestamp\"", ",", "lines", "[", "n", "]", ")", "n", "+=", "1", "signature", "=", "Revocation", ".", "parse_field", "(", "\"IdtySignature\"", ",", "lines", "[", "n", "]", ")", "n", "+=", "1", "return", "Identity", "(", "version", ",", "currency", ",", "issuer", ",", "unique_id", ",", "timestamp", ",", "signature", ")" ]
Insert widget to the splitter at the specified idx position and make it visible .
def qteInsertWidget ( self , idx , widget ) : # Insert the widget into the splitter. self . insertWidget ( idx , widget ) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : widget . show ( ) else : widget . show ( True ) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self . qteAdjustWidgetSizes ( )
7,744
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L656-L700
[ "def", "_get_csr_extensions", "(", "csr", ")", ":", "ret", "=", "OrderedDict", "(", ")", "csrtempfile", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "csrtempfile", ".", "write", "(", "csr", ".", "as_pem", "(", ")", ")", "csrtempfile", ".", "flush", "(", ")", "csryaml", "=", "_parse_openssl_req", "(", "csrtempfile", ".", "name", ")", "csrtempfile", ".", "close", "(", ")", "if", "csryaml", "and", "'Requested Extensions'", "in", "csryaml", "[", "'Certificate Request'", "]", "[", "'Data'", "]", ":", "csrexts", "=", "csryaml", "[", "'Certificate Request'", "]", "[", "'Data'", "]", "[", "'Requested Extensions'", "]", "if", "not", "csrexts", ":", "return", "ret", "for", "short_name", ",", "long_name", "in", "six", ".", "iteritems", "(", "EXT_NAME_MAPPINGS", ")", ":", "if", "long_name", "in", "csrexts", ":", "csrexts", "[", "short_name", "]", "=", "csrexts", "[", "long_name", "]", "del", "csrexts", "[", "long_name", "]", "ret", "=", "csrexts", "return", "ret" ]
Trigger the focus manager and work off all queued macros .
def timerEvent ( self , event ) : self . killTimer ( event . timerId ( ) ) if event . timerId ( ) == self . _qteTimerRunMacro : # Declare the macro execution timer event handled. self . _qteTimerRunMacro = None # If we are in this branch then the focus manager was just # executed, the event loop has updated all widgets and # cleared out all signals, and there is at least one macro # in the macro queue and/or at least one key to emulate # in the key queue. Execute the macros/keys and trigger # the focus manager after each. The macro queue is cleared # out first and the keys are only emulated if no more # macros are left. while True : if len ( self . _qteMacroQueue ) > 0 : ( macroName , qteWidget , event ) = self . _qteMacroQueue . pop ( 0 ) self . _qteRunQueuedMacro ( macroName , qteWidget , event ) elif len ( self . _qteKeyEmulationQueue ) > 0 : # Determine the recipient of the event. This can # be, in order of preference, the active widget in # the active applet, or just the active applet (if # it has no widget inside), or the active window # (if no applets are available). if self . _qteActiveApplet is None : receiver = self . qteActiveWindow ( ) else : if self . _qteActiveApplet . _qteActiveWidget is None : receiver = self . _qteActiveApplet else : receiver = self . _qteActiveApplet . _qteActiveWidget # Call the event filter directly and trigger the focus # manager again. keysequence = self . _qteKeyEmulationQueue . pop ( 0 ) self . _qteEventFilter . eventFilter ( receiver , keysequence ) else : # If we are in this branch then no more macros are left # to run. So trigger the focus manager one more time # and then leave the while-loop. self . _qteFocusManager ( ) break self . _qteFocusManager ( ) elif event . timerId ( ) == self . debugTimer : #win = self.qteNextWindow() #self.qteMakeWindowActive(win) #self.debugTimer = self.startTimer(1000) pass else : # Should not happen. print ( 'Unknown timer ID' ) pass
7,745
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1003-L1078
[ "def", "native_libraries_verify", "(", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "REVISION", ")", "with", "open", "(", "BINARY_EXT_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"docs/python/binary-extension.rst.actual\"", ",", "\"docs/python/binary-extension.rst.expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"docs/python/binary-extension.rst contents are as expected.\"", ")" ]
Update the Qtmacs internal focus state as the result of a mouse click .
def _qteMouseClicked ( self , widgetObj ) : # ------------------------------------------------------------ # The following cases for widgetObj have to be distinguished: # 1: not part of the Qtmacs widget hierarchy # 2: part of the Qtmacs widget hierarchy but not registered # 3: registered with Qtmacs and an applet # 4: registered with Qtmacs and anything but an applet # ------------------------------------------------------------ # Case 1: return immediately if widgetObj is not part of the # Qtmacs widget hierarchy; otherwise, declare the applet # containing the widgetObj active. app = qteGetAppletFromWidget ( widgetObj ) if app is None : return else : self . _qteActiveApplet = app # Case 2: unregistered widgets are activated immediately. if not hasattr ( widgetObj , '_qteAdmin' ) : self . _qteActiveApplet . qteMakeWidgetActive ( widgetObj ) else : if app . _qteAdmin . isQtmacsApplet : # Case 3: widgetObj is a QtmacsApplet instance; do not # focus any of its widgets as the focus manager will # take care of it. self . _qteActiveApplet . qteMakeWidgetActive ( None ) else : # Case 4: widgetObj was registered with qteAddWidget # and can thus be focused directly. self . _qteActiveApplet . qteMakeWidgetActive ( widgetObj ) # Trigger the focus manager. self . _qteFocusManager ( )
7,746
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1286-L1335
[ "def", "load_clients", "(", "stream", ",", "configuration_class", "=", "ClientConfiguration", ")", ":", "client_dict", "=", "yaml", ".", "safe_load", "(", "stream", ")", "if", "isinstance", "(", "client_dict", ",", "dict", ")", ":", "return", "{", "client_name", ":", "configuration_class", "(", "*", "*", "client_config", ")", "for", "client_name", ",", "client_config", "in", "six", ".", "iteritems", "(", "client_dict", ")", "}", "raise", "ValueError", "(", "\"Valid configuration could not be decoded.\"", ")" ]
Slot for Qt native focus - changed signal to notify Qtmacs if the window was switched .
def qteFocusChanged ( self , old , new ) : # Do nothing if new is old. if old is new : return # If neither is None but both have the same top level # window then do nothing. if ( old is not None ) and ( new is not None ) : if old . isActiveWindow ( ) is new . isActiveWindow ( ) : return
7,747
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1337-L1352
[ "def", "getCountry", "(", "self", ",", "default", "=", "None", ")", ":", "physical_address", "=", "self", ".", "getPhysicalAddress", "(", ")", ".", "get", "(", "\"country\"", ",", "default", ")", "postal_address", "=", "self", ".", "getPostalAddress", "(", ")", ".", "get", "(", "\"country\"", ",", "default", ")", "return", "physical_address", "or", "postal_address" ]
Test if instance obj is a mini applet .
def qteIsMiniApplet ( self , obj ) : try : ret = obj . _qteAdmin . isMiniApplet except AttributeError : ret = False return ret
7,748
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1407-L1428
[ "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" ]
Create a new empty window with windowID at position pos .
def qteNewWindow ( self , pos : QtCore . QRect = None , windowID : str = None ) : # Compile a list of all window IDs. winIDList = [ _ . _qteWindowID for _ in self . _qteWindowList ] # If no window ID was supplied simply count until a new and # unique ID was found. if windowID is None : cnt = 0 while str ( cnt ) in winIDList : cnt += 1 windowID = str ( cnt ) # If no position was specified use a default one. if pos is None : pos = QtCore . QRect ( 500 , 300 , 1000 , 500 ) # Raise an error if a window with this ID already exists. if windowID in winIDList : msg = 'Window with ID <b>{}</b> already exists.' . format ( windowID ) raise QtmacsOtherError ( msg ) # Instantiate a new window object. window = QtmacsWindow ( pos , windowID ) # Add the new window to the window list and make it visible. self . _qteWindowList . append ( window ) window . show ( ) # Trigger the focus manager once the event loop is in control again. return window
7,749
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1431-L1477
[ "def", "list_distributions", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "retries", "=", "10", "sleep", "=", "6", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "Items", "=", "[", "]", "while", "retries", ":", "try", ":", "log", ".", "debug", "(", "'Garnering list of CloudFront distributions'", ")", "Marker", "=", "''", "while", "Marker", "is", "not", "None", ":", "ret", "=", "conn", ".", "list_distributions", "(", "Marker", "=", "Marker", ")", "Items", "+=", "ret", ".", "get", "(", "'DistributionList'", ",", "{", "}", ")", ".", "get", "(", "'Items'", ",", "[", "]", ")", "Marker", "=", "ret", ".", "get", "(", "'DistributionList'", ",", "{", "}", ")", ".", "get", "(", "'NextMarker'", ")", "return", "Items", "except", "botocore", ".", "exceptions", ".", "ParamValidationError", "as", "err", ":", "raise", "SaltInvocationError", "(", "str", "(", "err", ")", ")", "except", "botocore", ".", "exceptions", ".", "ClientError", "as", "err", ":", "if", "retries", "and", "err", ".", "response", ".", "get", "(", "'Error'", ",", "{", "}", ")", ".", "get", "(", "'Code'", ")", "==", "'Throttling'", ":", "retries", "-=", "1", "log", ".", "debug", "(", "'Throttled by AWS API, retrying in %s seconds...'", ",", "sleep", ")", "time", ".", "sleep", "(", "sleep", ")", "continue", "log", ".", "error", "(", "'Failed to list CloudFront distributions: %s'", ",", "err", ".", "message", ")", "return", "None" ]
Make the window windowObj active and focus the first applet therein .
def qteMakeWindowActive ( self , windowObj : QtmacsWindow ) : if windowObj in self . _qteWindowList : # This will trigger the focusChanged slot which, in # conjunction with the focus manager, will take care of # the rest. Note that ``activateWindow`` is a native Qt # method, not a Qtmacs invention. windowObj . activateWindow ( ) else : self . qteLogger . warning ( 'Window to activate does not exist' )
7,750
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1480-L1505
[ "def", "recv", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Receiving'", ")", "try", ":", "message_length", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "message_length", "-=", "Connection", ".", "COMM_LENGTH", "LOGGER", ".", "debug", "(", "'Length: %i'", ",", "message_length", ")", "except", "socket", ".", "timeout", ":", "return", "None", "comm_status", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "LOGGER", ".", "debug", "(", "'Status: %i'", ",", "comm_status", ")", "bytes_received", "=", "0", "message", "=", "b\"\"", "while", "bytes_received", "<", "message_length", ":", "if", "message_length", "-", "bytes_received", ">=", "1024", ":", "recv_len", "=", "1024", "else", ":", "recv_len", "=", "message_length", "-", "bytes_received", "bytes_received", "+=", "recv_len", "LOGGER", ".", "debug", "(", "'Received %i'", ",", "bytes_received", ")", "message", "+=", "self", ".", "_socket", ".", "recv", "(", "recv_len", ")", "if", "comm_status", "==", "0", ":", "message", "=", "self", ".", "_crypt", ".", "decrypt", "(", "message", ")", "else", ":", "return", "Message", "(", "len", "(", "message", ")", ",", "Connection", ".", "COMM_ERROR", ",", "message", ")", "msg", "=", "Message", "(", "message_length", ",", "comm_status", ",", "message", ")", "return", "msg" ]
Return the currently active QtmacsWindow object .
def qteActiveWindow ( self ) : if len ( self . _qteWindowList ) == 0 : self . qteLogger . critical ( 'The window list is empty.' ) return None elif len ( self . _qteWindowList ) == 1 : return self . _qteWindowList [ 0 ] else : # Find the active window. for win in self . _qteWindowList : if win . isActiveWindow ( ) : return win # Return the first window if none is active. return self . _qteWindowList [ 0 ]
7,751
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1507-L1543
[ "def", "venv_metadata_extension", "(", "extraction_fce", ")", ":", "def", "inner", "(", "self", ")", ":", "data", "=", "extraction_fce", "(", "self", ")", "if", "virtualenv", "is", "None", "or", "not", "self", ".", "venv", ":", "logger", ".", "debug", "(", "\"Skipping virtualenv metadata extraction.\"", ")", "return", "data", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "extractor", "=", "virtualenv", ".", "VirtualEnv", "(", "self", ".", "name", ",", "temp_dir", ",", "self", ".", "name_convertor", ",", "self", ".", "base_python_version", ")", "data", ".", "set_from", "(", "extractor", ".", "get_venv_data", ",", "update", "=", "True", ")", "except", "exc", ".", "VirtualenvFailException", "as", "e", ":", "logger", ".", "error", "(", "\"{}, skipping virtualenv metadata extraction.\"", ".", "format", "(", "e", ")", ")", "finally", ":", "shutil", ".", "rmtree", "(", "temp_dir", ")", "return", "data", "return", "inner" ]
Return next window in cyclic order .
def qteNextWindow ( self ) : # Get the currently active window. win = self . qteActiveWindow ( ) if win in self . _qteWindowList : # Find the index of the window in the window list and # cyclically move to the next element in this list to find # the next window object. idx = self . _qteWindowList . index ( win ) idx = ( idx + 1 ) % len ( self . _qteWindowList ) return self . _qteWindowList [ idx ] else : msg = 'qteNextWindow method found a non-existing window.' self . qteLogger . warning ( msg ) return None
7,752
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1545-L1575
[ "def", "get_lab_managers_formatted_emails", "(", "self", ")", ":", "users", "=", "api", ".", "get_users_by_roles", "(", "\"LabManager\"", ")", "users", "=", "map", "(", "lambda", "user", ":", "(", "user", ".", "getProperty", "(", "\"fullname\"", ")", ",", "user", ".", "getProperty", "(", "\"email\"", ")", ")", ",", "users", ")", "return", "map", "(", "self", ".", "get_formatted_email", ",", "users", ")" ]
Return the next applet in cyclic order .
def qteNextApplet ( self , numSkip : int = 1 , ofsApp : ( QtmacsApplet , str ) = None , skipInvisible : bool = True , skipVisible : bool = False , skipMiniApplet : bool = True , windowObj : QtmacsWindow = None ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( ofsApp , str ) : ofsApp = self . qteGetAppletHandle ( ofsApp ) # Return immediately if the applet list is empty. if len ( self . _qteAppletList ) == 0 : return None # Sanity check: if the user requests applets that are neither # visible nor invisible then return immediately because no # such applet can possibly exist. if skipVisible and skipInvisible : return None # Make a copy of the applet list. appList = list ( self . _qteAppletList ) # Remove all invisible applets from the list if the # skipInvisible flag is set. if skipInvisible : appList = [ app for app in appList if app . qteIsVisible ( ) ] # From the list of (now guaranteed visible) applets remove # all those that are not in the specified window. if windowObj is not None : appList = [ app for app in appList if app . qteParentWindow ( ) == windowObj ] # Remove all visible applets from the list if the # skipInvisible flag is set. if skipVisible : appList = [ app for app in appList if not app . qteIsVisible ( ) ] # If the mini-buffer is to be skipped remove it (if a custom # mini applet even exists). if skipMiniApplet : if self . _qteMiniApplet in appList : appList . remove ( self . _qteMiniApplet ) # Return immediately if no applet satisfied all criteria. if len ( appList ) == 0 : return None # If no offset applet was given use the currently active one. if ofsApp is None : ofsApp = self . _qteActiveApplet if ofsApp in self . _qteAppletList : # Determine if the offset applet is part of the pruned # list. if ofsApp in appList : # Yes: determine its index in the list. ofsIdx = appList . index ( ofsApp ) else : # No: traverse all applets until one is found that is # also part of the pruned list (start at ofsIdx). Then # determine its index in the list. ofsIdx = self . _qteAppletList . index ( ofsApp ) glob_list = self . _qteAppletList [ ofsIdx : ] glob_list += self . _qteAppletList [ : ofsIdx ] # Compile the intersection between the global and pruned list. ofsIdx = [ appList . index ( _ ) for _ in glob_list if _ in appList ] if len ( ofsIdx ) == 0 : msg = ( 'No match between global and local applet list' ' --> Bug.' ) self . qteLogger . error ( msg , stack_info = True ) return None else : # Pick the first match. ofsIdx = ofsIdx [ 0 ] else : # The offset applet does not exist, eg. because the user # supplied a handle that does not point to an applet or # we are called from qteKillApplet to replace the just # removed (and active) applet. ofsIdx = 0 # Compute the index of the next applet and wrap around the # list if necessary. ofsIdx = ( ofsIdx + numSkip ) % len ( appList ) # Return a handle to the applet that meets the specified # criteria. return appList [ ofsIdx ]
7,753
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1672-L1809
[ "def", "modify_log_destinations", "(", "self", ",", "settings", ")", ":", "if", "not", "isinstance", "(", "settings", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"settings can only be an instance of type basestring\"", ")", "self", ".", "_call", "(", "\"modifyLogDestinations\"", ",", "in_p", "=", "[", "settings", "]", ")" ]
Queue a previously registered macro for execution once the event loop is idle .
def qteRunMacro ( self , macroName : str , widgetObj : QtGui . QWidget = None , keysequence : QtmacsKeysequence = None ) : # Add the new macro to the queue and call qteUpdate to ensure # that the macro is processed once the event loop is idle again. self . _qteMacroQueue . append ( ( macroName , widgetObj , keysequence ) ) self . qteUpdate ( )
7,754
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1812-L1844
[ "def", "setFaces", "(", "variant", ")", ":", "global", "FACES", "if", "variant", "==", "CHALDEAN_FACES", ":", "FACES", "=", "tables", ".", "CHALDEAN_FACES", "else", ":", "FACES", "=", "tables", ".", "TRIPLICITY_FACES" ]
Execute the next macro in the macro queue .
def _qteRunQueuedMacro ( self , macroName : str , widgetObj : QtGui . QWidget = None , keysequence : QtmacsKeysequence = None ) : # Fetch the applet holding the widget (this may be None). app = qteGetAppletFromWidget ( widgetObj ) # Double check that the applet still exists, unless there is # no applet (can happen when the windows are empty). if app is not None : if sip . isdeleted ( app ) : msg = 'Ignored macro <b>{}</b> because it targeted a' msg += ' nonexistent applet.' . format ( macroName ) self . qteLogger . warning ( msg ) return # Fetch a signature compatible macro object. macroObj = self . qteGetMacroObject ( macroName , widgetObj ) # Log an error if no compatible macro was found. if macroObj is None : msg = 'No <b>{}</b>-macro compatible with {}:{}-type applet' msg = msg . format ( macroName , app . qteAppletSignature ( ) , widgetObj . _qteAdmin . widgetSignature ) self . qteLogger . warning ( msg ) return # Update the 'last_key_sequence' variable in case the macros, # or slots triggered by that macro, have access to it. self . qteDefVar ( 'last_key_sequence' , keysequence , doc = "Last valid key sequence that triggered a macro." ) # Set some variables in the macro object for convenient access # from inside the macro. if app is None : macroObj . qteApplet = macroObj . qteWidget = None else : macroObj . qteApplet = app macroObj . qteWidget = widgetObj # Run the macro and trigger the focus manager. macroObj . qtePrepareToRun ( )
7,755
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1847-L1912
[ "def", "configure_splitevaluator", "(", "self", ")", ":", "if", "self", ".", "classification", ":", "speval", "=", "javabridge", ".", "make_instance", "(", "\"weka/experiment/ClassifierSplitEvaluator\"", ",", "\"()V\"", ")", "else", ":", "speval", "=", "javabridge", ".", "make_instance", "(", "\"weka/experiment/RegressionSplitEvaluator\"", ",", "\"()V\"", ")", "classifier", "=", "javabridge", ".", "call", "(", "speval", ",", "\"getClassifier\"", ",", "\"()Lweka/classifiers/Classifier;\"", ")", "return", "speval", ",", "classifier" ]
Create a new instance of appletName and assign it the appletID .
def qteNewApplet ( self , appletName : str , appletID : str = None , windowObj : QtmacsWindow = None ) : # Use the currently active window if none was specified. if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . error ( msg , stack_info = True ) return # Determine an automatic applet ID if none was provided. if appletID is None : cnt = 0 while True : appletID = appletName + '_' + str ( cnt ) if self . qteGetAppletHandle ( appletID ) is None : break else : cnt += 1 # Return immediately if an applet with the same ID already # exists. if self . qteGetAppletHandle ( appletID ) is not None : msg = 'Applet with ID <b>{}</b> already exists' . format ( appletID ) self . qteLogger . error ( msg , stack_info = True ) return None # Verify that the requested applet class was registered # beforehand and fetch it. if appletName not in self . _qteRegistryApplets : msg = 'Unknown applet <b>{}</b>' . format ( appletName ) self . qteLogger . error ( msg , stack_info = True ) return None else : cls = self . _qteRegistryApplets [ appletName ] # Try to instantiate the class. try : app = cls ( appletID ) except Exception : msg = 'Applet <b>{}</b> has a faulty constructor.' . format ( appletID ) self . qteLogger . exception ( msg , exc_info = True , stack_info = True ) return None # Ensure the applet class has an applet signature. if app . qteAppletSignature ( ) is None : msg = 'Cannot add applet <b>{}</b> ' . format ( app . qteAppletID ( ) ) msg += 'because it has not applet signature.' msg += ' Use self.qteSetAppletSignature in the constructor' msg += ' of the class to fix this.' self . qteLogger . error ( msg , stack_info = True ) return None # Add the applet to the list of instantiated Qtmacs applets. self . _qteAppletList . insert ( 0 , app ) # If the new applet does not yet have an internal layout then # arrange all its children automatically. The layout used for # this is horizontal and the widgets are added in the order in # which they were registered with Qtmacs. if app . layout ( ) is None : appLayout = QtGui . QHBoxLayout ( ) for handle in app . _qteAdmin . widgetList : appLayout . addWidget ( handle ) app . setLayout ( appLayout ) # Initially, the window does not have a parent. A parent will # be assigned automatically once the applet is made visible, # in which case it is re-parented into a QtmacsSplitter. app . qteReparent ( None ) # Emit the init hook for this applet. self . qteRunHook ( 'init' , QtmacsMessage ( None , app ) ) # Return applet handle. return app
7,756
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1915-L2022
[ "def", "clear_schema", "(", "self", ")", ":", "execute", "=", "self", ".", "cursor", ".", "execute", "execute", "(", "'TRUNCATE TABLE gauged_data'", ")", "execute", "(", "'TRUNCATE TABLE gauged_keys'", ")", "execute", "(", "'TRUNCATE TABLE gauged_writer_history'", ")", "execute", "(", "'TRUNCATE TABLE gauged_cache'", ")", "execute", "(", "'TRUNCATE TABLE gauged_statistics'", ")", "self", ".", "db", ".", "commit", "(", ")" ]
Install appletObj as the mini applet in the window layout .
def qteAddMiniApplet ( self , appletObj : QtmacsApplet ) : # Do nothing if a custom mini applet has already been # installed. if self . _qteMiniApplet is not None : msg = 'Cannot replace mini applet more than once.' self . qteLogger . warning ( msg ) return False # Arrange all registered widgets inside this applet # automatically if the mini applet object did not install its # own layout. if appletObj . layout ( ) is None : appLayout = QtGui . QHBoxLayout ( ) for handle in appletObj . _qteAdmin . widgetList : appLayout . addWidget ( handle ) appletObj . setLayout ( appLayout ) # Now that we have decided to install this mini applet, keep a # reference to it and set the mini applet flag in the # applet. This flag is necessary for some methods to separate # conventional applets from mini applets. appletObj . _qteAdmin . isMiniApplet = True self . _qteMiniApplet = appletObj # Shorthands. app = self . _qteActiveApplet appWin = self . qteActiveWindow ( ) # Remember which window and applet spawned this mini applet. self . _qteMiniApplet . _qteCallingApplet = app self . _qteMiniApplet . _qteCallingWindow = appWin del app # Add the mini applet to the applet registry, ie. for most # purposes the mini applet is treated like any other applet. self . _qteAppletList . insert ( 0 , self . _qteMiniApplet ) # Add the mini applet to the respective splitter in the window # layout and show it. appWin . qteLayoutSplitter . addWidget ( self . _qteMiniApplet ) self . _qteMiniApplet . show ( True ) # Give focus to first focusable widget in the mini applet # applet (if one exists) wid = self . _qteMiniApplet . qteNextWidget ( numSkip = 0 ) self . _qteMiniApplet . qteMakeWidgetActive ( wid ) self . qteMakeAppletActive ( self . _qteMiniApplet ) # Mini applet was successfully installed. return True
7,757
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2025-L2098
[ "def", "sponsored", "(", "self", ",", "*", "*", "kwargs", ")", ":", "eqs", "=", "self", ".", "search", "(", "*", "*", "kwargs", ")", "eqs", "=", "eqs", ".", "filter", "(", "AllSponsored", "(", ")", ")", "published_offset", "=", "getattr", "(", "settings", ",", "\"RECENT_SPONSORED_OFFSET_HOURS\"", ",", "None", ")", "if", "published_offset", ":", "now", "=", "timezone", ".", "now", "(", ")", "eqs", "=", "eqs", ".", "filter", "(", "Published", "(", "after", "=", "now", "-", "timezone", ".", "timedelta", "(", "hours", "=", "published_offset", ")", ",", "before", "=", "now", ")", ")", "return", "eqs" ]
Remove the mini applet .
def qteKillMiniApplet ( self ) : # Sanity check: is the handle valid? if self . _qteMiniApplet is None : return # Sanity check: is it really a mini applet? if not self . qteIsMiniApplet ( self . _qteMiniApplet ) : msg = ( 'Mini applet does not have its mini applet flag set.' ' Ignored.' ) self . qteLogger . warning ( msg ) if self . _qteMiniApplet not in self . _qteAppletList : # Something is wrong because the mini applet is not part # of the applet list. msg = 'Custom mini applet not in applet list --> Bug.' self . qteLogger . warning ( msg ) else : # Inform the mini applet that it is about to be killed. try : self . _qteMiniApplet . qteToBeKilled ( ) except Exception : msg = 'qteToBeKilledRoutine is faulty' self . qteLogger . exception ( msg , exc_info = True , stack_info = True ) # Shorthands to calling window. win = self . _qteMiniApplet . _qteCallingWindow # We need to move the focus from the mini applet back to a # regular applet. Therefore, first look for the next # visible applet in the current window (ie. the last one # that was made active). app = self . qteNextApplet ( windowObj = win ) if app is not None : # Found another (visible or invisible) applet --> make # it active/visible. self . qteMakeAppletActive ( app ) else : # No visible applet available in this window --> look # for an invisible one. app = self . qteNextApplet ( skipInvisible = False , skipVisible = True ) if app is not None : # Found an invisible applet --> make it # active/visible. self . qteMakeAppletActive ( app ) else : # There is no other visible applet in this window. # The focus manager will therefore make a new applet # active. self . _qteActiveApplet = None self . _qteAppletList . remove ( self . _qteMiniApplet ) # Close the mini applet applet and schedule it for deletion. self . _qteMiniApplet . close ( ) self . _qteMiniApplet . deleteLater ( ) # Clear the handle to the mini applet. self . _qteMiniApplet = None
7,758
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2100-L2175
[ "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" ]
Return the splitter that holds appletObj .
def _qteFindAppletInSplitter ( self , appletObj : QtmacsApplet , split : QtmacsSplitter ) : def splitterIter ( split ) : """ Iterator over all QtmacsSplitters. """ for idx in range ( split . count ( ) ) : subSplitter = split . widget ( idx ) subID = subSplitter . _qteAdmin . widgetSignature if subID == '__QtmacsLayoutSplitter__' : yield from splitterIter ( subSplitter ) yield split # Traverse all QtmacsSplitter until ``appletObj`` was found. for curSplit in splitterIter ( split ) : if appletObj in curSplit . children ( ) : return curSplit # No splitter holds ``appletObj``. return None
7,759
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2178-L2219
[ "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" ]
Reveal applet by splitting the space occupied by the current applet .
def qteSplitApplet ( self , applet : ( QtmacsApplet , str ) = None , splitHoriz : bool = True , windowObj : QtmacsWindow = None ) : # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance ( applet , str ) : newAppObj = self . qteGetAppletHandle ( applet ) else : newAppObj = applet # Use the currently active window if none was specified. if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . error ( msg , stack_info = True ) return # Convert ``splitHoriz`` to the respective Qt constant. if splitHoriz : splitOrientation = QtCore . Qt . Horizontal else : splitOrientation = QtCore . Qt . Vertical if newAppObj is None : # If no new applet was specified use the next available # invisible applet. newAppObj = self . qteNextApplet ( skipVisible = True , skipInvisible = False ) else : # Do nothing if the new applet is already visible. if newAppObj . qteIsVisible ( ) : return False # If we still have not found an applet then there are no # invisible applets left to show. Therefore, splitting makes # no sense. if newAppObj is None : self . qteLogger . warning ( 'All applets are already visible.' ) return False # If the root splitter is empty then add the new applet and # return immediately. if windowObj . qteAppletSplitter . count ( ) == 0 : windowObj . qteAppletSplitter . qteAddWidget ( newAppObj ) windowObj . qteAppletSplitter . setOrientation ( splitOrientation ) return True # ------------------------------------------------------------ # The root splitter contains at least one widget, if we got # this far. # ------------------------------------------------------------ # Shorthand to last active applet in the current window. Query # this applet with qteNextApplet method because # self._qteActiveApplet may be a mini applet, and we are only # interested in genuine applets. curApp = self . qteNextApplet ( numSkip = 0 , windowObj = windowObj ) # Get a reference to the splitter in which the currently # active applet lives. This may be the root splitter, or one # of its child splitters. split = self . _qteFindAppletInSplitter ( curApp , windowObj . qteAppletSplitter ) if split is None : msg = 'Active applet <b>{}</b> not in the layout.' msg = msg . format ( curApp . qteAppletID ( ) ) self . qteLogger . error ( msg , stack_info = True ) return False # If 'curApp' lives in the root splitter, and the root # splitter contains only a single element, then simply add the # new applet as the second element and return. if split is windowObj . qteAppletSplitter : if split . count ( ) == 1 : split . qteAddWidget ( newAppObj ) split . setOrientation ( splitOrientation ) return True # ------------------------------------------------------------ # The splitter (root or not) contains two widgets, if we got # this far. # ------------------------------------------------------------ # Determine the index of the applet inside the splitter. curAppIdx = split . indexOf ( curApp ) # Create a new splitter and populate it with 'curApp' and the # previously invisible ``newAppObj``. Then insert this new splitter at # the position where the old applet was taken from. Note: widgets are # inserted with ``qteAddWidget`` (because they are ``QtmacsApplet`` # instances), whereas splitters are added with ``insertWidget``, NOT # ``qteInsertWidget``. The reason is that splitters do not require the # extra TLC necessary for applets in terms of how and where to show # them. newSplit = QtmacsSplitter ( splitOrientation , windowObj ) curApp . setParent ( None ) newSplit . qteAddWidget ( curApp ) newSplit . qteAddWidget ( newAppObj ) split . insertWidget ( curAppIdx , newSplit ) # Adjust the size of two widgets in ``split`` (ie. ``newSplit`` and # whatever other widget) to take up equal space. The same adjusment is # made for ``newSplit``, but there the ``qteAddWidget`` methods have # already taken care of it. split . qteAdjustWidgetSizes ( ) return True
7,760
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2222-L2363
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "BaseAuthorDetail", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", "[", "'author'", "]", "=", "self", ".", "author", "return", "context" ]
Replace oldApplet with newApplet in the window layout .
def qteReplaceAppletInLayout ( self , newApplet : ( QtmacsApplet , str ) , oldApplet : ( QtmacsApplet , str ) = None , windowObj : QtmacsWindow = None ) : # If ``oldAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``oldAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance ( oldApplet , str ) : oldAppObj = self . qteGetAppletHandle ( oldApplet ) else : oldAppObj = oldApplet # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance ( newApplet , str ) : newAppObj = self . qteGetAppletHandle ( newApplet ) else : newAppObj = newApplet # Use the currently active window if none was specified. if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . warning ( msg , stack_info = True ) return # If the main splitter contains no applet then just add newAppObj. if windowObj . qteAppletSplitter . count ( ) == 0 : windowObj . qteAppletSplitter . qteAddWidget ( newAppObj ) return # If no oldAppObj was specified use the currently active one # instead. Do not use qteActiveApplet to determine it, though, # because it may point to a mini buffer. If it is, then we # need the last active Qtmacs applet. In either case, the # qteNextApplet method will take care of these distinctions. if oldAppObj is None : oldAppObj = self . qteNextApplet ( numSkip = 0 , windowObj = windowObj ) # Sanity check: the applet to replace must exist. if oldAppObj is None : msg = 'Applet to replace does not exist.' self . qteLogger . error ( msg , stack_info = True ) return # Sanity check: do nothing if the old- and new applet are the # same. if newAppObj is oldAppObj : return # Sanity check: do nothing if both applets are already # visible. if oldAppObj . qteIsVisible ( ) and newAppObj . qteIsVisible ( ) : return # Search for the splitter that contains 'oldAppObj'. split = self . _qteFindAppletInSplitter ( oldAppObj , windowObj . qteAppletSplitter ) if split is None : msg = ( 'Applet <b>{}</b> not replaced because it is not' 'in the layout.' . format ( oldAppObj . qteAppletID ( ) ) ) self . qteLogger . warning ( msg ) return # Determine the position of oldAppObj inside the splitter. oldAppIdx = split . indexOf ( oldAppObj ) # Replace oldAppObj with newAppObj but maintain the widget sizes. To do # so, first insert newAppObj into the splitter at the position of # oldAppObj. Afterwards, remove oldAppObj by re-parenting it, make # it invisible, and restore the widget sizes. sizes = split . sizes ( ) split . qteInsertWidget ( oldAppIdx , newAppObj ) oldAppObj . hide ( True ) split . setSizes ( sizes )
7,761
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2366-L2469
[ "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 applet from the window layout .
def qteRemoveAppletFromLayout ( self , applet : ( QtmacsApplet , str ) ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Return immediately if the applet does not exist in any splitter. for window in self . _qteWindowList : split = self . _qteFindAppletInSplitter ( appletObj , window . qteAppletSplitter ) if split is not None : break if split is None : return # If the applet lives in the main splitter and is the only # widget there it must be replaced with another applet. This # case needs to be handled separately from the other options # because every other splitter will always contain exactly two # items (ie. two applets, two splitters, or one of each). if ( split is window . qteAppletSplitter ) and ( split . count ( ) == 1 ) : # Remove the existing applet object from the splitter and # hide it. split . widget ( 0 ) . hide ( True ) # Get the next available applet to focus on. Try to find a # visible applet in the current window, and if none exists # then pick the first invisible one. If there is neither # a visible nor an invisible applet left then do nothing. nextApp = self . qteNextApplet ( windowObj = window ) if nextApp is None : nextApp = self . qteNextApplet ( skipInvisible = False , skipVisible = True ) if nextApp is None : return # Ok, we found an applet to show. split . qteAddWidget ( nextApp ) return # ------------------------------------------------------------ # If we got until here we know that the splitter (root or not) # contains (at least) two elements. Note: if it contains more # than two elements then there is a bug somewhere. # ------------------------------------------------------------ # Find the index of the object inside the splitter. appletIdx = split . indexOf ( appletObj ) # Detach the applet from the splitter and make it invisible. appletObj . hide ( True ) # Verify that really only one additional element is left in # the splitter. If not, then something is wrong. if split . count ( ) != 1 : msg = ( 'Splitter has <b>{}</b> elements left instead of' ' exactly one.' . format ( split . count ( ) ) ) self . qteLogger . warning ( msg ) # Get a reference to the other widget in the splitter (either # a QtmacsSplitter or a QtmacsApplet). otherWidget = split . widget ( 0 ) # Is the other widget another splitter? if otherWidget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : # Yes, ``otherWidget`` is a QtmacsSplitter object, # therefore shift all its widgets over to the current # splitter. for ii in range ( otherWidget . count ( ) ) : # Get the next widget from that splitter. Note that we # always pick the widget at the 0'th position because # the splitter will re-index the remaining widgets # after each removal. obj = otherWidget . widget ( 0 ) if appletIdx == 0 : split . qteAddWidget ( obj ) else : split . qteInsertWidget ( 1 + ii , obj ) # Delete the child splitter. otherWidget . setParent ( None ) otherWidget . close ( ) else : # No, ``otherWidget`` is a QtmacsApplet, therefore move it # to the parent splitter and delete the current one, # unless 'split' is the root splitter in which case # nothing happens. if split is not window . qteAppletSplitter : otherWidget . qteReparent ( split . parent ( ) ) split . setParent ( None ) split . close ( )
7,762
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2472-L2596
[ "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" ]
Destroy the applet with ID appletID .
def qteKillApplet ( self , appletID : str ) : # Compile list of all applet IDs. ID_list = [ _ . qteAppletID ( ) for _ in self . _qteAppletList ] if appletID not in ID_list : # Do nothing if the applet does not exist. return else : # Get a reference to the actual applet object based on the # name. idx = ID_list . index ( appletID ) appObj = self . _qteAppletList [ idx ] # Mini applets are killed with a special method. if self . qteIsMiniApplet ( appObj ) : self . qteKillMiniApplet ( ) return # Inform the applet that it is about to be killed. appObj . qteToBeKilled ( ) # Determine the window of the applet. window = appObj . qteParentWindow ( ) # Get the previous invisible applet (*may* come in handy a few # lines below). newApplet = self . qteNextApplet ( numSkip = - 1 , skipInvisible = False , skipVisible = True ) # If there is no invisible applet available, or the only available # applet is the one to be killed, then set newApplet to None. if ( newApplet is None ) or ( newApplet is appObj ) : newApplet = None else : self . qteReplaceAppletInLayout ( newApplet , appObj , window ) # Ensure that _qteActiveApplet does not point to the applet # to be killed as it will otherwise result in a dangling # pointer. if self . _qteActiveApplet is appObj : self . _qteActiveApplet = newApplet # Remove the applet object from the applet list. self . qteLogger . debug ( 'Kill applet: <b>{}</b>' . format ( appletID ) ) self . _qteAppletList . remove ( appObj ) # Close the applet and schedule it for destruction. Explicitly # call the sip.delete() method to ensure that all signals are # *immediately* disconnected, as otherwise there is a good # chance that Qtmacs segfaults if Python/Qt thinks the slots # are still connected when really the object does not exist # anymore. appObj . close ( ) sip . delete ( appObj )
7,763
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2599-L2677
[ "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" ]
Trigger the hook named hookName and pass on msgObj .
def qteRunHook ( self , hookName : str , msgObj : QtmacsMessage = None ) : # Shorthand. reg = self . _qteRegistryHooks # Do nothing if there are not recipients for the hook. if hookName not in reg : return # Create an empty ``QtmacsMessage`` object if none was provided. if msgObj is None : msgObj = QtmacsMessage ( ) # Add information about the hook that will deliver ``msgObj``. msgObj . setHookName ( hookName ) # Try to call each slot. Intercept any errors but ensure that # really all slots are called, irrespective of how many of them # raise an error during execution. for fun in reg [ hookName ] : try : fun ( msgObj ) except Exception as err : # Format the error message. msg = '<b>{}</b>-hook function <b>{}</b>' . format ( hookName , str ( fun ) [ 1 : - 1 ] ) msg += " did not execute properly." if isinstance ( err , QtmacsArgumentError ) : msg += '<br/>' + str ( err ) # Log the error. self . qteLogger . exception ( msg , exc_info = True , stack_info = True )
7,764
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2680-L2741
[ "def", "clusterstatus", "(", "self", ")", ":", "res", "=", "self", ".", "cluster_status_raw", "(", ")", "cluster", "=", "res", "[", "'cluster'", "]", "[", "'collections'", "]", "out", "=", "{", "}", "try", ":", "for", "collection", "in", "cluster", ":", "out", "[", "collection", "]", "=", "{", "}", "for", "shard", "in", "cluster", "[", "collection", "]", "[", "'shards'", "]", ":", "out", "[", "collection", "]", "[", "shard", "]", "=", "{", "}", "for", "replica", "in", "cluster", "[", "collection", "]", "[", "'shards'", "]", "[", "shard", "]", "[", "'replicas'", "]", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "=", "cluster", "[", "collection", "]", "[", "'shards'", "]", "[", "shard", "]", "[", "'replicas'", "]", "[", "replica", "]", "if", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'state'", "]", "!=", "'active'", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'doc_count'", "]", "=", "False", "else", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'doc_count'", "]", "=", "self", ".", "_get_collection_counts", "(", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "\"Couldn't parse response from clusterstatus API call\"", ")", "self", ".", "logger", ".", "exception", "(", "e", ")", "return", "out" ]
Connect the method or function slot to hookName .
def qteConnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) : # Shorthand. reg = self . _qteRegistryHooks if hookName in reg : reg [ hookName ] . append ( slot ) else : reg [ hookName ] = [ slot ]
7,765
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2744-L2768
[ "def", "data_and_files", "(", "self", ",", "data", "=", "True", ",", "files", "=", "True", ",", "stream", "=", "None", ")", ":", "if", "self", ".", "method", "in", "ENCODE_URL_METHODS", ":", "value", "=", "{", "}", ",", "None", "else", ":", "value", "=", "self", ".", "cache", ".", "get", "(", "'data_and_files'", ")", "if", "not", "value", ":", "return", "self", ".", "_data_and_files", "(", "data", ",", "files", ",", "stream", ")", "elif", "data", "and", "files", ":", "return", "value", "elif", "data", ":", "return", "value", "[", "0", "]", "elif", "files", ":", "return", "value", "[", "1", "]", "else", ":", "return", "None" ]
Disconnect slot from hookName .
def qteDisconnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) : # Shorthand. reg = self . _qteRegistryHooks # Return immediately if no hook with that name exists. if hookName not in reg : msg = 'There is no hook called <b>{}</b>.' self . qteLogger . info ( msg . format ( hookName ) ) return False # Return immediately if the ``slot`` is not connected to the hook. if slot not in reg [ hookName ] : msg = 'Slot <b>{}</b> is not connected to hook <b>{}</b>.' self . qteLogger . info ( msg . format ( str ( slot ) [ 1 : - 1 ] , hookName ) ) return False # Remove ``slot`` from the list. reg [ hookName ] . remove ( slot ) # If the list is now empty, then remove it altogether. if len ( reg [ hookName ] ) == 0 : reg . pop ( hookName ) return True
7,766
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2771-L2816
[ "def", "forbidden", "(", "cls", ",", "errors", "=", "None", ")", ":", "if", "cls", ".", "expose_status", ":", "# pragma: no cover", "cls", ".", "response", ".", "content_type", "=", "'application/json'", "cls", ".", "response", ".", "_status_line", "=", "'403 Forbidden'", "return", "cls", "(", "403", ",", "errors", "=", "errors", ")", ".", "to_json" ]
Import fileName at run - time .
def qteImportModule ( self , fileName : str ) : # Split the absolute file name into the path- and file name. path , name = os . path . split ( fileName ) name , ext = os . path . splitext ( name ) # If the file name has a path prefix then search there, otherwise # search the default paths for Python. if path == '' : path = sys . path else : path = [ path ] # Try to locate the module. try : fp , pathname , desc = imp . find_module ( name , path ) except ImportError : msg = 'Could not find module <b>{}</b>.' . format ( fileName ) self . qteLogger . error ( msg ) return None # Try to import the module. try : mod = imp . load_module ( name , fp , pathname , desc ) return mod except ImportError : msg = 'Could not import module <b>{}</b>.' . format ( fileName ) self . qteLogger . error ( msg ) return None finally : # According to the imp documentation the file pointer # should always be closed explicitly. if fp : fp . close ( )
7,767
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2819-L2871
[ "def", "delete_classifier", "(", "self", ",", "classifier_id", ",", "*", "*", "kwargs", ")", ":", "if", "classifier_id", "is", "None", ":", "raise", "ValueError", "(", "'classifier_id must be provided'", ")", "headers", "=", "{", "}", "if", "'headers'", "in", "kwargs", ":", "headers", ".", "update", "(", "kwargs", ".", "get", "(", "'headers'", ")", ")", "sdk_headers", "=", "get_sdk_headers", "(", "'watson_vision_combined'", ",", "'V3'", ",", "'delete_classifier'", ")", "headers", ".", "update", "(", "sdk_headers", ")", "params", "=", "{", "'version'", ":", "self", ".", "version", "}", "url", "=", "'/v3/classifiers/{0}'", ".", "format", "(", "*", "self", ".", "_encode_path_vars", "(", "classifier_id", ")", ")", "response", "=", "self", ".", "request", "(", "method", "=", "'DELETE'", ",", "url", "=", "url", ",", "headers", "=", "headers", ",", "params", "=", "params", ",", "accept_json", "=", "True", ")", "return", "response" ]
Convert the class name of a macro class to macro name .
def qteMacroNameMangling ( self , macroCls ) : # Replace camel bump as hyphenated lower case string. macroName = re . sub ( r"([A-Z])" , r'-\1' , macroCls . __name__ ) # If the first character of the class name was a # capital letter (likely) then the above substitution would have # resulted in a leading hyphen. Remove it. if macroName [ 0 ] == '-' : macroName = macroName [ 1 : ] # Return the lower case string. return macroName . lower ( )
7,768
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2873-L2911
[ "def", "unmount", "(", "self", ",", "force", "=", "None", ",", "auth_no_user_interaction", "=", "None", ")", ":", "return", "self", ".", "_M", ".", "Filesystem", ".", "Unmount", "(", "'(a{sv})'", ",", "filter_opt", "(", "{", "'force'", ":", "(", "'b'", ",", "force", ")", ",", "'auth.no_user_interaction'", ":", "(", "'b'", ",", "auth_no_user_interaction", ")", ",", "}", ")", ")" ]
Register a macro .
def qteRegisterMacro ( self , macroCls , replaceMacro : bool = False , macroName : str = None ) : # Check type of input arguments. if not issubclass ( macroCls , QtmacsMacro ) : args = ( 'macroCls' , 'class QtmacsMacro' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Try to instantiate the macro class. try : macroObj = macroCls ( ) except Exception : msg = 'The macro <b>{}</b> has a faulty constructor.' msg = msg . format ( macroCls . __name__ ) self . qteLogger . error ( msg , stack_info = True ) return None # The three options to determine the macro name, in order of # precedence, are: passed to this function, specified in the # macro constructor, name mangled. if macroName is None : # No macro name was passed to the function. if macroObj . qteMacroName ( ) is None : # The macro has already named itself. macroName = self . qteMacroNameMangling ( macroCls ) else : # The macro name is inferred from the class name. macroName = macroObj . qteMacroName ( ) # Let the macro know under which name it is known inside Qtmacs. macroObj . _qteMacroName = macroName # Ensure the macro has applet signatures. if len ( macroObj . qteAppletSignature ( ) ) == 0 : msg = 'Macro <b>{}</b> has no applet signatures.' . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return None # Ensure the macro has widget signatures. if len ( macroObj . qteWidgetSignature ( ) ) == 0 : msg = 'Macro <b>{}</b> has no widget signatures.' . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return None # Flag to indicate that at least one new macro type was # registered. anyRegistered = False # Iterate over all applet signatures. for app_sig in macroObj . qteAppletSignature ( ) : # Iterate over all widget signatures. for wid_sig in macroObj . qteWidgetSignature ( ) : # Infer the macro name from the class name of the # passed macro object. macroNameInternal = ( macroName , app_sig , wid_sig ) # If a macro with this name already exists then either # replace it, or skip the registration process for the # new one. if macroNameInternal in self . _qteRegistryMacros : if replaceMacro : # Remove existing macro. tmp = self . _qteRegistryMacros . pop ( macroNameInternal ) msg = 'Replacing existing macro <b>{}</b> with new {}.' msg = msg . format ( macroNameInternal , macroObj ) self . qteLogger . info ( msg ) tmp . deleteLater ( ) else : msg = 'Macro <b>{}</b> already exists (not replaced).' msg = msg . format ( macroNameInternal ) self . qteLogger . info ( msg ) # Macro was not registered for this widget # signature. continue # Add macro object to the registry. self . _qteRegistryMacros [ macroNameInternal ] = macroObj msg = ( 'Macro <b>{}</b> successfully registered.' . format ( macroNameInternal ) ) self . qteLogger . info ( msg ) anyRegistered = True # Return the name of the macro, irrespective of whether or not # it is a newly created macro, or if the old macro was kept # (in case of a name conflict). return macroName
7,769
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2914-L3044
[ "def", "decompressSkeletalBoneData", "(", "self", ",", "pvCompressedBuffer", ",", "unCompressedBufferSize", ",", "eTransformSpace", ",", "unTransformArrayCount", ")", ":", "fn", "=", "self", ".", "function_table", ".", "decompressSkeletalBoneData", "pTransformArray", "=", "VRBoneTransform_t", "(", ")", "result", "=", "fn", "(", "pvCompressedBuffer", ",", "unCompressedBufferSize", ",", "eTransformSpace", ",", "byref", "(", "pTransformArray", ")", ",", "unTransformArrayCount", ")", "return", "result", ",", "pTransformArray" ]
Return macro that is name - and signature compatible with macroName and widgetObj .
def qteGetMacroObject ( self , macroName : str , widgetObj : QtGui . QWidget ) : # Determine the applet- and widget signature. This is trivial # if the widget was registered with Qtmacs because its # '_qteAdmin' attribute will provide this information. If, on # the other hand, the widget was not registered with Qtmacs # then it has no signature, yet its parent applet must because # every applet has one. The only exception when the applet # signature is therefore when there are no applets to begin # with, ie. the the window is empty. if hasattr ( widgetObj , '_qteAdmin' ) : app_signature = widgetObj . _qteAdmin . appletSignature wid_signature = widgetObj . _qteAdmin . widgetSignature # Return immediately if the applet signature is None # (should be impossible). if app_signature is None : msg = 'Applet has no signature.' self . qteLogger . error ( msg , stack_info = True ) return None else : wid_signature = None app = qteGetAppletFromWidget ( widgetObj ) if app is None : app_signature = None else : app_signature = app . _qteAdmin . appletSignature # Find all macros with name 'macroName'. This will produce a list of # tuples with entries (macroName, app_sig, wid_sig). name_match = [ m for m in self . _qteRegistryMacros if m [ 0 ] == macroName ] # Find all macros with a compatible applet signature. This is # produce another list of tuples with the same format as # the name_match list (see above). app_sig_match = [ _ for _ in name_match if _ [ 1 ] in ( app_signature , '*' ) ] if wid_signature is None : wid_sig_match = [ _ for _ in app_sig_match if _ [ 2 ] == '*' ] else : # Find all macros with a compatible widget signature. This is # a list of tuples, each tuple consisting of (macroName, # app_sig, wid_sig). wid_sig_match = [ _ for _ in app_sig_match if _ [ 2 ] in ( wid_signature , '*' ) ] # Pick a macro. if len ( wid_sig_match ) == 0 : # No macro is compatible with either the applet- or widget # signature. return None elif len ( wid_sig_match ) == 1 : match = wid_sig_match [ 0 ] # Exactly one macro is compatible with either the applet- # or widget signature. return self . _qteRegistryMacros [ match ] else : # Found multiple matches. For any given macro 'name', # applet signature 'app', and widget signature 'wid' there # can be at most four macros in the list: *:*:name, # wid:*:name, *:app:name, and wid:app:name. # See if there is a macro for which both the applet and # widget signature match. tmp = [ match for match in wid_sig_match if ( match [ 1 ] != '*' ) and ( match [ 2 ] != '*' ) ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] # See if there is a macro with a matching widget signature. tmp = [ match for match in wid_sig_match if match [ 2 ] != '*' ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] # See if there is a macro with a matching applet signature. tmp = [ match for match in wid_sig_match if match [ 1 ] != '*' ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] # At this point only one possibility is left, namely a # generic macro that is applicable to arbitrary applets # and widgets, eg. NextApplet. tmp = [ match for match in wid_sig_match if ( match [ 1 ] == '*' ) and ( match [ 2 ] == '*' ) ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] # This should be impossible. msg = 'No compatible macro found - should be impossible.' self . qteLogger . error ( msg , stack_info = True )
7,770
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3089-L3213
[ "def", "get_users", "(", "self", ",", "limit", "=", "100", ",", "offset", "=", "0", ")", ":", "url", "=", "self", ".", "TEAM_USERS_URL", "+", "\"?limit=%s&offset=%s\"", "%", "(", "limit", ",", "offset", ")", "connection", "=", "Connection", "(", "self", ".", "token", ")", "connection", ".", "set_url", "(", "self", ".", "production", ",", "url", ")", "return", "connection", ".", "get_request", "(", ")" ]
Return all macro names known to Qtmacs as a list .
def qteGetAllMacroNames ( self , widgetObj : QtGui . QWidget = None ) : # The keys of qteRegistryMacros are (macroObj, app_sig, # wid_sig) tuples. Get them, extract the macro names, and # remove all duplicates. macro_list = tuple ( self . _qteRegistryMacros . keys ( ) ) macro_list = [ _ [ 0 ] for _ in macro_list ] macro_list = tuple ( set ( macro_list ) ) # If no widget object was supplied then omit the signature # check and return the macro list verbatim. if widgetObj is None : return macro_list else : # Use qteGetMacroObject to compile a list of macros that # are compatible with widgetObj. This list contains # (macroObj, macroName, app_sig, wid_sig) tuples. macro_list = [ self . qteGetMacroObject ( macroName , widgetObj ) for macroName in macro_list ] # Remove all elements where macroObj=None. This is the # case if no compatible macro with the specified name # could be found for widgetObj. macro_list = [ _ . qteMacroName ( ) for _ in macro_list if _ is not None ] return macro_list
7,771
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3216-L3262
[ "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", ")", ")", ")" ]
Associate macroName with keysequence in all current applets .
def qteBindKeyGlobal ( self , keysequence , macroName : str ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence ( keysequence ) # Sanity check: the macro must have been registered # beforehand. if not self . qteIsMacroRegistered ( macroName ) : msg = 'Cannot globally bind key to unknown macro <b>{}</b>.' msg = msg . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return False # Insert/overwrite the key sequence and associate it with the # new macro. self . _qteGlobalKeyMap . qteInsertKey ( keysequence , macroName ) # Now update the local key map of every applet. Note that # globally bound macros apply to every applet (hence the loop # below) and every widget therein (hence the "*" parameter for # the widget signature). for app in self . _qteAppletList : self . qteBindKeyApplet ( keysequence , macroName , app ) return True
7,772
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3265-L3327
[ "def", "get_time_to_merge_request_response", "(", "self", ",", "item", ")", ":", "review_dates", "=", "[", "str_to_datetime", "(", "review", "[", "'created_at'", "]", ")", "for", "review", "in", "item", "[", "'review_comments_data'", "]", "if", "item", "[", "'user'", "]", "[", "'login'", "]", "!=", "review", "[", "'user'", "]", "[", "'login'", "]", "]", "if", "review_dates", ":", "return", "min", "(", "review_dates", ")", "return", "None" ]
Bind macroName to all widgets in appletObj .
def qteBindKeyApplet ( self , keysequence , macroName : str , appletObj : QtmacsApplet ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Verify that Qtmacs knows a macro named 'macroName'. if not self . qteIsMacroRegistered ( macroName ) : msg = ( 'Cannot bind key because the macro <b>{}</b> does' 'not exist.' . format ( macroName ) ) self . qteLogger . error ( msg , stack_info = True ) return False # Bind the key also to the applet itself because it can # receive keyboard events (eg. when it is empty). appletObj . _qteAdmin . keyMap . qteInsertKey ( keysequence , macroName ) # Update the key map of every widget inside the applet. for wid in appletObj . _qteAdmin . widgetList : self . qteBindKeyWidget ( keysequence , macroName , wid ) return True
7,773
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3330-L3385
[ "def", "publication_range", "(", "self", ")", ":", "r", "=", "self", ".", "_json", "[", "'author-profile'", "]", "[", "'publication-range'", "]", "return", "(", "r", "[", "'@start'", "]", ",", "r", "[", "'@end'", "]", ")", "return", "self", ".", "_json", "[", "'coredata'", "]", ".", "get", "(", "'orcid'", ")" ]
Bind macroName to widgetObj and associate it with keysequence .
def qteBindKeyWidget ( self , keysequence , macroName : str , widgetObj : QtGui . QWidget ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Verify that Qtmacs knows a macro named 'macroName'. if not self . qteIsMacroRegistered ( macroName ) : msg = ( 'Cannot bind key to unknown macro <b>{}</b>.' . format ( macroName ) ) self . qteLogger . error ( msg , stack_info = True ) return False # Associate 'keysequence' with 'macroName' for 'widgetObj'. try : widgetObj . _qteAdmin . keyMap . qteInsertKey ( keysequence , macroName ) except AttributeError : msg = 'Received an invalid macro object.' self . qteLogger . error ( msg , stack_info = True ) return False return True
7,774
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3388-L3456
[ "def", "_accept", "(", "random_sample", ":", "float", ",", "cost_diff", ":", "float", ",", "temp", ":", "float", ")", "->", "Tuple", "[", "bool", ",", "float", "]", ":", "exponent", "=", "-", "cost_diff", "/", "temp", "if", "exponent", ">=", "0.0", ":", "return", "True", ",", "1.0", "else", ":", "probability", "=", "math", ".", "exp", "(", "exponent", ")", "return", "probability", ">", "random_sample", ",", "probability" ]
Remove keysequence bindings from all widgets inside applet .
def qteUnbindKeyApplet ( self , applet : ( QtmacsApplet , str ) , keysequence ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None : return # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Remove the key sequence from the applet window itself. appletObj . _qteAdmin . keyMap . qteRemoveKey ( keysequence ) for wid in appletObj . _qteAdmin . widgetList : self . qteUnbindKeyFromWidgetObject ( keysequence , wid )
7,775
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3459-L3519
[ "def", "_get_subject_info", "(", "self", ",", "n_local_subj", ",", "data", ")", ":", "max_sample_tr", "=", "np", ".", "zeros", "(", "n_local_subj", ")", ".", "astype", "(", "int", ")", "max_sample_voxel", "=", "np", ".", "zeros", "(", "n_local_subj", ")", ".", "astype", "(", "int", ")", "for", "idx", "in", "np", ".", "arange", "(", "n_local_subj", ")", ":", "nvoxel", "=", "data", "[", "idx", "]", ".", "shape", "[", "0", "]", "ntr", "=", "data", "[", "idx", "]", ".", "shape", "[", "1", "]", "max_sample_voxel", "[", "idx", "]", "=", "min", "(", "self", ".", "max_voxel", ",", "int", "(", "self", ".", "voxel_ratio", "*", "nvoxel", ")", ")", "max_sample_tr", "[", "idx", "]", "=", "min", "(", "self", ".", "max_tr", ",", "int", "(", "self", ".", "tr_ratio", "*", "ntr", ")", ")", "return", "max_sample_tr", ",", "max_sample_voxel" ]
Disassociate the macro triggered by keysequence from widgetObj .
def qteUnbindKeyFromWidgetObject ( self , keysequence , widgetObj : QtGui . QWidget ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Remove the key sequence from the local key maps. widgetObj . _qteAdmin . keyMap . qteRemoveKey ( keysequence )
7,776
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3522-L3569
[ "def", "_compute_ogg_page_crc", "(", "page", ")", ":", "page_zero_crc", "=", "page", "[", ":", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "]", "+", "b\"\\00\"", "*", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", "+", "page", "[", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "+", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", ":", "]", "return", "ogg_page_crc", "(", "page_zero_crc", ")" ]
Restore the global key - map for all widgets inside applet .
def qteUnbindAllFromApplet ( self , applet : ( QtmacsApplet , str ) ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None : return # Remove the key sequence from the applet window itself. appletObj . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( ) # Restore the global key-map for every widget. for wid in appletObj . _qteAdmin . widgetList : wid . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( )
7,777
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3572-L3619
[ "def", "verify", "(", "cls", ",", "user_id", ",", "verification_hash", ")", ":", "user", "=", "yield", "cls", ".", "get", "(", "user_id", ")", "# If user does not have verification hash then this means they have already been verified", "if", "'verification_hash'", "not", "in", "user", ".", "_resource", ":", "raise", "Return", "(", "user", ")", "if", "user", ".", "verification_hash", "!=", "verification_hash", ":", "raise", "exceptions", ".", "ValidationError", "(", "'Invalid verification hash'", ")", "del", "user", ".", "verification_hash", "yield", "user", ".", "_save", "(", ")", "raise", "Return", "(", "user", ")" ]
Reset the local key - map of widgetObj to the current global key - map .
def qteUnbindAllFromWidgetObject ( self , widgetObj : QtGui . QWidget ) : # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Install the global key-map for this widget. widgetObj . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( )
7,778
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3622-L3649
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Register cls as an applet .
def qteRegisterApplet ( self , cls , replaceApplet : bool = False ) : # Check type of input arguments. if not issubclass ( cls , QtmacsApplet ) : args = ( 'cls' , 'class QtmacsApplet' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Extract the class name as string, because this is the name # under which the applet will be known. class_name = cls . __name__ # Issue a warning if an applet with this name already exists. if class_name in self . _qteRegistryApplets : msg = 'The original applet <b>{}</b>' . format ( class_name ) if replaceApplet : msg += ' was redefined.' self . qteLogger . warning ( msg ) else : msg += ' was not redefined.' self . qteLogger . warning ( msg ) return class_name # Execute the classmethod __qteRegisterAppletInit__ to # allow the applet to make global initialisations that do # not depend on a particular instance, eg. the supported # file types. cls . __qteRegisterAppletInit__ ( ) # Add the class (not instance!) to the applet registry. self . _qteRegistryApplets [ class_name ] = cls self . qteLogger . info ( 'Applet <b>{}</b> now registered.' . format ( class_name ) ) return class_name
7,779
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3688-L3758
[ "def", "_get_port_speed_price_id", "(", "items", ",", "port_speed", ",", "no_public", ",", "location", ")", ":", "for", "item", "in", "items", ":", "if", "utils", ".", "lookup", "(", "item", ",", "'itemCategory'", ",", "'categoryCode'", ")", "!=", "'port_speed'", ":", "continue", "# Check for correct capacity and if the item matches private only", "if", "any", "(", "[", "int", "(", "utils", ".", "lookup", "(", "item", ",", "'capacity'", ")", ")", "!=", "port_speed", ",", "_is_private_port_speed_item", "(", "item", ")", "!=", "no_public", ",", "not", "_is_bonded", "(", "item", ")", "]", ")", ":", "continue", "for", "price", "in", "item", "[", "'prices'", "]", ":", "if", "not", "_matches_location", "(", "price", ",", "location", ")", ":", "continue", "return", "price", "[", "'id'", "]", "raise", "SoftLayer", ".", "SoftLayerError", "(", "\"Could not find valid price for port speed: '%s'\"", "%", "port_speed", ")" ]
Return a handle to appletID .
def qteGetAppletHandle ( self , appletID : str ) : # Compile list of applet Ids. id_list = [ _ . qteAppletID ( ) for _ in self . _qteAppletList ] # If one of the applets has ``appletID`` then return a # reference to it. if appletID in id_list : idx = id_list . index ( appletID ) return self . _qteAppletList [ idx ] else : return None
7,780
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3797-L3825
[ "def", "get_duration_metadata", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'duration'", "]", ")", "metadata", ".", "update", "(", "{", "'existing_duration_values'", ":", "self", ".", "_my_map", "[", "'duration'", "]", "}", ")", "return", "Metadata", "(", "*", "*", "metadata", ")" ]
Make applet visible and give it the focus .
def qteMakeAppletActive ( self , applet : ( QtmacsApplet , str ) ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Sanity check: return if the applet does not exist. if appletObj not in self . _qteAppletList : return False # If ``appletObj`` is a mini applet then double check that it # is actually installed and visible. If it is a conventional # applet then insert it into the layout. if self . qteIsMiniApplet ( appletObj ) : if appletObj is not self . _qteMiniApplet : self . qteLogger . warning ( 'Wrong mini applet. Not activated.' ) print ( appletObj ) print ( self . _qteMiniApplet ) return False if not appletObj . qteIsVisible ( ) : appletObj . show ( True ) else : if not appletObj . qteIsVisible ( ) : # Add the applet to the layout by replacing the # currently active applet. self . qteReplaceAppletInLayout ( appletObj ) # Update the qteActiveApplet pointer. Note that the actual # focusing is done exclusively in the focus manager. self . _qteActiveApplet = appletObj return True
7,781
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3828-L3885
[ "def", "get_channel_info", "(", "self", ")", ":", "csv_filename", "=", "get_metadata_file_path", "(", "channeldir", "=", "self", ".", "channeldir", ",", "filename", "=", "self", ".", "channelinfo", ")", "csv_lines", "=", "_read_csv_lines", "(", "csv_filename", ")", "dict_reader", "=", "csv", ".", "DictReader", "(", "csv_lines", ")", "channel_csvs_list", "=", "list", "(", "dict_reader", ")", "channel_csv", "=", "channel_csvs_list", "[", "0", "]", "if", "len", "(", "channel_csvs_list", ")", ">", "1", ":", "raise", "ValueError", "(", "'Found multiple channel rows in '", "+", "self", ".", "channelinfo", ")", "channel_cleaned", "=", "_clean_dict", "(", "channel_csv", ")", "channel_info", "=", "self", ".", "_map_channel_row_to_dict", "(", "channel_cleaned", ")", "return", "channel_info" ]
Close Qtmacs .
def qteCloseQtmacs ( self ) : # Announce the shutdown. msgObj = QtmacsMessage ( ) msgObj . setSignalName ( 'qtesigCloseQtmacs' ) self . qtesigCloseQtmacs . emit ( msgObj ) # Kill all applets and update the GUI. for appName in self . qteGetAllAppletIDs ( ) : self . qteKillApplet ( appName ) self . _qteFocusManager ( ) # Kill all windows and update the GUI. for window in self . _qteWindowList : window . close ( ) self . _qteFocusManager ( ) # Schedule QtmacsMain for deletion. self . deleteLater ( )
7,782
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3887-L3921
[ "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.\"", ")" ]
Define and document varName in an arbitrary name space .
def qteDefVar ( self , varName : str , value , module = None , doc : str = None ) : # Use the global name space per default. if module is None : module = qte_global # Create the documentation dictionary if it does not exist # already. if not hasattr ( module , '_qte__variable__docstring__dictionary__' ) : module . _qte__variable__docstring__dictionary__ = { } # Set the variable value and documentation string. setattr ( module , varName , value ) module . _qte__variable__docstring__dictionary__ [ varName ] = doc return True
7,783
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3943-L3982
[ "def", "activation_key_expired", "(", "self", ")", ":", "expiration_days", "=", "datetime", ".", "timedelta", "(", "days", "=", "defaults", ".", "ACCOUNTS_ACTIVATION_DAYS", ")", "expiration_date", "=", "self", ".", "date_joined", "+", "expiration_days", "if", "self", ".", "activation_key", "==", "defaults", ".", "ACCOUNTS_ACTIVATED", ":", "return", "True", "if", "get_datetime_now", "(", ")", ">=", "expiration_date", ":", "return", "True", "return", "False" ]
Retrieve documentation for varName defined in module .
def qteGetVariableDoc ( self , varName : str , module = None ) : # Use the global name space per default. if module is None : module = qte_global # No documentation for the variable can exists if the doc # string dictionary is undefined. if not hasattr ( module , '_qte__variable__docstring__dictionary__' ) : return None # If the variable is undefined then return **None**. if varName not in module . _qte__variable__docstring__dictionary__ : return None # Return the requested value. return module . _qte__variable__docstring__dictionary__ [ varName ]
7,784
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3985-L4019
[ "def", "remove", "(", "self", ",", "oid", ")", ":", "hba", "=", "self", ".", "lookup_by_oid", "(", "oid", ")", "partition", "=", "self", ".", "parent", "devno", "=", "hba", ".", "properties", ".", "get", "(", "'device-number'", ",", "None", ")", "if", "devno", ":", "partition", ".", "devno_free_if_allocated", "(", "devno", ")", "wwpn", "=", "hba", ".", "properties", ".", "get", "(", "'wwpn'", ",", "None", ")", "if", "wwpn", ":", "partition", ".", "wwpn_free_if_allocated", "(", "wwpn", ")", "assert", "'hba-uris'", "in", "partition", ".", "properties", "hba_uris", "=", "partition", ".", "properties", "[", "'hba-uris'", "]", "hba_uris", ".", "remove", "(", "hba", ".", "uri", ")", "super", "(", "FakedHbaManager", ",", "self", ")", ".", "remove", "(", "oid", ")" ]
Emulate the Qt key presses that define keysequence .
def qteEmulateKeypresses ( self , keysequence ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence ( keysequence ) key_list = keysequence . toQKeyEventList ( ) # Do nothing if the key list is empty. if len ( key_list ) > 0 : # Add the keys to the queue which the event timer will # process. for event in key_list : self . _qteKeyEmulationQueue . append ( event )
7,785
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L4027-L4059
[ "def", "plot_diagram", "(", "config", ",", "results", ",", "images_dir", ",", "out_filename", ")", ":", "img_files", "=", "plot_temp_diagrams", "(", "config", ",", "results", ",", "images_dir", ")", "join_images", "(", "img_files", ",", "out_filename", ")", "for", "img_file", "in", "img_files", ":", "os", ".", "remove", "(", "img_file", ")" ]
Perform validation and filtering at the same time return a validation result object .
def process ( self , model = None , context = None ) : self . filter ( model , context ) return self . validate ( model , context )
7,786
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/schema.py#L168-L178
[ "def", "visualize_embeddings", "(", "summary_writer", ",", "config", ")", ":", "logdir", "=", "summary_writer", ".", "get_logdir", "(", ")", "# Sanity checks.", "if", "logdir", "is", "None", ":", "raise", "ValueError", "(", "'Summary writer must have a logdir'", ")", "# Saving the config file in the logdir.", "config_pbtxt", "=", "_text_format", ".", "MessageToString", "(", "config", ")", "path", "=", "os", ".", "path", ".", "join", "(", "logdir", ",", "_projector_plugin", ".", "PROJECTOR_FILENAME", ")", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "config_pbtxt", ")" ]
Return system information as a dict .
def get_sys_info ( ) : blob = dict ( ) blob [ "OS" ] = platform . system ( ) blob [ "OS-release" ] = platform . release ( ) blob [ "Python" ] = platform . python_version ( ) return blob
7,787
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L38-L44
[ "def", "publish", "(", "ctx", ",", "test", "=", "False", ")", ":", "clean", "(", "ctx", ")", "if", "test", ":", "run", "(", "'python setup.py register -r test sdist bdist_wheel'", ",", "echo", "=", "True", ")", "run", "(", "'twine upload dist/* -r test'", ",", "echo", "=", "True", ")", "else", ":", "run", "(", "'python setup.py register sdist bdist_wheel'", ",", "echo", "=", "True", ")", "run", "(", "'twine upload dist/*'", ",", "echo", "=", "True", ")" ]
Return build and package dependencies as a dict .
def get_pkg_info ( package_name , additional = ( "pip" , "flit" , "pbr" , "setuptools" , "wheel" ) ) : dist_index = build_dist_index ( pkg_resources . working_set ) root = dist_index [ package_name ] tree = construct_tree ( dist_index ) dependencies = { pkg . name : pkg . installed_version for pkg in tree [ root ] } # Add the initial package itself. root = root . as_requirement ( ) dependencies [ root . name ] = root . installed_version # Retrieve information on additional packages such as build tools. for name in additional : try : pkg = dist_index [ name ] . as_requirement ( ) dependencies [ pkg . name ] = pkg . installed_version except KeyError : continue return dependencies
7,788
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L47-L65
[ "def", "_get_site_amplification_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "s_b", ",", "s_c", ",", "s_d", "=", "self", ".", "_get_site_dummy_variables", "(", "vs30", ")", "return", "(", "C", "[", "\"sB\"", "]", "*", "s_b", ")", "+", "(", "C", "[", "\"sC\"", "]", "*", "s_c", ")", "+", "(", "C", "[", "\"sD\"", "]", "*", "s_d", ")" ]
Print an information dict to stdout in order .
def print_info ( info ) : format_str = "{:<%d} {:>%d}" % ( max ( map ( len , info ) ) , max ( map ( len , info . values ( ) ) ) , ) for name in sorted ( info ) : print ( format_str . format ( name , info [ name ] ) )
7,789
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L68-L75
[ "def", "compute", "(", "self", ",", "nodes", ")", ":", "result", "=", "defaultdict", "(", "list", ")", "# Create links when clusters from different hypercubes have members with the same sample id.", "candidates", "=", "itertools", ".", "combinations", "(", "nodes", ".", "keys", "(", ")", ",", "2", ")", "for", "candidate", "in", "candidates", ":", "# if there are non-unique members in the union", "if", "(", "len", "(", "set", "(", "nodes", "[", "candidate", "[", "0", "]", "]", ")", ".", "intersection", "(", "nodes", "[", "candidate", "[", "1", "]", "]", ")", ")", ">=", "self", ".", "min_intersection", ")", ":", "result", "[", "candidate", "[", "0", "]", "]", ".", "append", "(", "candidate", "[", "1", "]", ")", "edges", "=", "[", "[", "x", ",", "end", "]", "for", "x", "in", "result", "for", "end", "in", "result", "[", "x", "]", "]", "simplices", "=", "[", "[", "n", "]", "for", "n", "in", "nodes", "]", "+", "edges", "return", "result", ",", "simplices" ]
Print the formatted information to standard out .
def print_dependencies ( package_name ) : info = get_sys_info ( ) print ( "\nSystem Information" ) print ( "==================" ) print_info ( info ) info = get_pkg_info ( package_name ) print ( "\nPackage Versions" ) print ( "================" ) print_info ( info )
7,790
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L78-L88
[ "def", "enable", "(", "self", ")", ":", "glEnable", "(", "GL_TEXTURE_3D", ")", "glTexParameteri", "(", "GL_TEXTURE_3D", ",", "GL_TEXTURE_WRAP_S", ",", "GL_REPEAT", ")", "glTexParameteri", "(", "GL_TEXTURE_3D", ",", "GL_TEXTURE_WRAP_T", ",", "GL_REPEAT", ")", "glTexParameteri", "(", "GL_TEXTURE_3D", ",", "GL_TEXTURE_WRAP_R", ",", "GL_REPEAT", ")", "glTexParameteri", "(", "GL_TEXTURE_3D", ",", "GL_TEXTURE_MAG_FILTER", ",", "GL_LINEAR", ")", "glTexParameteri", "(", "GL_TEXTURE_3D", ",", "GL_TEXTURE_MIN_FILTER", ",", "GL_LINEAR", ")" ]
Allows for repeated http requests up to retries additional times
def repeat_read_url_request ( url , headers = None , data = None , retries = 2 , logger = None ) : if logger : logger . debug ( "Retrieving url content: {}" . format ( url ) ) req = urllib2 . Request ( url , data , headers = headers or { } ) return repeat_call ( lambda : urllib2 . urlopen ( req ) . read ( ) , retries )
7,791
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/web/operators.py#L6-L13
[ "def", "communityvisibilitystate", "(", "self", ")", ":", "if", "self", ".", "_communityvisibilitystate", "==", "None", ":", "return", "None", "elif", "self", ".", "_communityvisibilitystate", "in", "self", ".", "VisibilityState", ":", "return", "self", ".", "VisibilityState", "[", "self", ".", "_communityvisibilitystate", "]", "else", ":", "#Invalid State", "return", "None" ]
Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response
def repeat_read_json_url_request ( url , headers = None , data = None , retries = 2 , logger = None ) : if logger : logger . debug ( "Retrieving url json content: {}" . format ( url ) ) req = urllib2 . Request ( url , data = data , headers = headers or { } ) return repeat_call ( lambda : json . loads ( urllib2 . urlopen ( req ) . read ( ) ) , retries )
7,792
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/web/operators.py#L15-L23
[ "def", "filter_inactive_ports", "(", "query", ")", ":", "port_model", "=", "models_v2", ".", "Port", "query", "=", "(", "query", ".", "filter", "(", "port_model", ".", "status", "==", "n_const", ".", "PORT_STATUS_ACTIVE", ")", ")", "return", "query" ]
Quick and dirty method to find an IP on a private network given a correctly formatted IPv4 quad .
def priv ( x ) : if x . startswith ( u'172.' ) : return 16 <= int ( x . split ( u'.' ) [ 1 ] ) < 32 return x . startswith ( ( u'192.168.' , u'10.' , u'172.' ) )
7,793
https://github.com/atl/py-smartdc/blob/cc5cd5910e19004cc46e376ce035affe28fc798e/smartdc/machine.py#L7-L14
[ "def", "increment_lessons", "(", "self", ",", "measure_vals", ",", "reward_buff_sizes", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "reward_buff_sizes", ":", "for", "brain_name", ",", "buff_size", "in", "reward_buff_sizes", ".", "items", "(", ")", ":", "if", "self", ".", "_lesson_ready_to_increment", "(", "brain_name", ",", "buff_size", ")", ":", "measure_val", "=", "measure_vals", "[", "brain_name", "]", "ret", "[", "brain_name", "]", "=", "(", "self", ".", "brains_to_curriculums", "[", "brain_name", "]", ".", "increment_lesson", "(", "measure_val", ")", ")", "else", ":", "for", "brain_name", ",", "measure_val", "in", "measure_vals", ".", "items", "(", ")", ":", "ret", "[", "brain_name", "]", "=", "(", "self", ".", "brains_to_curriculums", "[", "brain_name", "]", ".", "increment_lesson", "(", "measure_val", ")", ")", "return", "ret" ]
Create client broadcast socket
def create_client_socket ( self , config ) : client_socket = WUDPNetworkNativeTransport . create_client_socket ( self , config ) client_socket . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 ) return client_socket
7,794
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/transport.py#L274-L282
[ "def", "__getNumberOfRepositories", "(", "self", ",", "web", ")", ":", "counters", "=", "web", ".", "find_all", "(", "'span'", ",", "{", "'class'", ":", "'Counter'", "}", ")", "try", ":", "if", "'k'", "not", "in", "counters", "[", "0", "]", ".", "text", ":", "self", ".", "numberOfRepos", "=", "int", "(", "counters", "[", "0", "]", ".", "text", ")", "else", ":", "reposText", "=", "counters", "[", "0", "]", ".", "text", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "reposText", "=", "reposText", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", ".", "replace", "(", "\"k\"", ",", "\"\"", ")", "if", "reposText", "and", "len", "(", "reposText", ")", ">", "1", ":", "self", ".", "numberOfRepos", "=", "int", "(", "reposText", ".", "split", "(", "\".\"", ")", "[", "0", "]", ")", "*", "1000", "+", "int", "(", "reposText", ".", "split", "(", "\".\"", ")", "[", "1", "]", ")", "*", "100", "elif", "reposText", ":", "self", ".", "numberOfRepos", "=", "int", "(", "reposText", ".", "split", "(", "\".\"", ")", "[", "0", "]", ")", "*", "1000", "except", "IndexError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")", "except", "AttributeError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")" ]
inline method to take advantage of retry
def run_object_query ( client , base_object_query , start_record , limit_to , verbose = False ) : if verbose : print ( "[start: %d limit: %d]" % ( start_record , limit_to ) ) start = datetime . datetime . now ( ) result = client . execute_object_query ( object_query = base_object_query , start_record = start_record , limit_to = limit_to ) end = datetime . datetime . now ( ) if verbose : print ( "[%s - %s]" % ( start , end ) ) return result
7,795
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L10-L23
[ "def", "clean_bucket_name", "(", "self", ")", ":", "bucket_name", "=", "self", ".", "cleaned_data", "[", "'bucket_name'", "]", "if", "not", "bucket_name", "==", "self", ".", "get_bucket_name", "(", ")", ":", "raise", "forms", ".", "ValidationError", "(", "'Bucket name does not validate.'", ")", "return", "bucket_name" ]
Takes a base query for all objects and recursively requests them
def get_long_query ( self , base_object_query , limit_to = 100 , max_calls = None , start_record = 0 , verbose = False ) : if verbose : print ( base_object_query ) record_index = start_record result = run_object_query ( self . client , base_object_query , record_index , limit_to , verbose ) obj_search_result = ( result [ 'body' ] [ "ExecuteMSQLResult" ] [ "ResultValue" ] [ "ObjectSearchResult" ] ) if obj_search_result is not None : search_results = obj_search_result [ "Objects" ] else : return [ ] if search_results is None : return [ ] result_set = search_results [ "MemberSuiteObject" ] all_objects = self . result_to_models ( result ) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len ( result_set ) >= limit_to : record_index += len ( result_set ) # should be `limit_to` result = run_object_query ( self . client , base_object_query , record_index , limit_to , verbose ) obj_search_result = ( result [ 'body' ] [ "ExecuteMSQLResult" ] [ "ResultValue" ] [ "ObjectSearchResult" ] ) if obj_search_result is not None : search_results = obj_search_result [ "Objects" ] else : search_results = None if search_results is None : result_set = [ ] else : result_set = search_results [ "MemberSuiteObject" ] all_objects += self . result_to_models ( result ) call_count += 1 return all_objects
7,796
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L35-L95
[ "def", "_sendStatCmd", "(", "self", ",", "cmd", ")", ":", "try", ":", "self", ".", "_conn", ".", "write", "(", "\"%s\\r\\n\"", "%", "cmd", ")", "regex", "=", "re", ".", "compile", "(", "'^(END|ERROR)\\r\\n'", ",", "re", ".", "MULTILINE", ")", "(", "idx", ",", "mobj", ",", "text", ")", "=", "self", ".", "_conn", ".", "expect", "(", "[", "regex", ",", "]", ",", "self", ".", "_timeout", ")", "#@UnusedVariable", "except", ":", "raise", "Exception", "(", "\"Communication with %s failed\"", "%", "self", ".", "_instanceName", ")", "if", "mobj", "is", "not", "None", ":", "if", "mobj", ".", "group", "(", "1", ")", "==", "'END'", ":", "return", "text", ".", "splitlines", "(", ")", "[", ":", "-", "1", "]", "elif", "mobj", ".", "group", "(", "1", ")", "==", "'ERROR'", ":", "raise", "Exception", "(", "\"Protocol error in communication with %s.\"", "%", "self", ".", "_instanceName", ")", "else", ":", "raise", "Exception", "(", "\"Connection with %s timed out.\"", "%", "self", ".", "_instanceName", ")" ]
The logger of this organizer
def logger ( self ) : if self . _experiment : return logging . getLogger ( '.' . join ( [ self . name , self . experiment ] ) ) elif self . _projectname : return logging . getLogger ( '.' . join ( [ self . name , self . projectname ] ) ) else : return logging . getLogger ( '.' . join ( [ self . name ] ) )
7,797
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/__init__.py#L98-L105
[ "def", "_pickle_load", "(", "path", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "topology", "=", "None", "if", "sys", ".", "version_info", ".", "major", "==", "2", ":", "if", "ext", "==", "'.pickle2'", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ")", "elif", "ext", "in", "(", "'.pickle3'", ",", "'.pickle'", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ",", "protocol", "=", "3", ")", "elif", "sys", ".", "version_info", ".", "major", "==", "3", ":", "if", "ext", "==", "'.pickle2'", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ")", "elif", "ext", "in", "(", "'.pickle3'", ",", "'.pickle'", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "topology", "=", "pickle", ".", "load", "(", "f", ")", "if", "topology", "is", "None", ":", "raise", "ValueError", "(", "'File {} is not compatible with this version'", ".", "format", "(", "path", ")", ")", "return", "topology" ]
Run the organizer from the command line
def main ( cls , args = None ) : organizer = cls ( ) organizer . parse_args ( args ) if not organizer . no_modification : organizer . config . save ( )
7,798
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/__init__.py#L141-L155
[ "def", "face_index", "(", "vertices", ")", ":", "new_verts", "=", "[", "]", "face_indices", "=", "[", "]", "for", "wall", "in", "vertices", ":", "face_wall", "=", "[", "]", "for", "vert", "in", "wall", ":", "if", "new_verts", ":", "if", "not", "np", ".", "isclose", "(", "vert", ",", "new_verts", ")", ".", "all", "(", "axis", "=", "1", ")", ".", "any", "(", ")", ":", "new_verts", ".", "append", "(", "vert", ")", "else", ":", "new_verts", ".", "append", "(", "vert", ")", "face_index", "=", "np", ".", "where", "(", "np", ".", "isclose", "(", "vert", ",", "new_verts", ")", ".", "all", "(", "axis", "=", "1", ")", ")", "[", "0", "]", "[", "0", "]", "face_wall", ".", "append", "(", "face_index", ")", "face_indices", ".", "append", "(", "face_wall", ")", "return", "np", ".", "array", "(", "new_verts", ")", ",", "np", ".", "array", "(", "face_indices", ")" ]
Start the commands of this organizer
def start ( self , * * kwargs ) : ts = { } ret = { } info_parts = { 'info' , 'get-value' , 'get_value' } for cmd in self . commands : parser_cmd = self . parser_commands . get ( cmd , cmd ) if parser_cmd in kwargs or cmd in kwargs : kws = kwargs . get ( cmd , kwargs . get ( parser_cmd ) ) if isinstance ( kws , Namespace ) : kws = vars ( kws ) func = getattr ( self , cmd or 'main' ) ret [ cmd ] = func ( * * kws ) if cmd not in info_parts : ts [ cmd ] = str ( dt . datetime . now ( ) ) exp = self . _experiment project_parts = { 'setup' } projectname = self . _projectname if ( projectname is not None and project_parts . intersection ( ts ) and projectname in self . config . projects ) : self . config . projects [ projectname ] [ 'timestamps' ] . update ( { key : ts [ key ] for key in project_parts . intersection ( ts ) } ) elif not ts : # don't make modifications for info self . no_modification = True if exp is not None and exp in self . config . experiments : projectname = self . projectname try : ts . update ( self . config . projects [ projectname ] [ 'timestamps' ] ) except KeyError : pass if not self . is_archived ( exp ) : self . config . experiments [ exp ] [ 'timestamps' ] . update ( ts ) return Namespace ( * * ret )
7,799
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/__init__.py#L159-L204
[ "def", "create_binding", "(", "self", ",", "vhost", ",", "exchange", ",", "queue", ",", "rt_key", "=", "None", ",", "args", "=", "None", ")", ":", "vhost", "=", "quote", "(", "vhost", ",", "''", ")", "exchange", "=", "quote", "(", "exchange", ",", "''", ")", "queue", "=", "quote", "(", "queue", ",", "''", ")", "body", "=", "json", ".", "dumps", "(", "{", "'routing_key'", ":", "rt_key", ",", "'arguments'", ":", "args", "or", "[", "]", "}", ")", "path", "=", "Client", ".", "urls", "[", "'bindings_between_exch_queue'", "]", "%", "(", "vhost", ",", "exchange", ",", "queue", ")", "binding", "=", "self", ".", "_call", "(", "path", ",", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "Client", ".", "json_headers", ")", "return", "binding" ]