query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
sequencelengths
20
553
Decodes a SymbolicStr
def decode_str ( s , free = False ) : try : if s . len == 0 : return u"" return ffi . unpack ( s . data , s . len ) . decode ( "utf-8" , "replace" ) finally : if free : lib . semaphore_str_free ( ffi . addressof ( s ) )
251,300
https://github.com/getsentry/semaphore/blob/6f260b4092261e893b4debd9a3a7a78232f46c5e/py/semaphore/utils.py#L69-L77
[ "def", "validate_submission", "(", "self", ",", "filename", ")", ":", "self", ".", "_prepare_temp_dir", "(", ")", "# Convert filename to be absolute path, relative path might cause problems", "# with mounting directory in Docker", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "# extract submission", "if", "not", "self", ".", "_extract_submission", "(", "filename", ")", ":", "return", "None", "# verify submission size", "if", "not", "self", ".", "_verify_submission_size", "(", ")", ":", "return", "None", "# Load metadata", "metadata", "=", "self", ".", "_load_and_verify_metadata", "(", ")", "if", "not", "metadata", ":", "return", "None", "submission_type", "=", "metadata", "[", "'type'", "]", "# verify docker container size", "if", "not", "self", ".", "_verify_docker_image_size", "(", "metadata", "[", "'container_gpu'", "]", ")", ":", "return", "None", "# Try to run submission on sample data", "self", ".", "_prepare_sample_data", "(", "submission_type", ")", "if", "not", "self", ".", "_run_submission", "(", "metadata", ")", ":", "logging", ".", "error", "(", "'Failure while running submission'", ")", "return", "None", "if", "not", "self", ".", "_verify_output", "(", "submission_type", ")", ":", "logging", ".", "warning", "(", "'Some of the outputs of your submission are invalid or '", "'missing. You submission still will be evaluation '", "'but you might get lower score.'", ")", "return", "metadata" ]
Encodes a SemaphoreStr
def encode_str ( s , mutable = False ) : rv = ffi . new ( "SemaphoreStr *" ) if isinstance ( s , text_type ) : s = s . encode ( "utf-8" ) if mutable : s = bytearray ( s ) rv . data = ffi . from_buffer ( s ) rv . len = len ( s ) # we have to hold a weak reference here to ensure our string does not # get collected before the string is used. attached_refs [ rv ] = s return rv
251,301
https://github.com/getsentry/semaphore/blob/6f260b4092261e893b4debd9a3a7a78232f46c5e/py/semaphore/utils.py#L80-L92
[ "def", "find_templates", "(", "self", ")", ":", "paths", "=", "set", "(", ")", "for", "loader", "in", "self", ".", "get_loaders", "(", ")", ":", "try", ":", "module", "=", "import_module", "(", "loader", ".", "__module__", ")", "get_template_sources", "=", "getattr", "(", "module", ",", "'get_template_sources'", ",", "loader", ".", "get_template_sources", ")", "template_sources", "=", "get_template_sources", "(", "''", ")", "paths", ".", "update", "(", "[", "t", ".", "name", "if", "isinstance", "(", "t", ",", "Origin", ")", "else", "t", "for", "t", "in", "template_sources", "]", ")", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "pass", "if", "not", "paths", ":", "raise", "CommandError", "(", "\"No template paths found. None of the configured template loaders provided template paths\"", ")", "templates", "=", "set", "(", ")", "for", "path", "in", "paths", ":", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "str", "(", "path", ")", ")", ":", "templates", ".", "update", "(", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "for", "name", "in", "files", "if", "not", "name", ".", "startswith", "(", "'.'", ")", "and", "any", "(", "name", ".", "endswith", "(", "ext", ")", "for", "ext", "in", "self", ".", "template_exts", ")", ")", "if", "not", "templates", ":", "raise", "CommandError", "(", "\"No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct.\"", ")", "return", "templates" ]
Decodes the given uuid value .
def decode_uuid ( value ) : return uuid . UUID ( bytes = bytes ( bytearray ( ffi . unpack ( value . data , 16 ) ) ) )
251,302
https://github.com/getsentry/semaphore/blob/6f260b4092261e893b4debd9a3a7a78232f46c5e/py/semaphore/utils.py#L104-L106
[ "def", "decode", "(", "dinfo", ",", "cio", ")", ":", "argtypes", "=", "[", "ctypes", ".", "POINTER", "(", "DecompressionInfoType", ")", ",", "ctypes", ".", "POINTER", "(", "CioType", ")", "]", "OPENJPEG", ".", "opj_decode", ".", "argtypes", "=", "argtypes", "OPENJPEG", ".", "opj_decode", ".", "restype", "=", "ctypes", ".", "POINTER", "(", "ImageType", ")", "image", "=", "OPENJPEG", ".", "opj_decode", "(", "dinfo", ",", "cio", ")", "return", "image" ]
Runs a quick check to see if cargo fmt is installed .
def has_cargo_fmt ( ) : try : c = subprocess . Popen ( [ "cargo" , "fmt" , "--" , "--help" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE , ) return c . wait ( ) == 0 except OSError : return False
251,303
https://github.com/getsentry/semaphore/blob/6f260b4092261e893b4debd9a3a7a78232f46c5e/scripts/git-precommit-hook.py#L8-L18
[ "def", "mprotect", "(", "self", ",", "lpAddress", ",", "dwSize", ",", "flNewProtect", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_OPERATION", ")", "return", "win32", ".", "VirtualProtectEx", "(", "hProcess", ",", "lpAddress", ",", "dwSize", ",", "flNewProtect", ")" ]
Returns a list of all modified files .
def get_modified_files ( ) : c = subprocess . Popen ( [ "git" , "diff-index" , "--cached" , "--name-only" , "HEAD" ] , stdout = subprocess . PIPE ) return c . communicate ( ) [ 0 ] . splitlines ( )
251,304
https://github.com/getsentry/semaphore/blob/6f260b4092261e893b4debd9a3a7a78232f46c5e/scripts/git-precommit-hook.py#L21-L26
[ "def", "authenticate_heat_admin", "(", "self", ",", "keystone", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating heat admin...'", ")", "ep", "=", "keystone", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'orchestration'", ",", "interface", "=", "'publicURL'", ")", "if", "keystone", ".", "session", ":", "return", "heat_client", ".", "Client", "(", "endpoint", "=", "ep", ",", "session", "=", "keystone", ".", "session", ")", "else", ":", "return", "heat_client", ".", "Client", "(", "endpoint", "=", "ep", ",", "token", "=", "keystone", ".", "auth_token", ")" ]
Return next chunk of data that we would from the file pointer .
def _get_next_chunk ( fp , previously_read_position , chunk_size ) : seek_position , read_size = _get_what_to_read_next ( fp , previously_read_position , chunk_size ) fp . seek ( seek_position ) read_content = fp . read ( read_size ) read_position = seek_position return read_content , read_position
251,305
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L95-L110
[ "def", "services", "(", "self", ")", ":", "self", ".", "_services", "=", "[", "]", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "if", "not", "self", ".", "_url", ".", "endswith", "(", "'/services'", ")", ":", "uURL", "=", "self", ".", "_url", "+", "\"/services\"", "else", ":", "uURL", "=", "self", ".", "_url", "res", "=", "self", ".", "_get", "(", "url", "=", "uURL", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")", "for", "k", ",", "v", "in", "res", ".", "items", "(", ")", ":", "if", "k", "==", "\"foldersDetail\"", ":", "for", "item", "in", "v", ":", "if", "'isDefault'", "in", "item", "and", "item", "[", "'isDefault'", "]", "==", "False", ":", "fURL", "=", "self", ".", "_url", "+", "\"/services/\"", "+", "item", "[", "'folderName'", "]", "resFolder", "=", "self", ".", "_get", "(", "url", "=", "fURL", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")", "for", "k1", ",", "v1", "in", "resFolder", ".", "items", "(", ")", ":", "if", "k1", "==", "\"services\"", ":", "self", ".", "_checkservice", "(", "k1", ",", "v1", ",", "fURL", ")", "elif", "k", "==", "\"services\"", ":", "self", ".", "_checkservice", "(", "k", ",", "v", ",", "uURL", ")", "return", "self", ".", "_services" ]
Return information on which file pointer position to read from and how many bytes .
def _get_what_to_read_next ( fp , previously_read_position , chunk_size ) : seek_position = max ( previously_read_position - chunk_size , 0 ) read_size = chunk_size # examples: say, our new_lines are potentially "\r\n", "\n", "\r" # find a reading point where it is not "\n", rewind further if necessary # if we have "\r\n" and we read in "\n", # the next iteration would treat "\r" as a different new line. # Q: why don't I just check if it is b"\n", but use a function ? # A: so that we can potentially expand this into generic sets of separators, later on. while seek_position > 0 : fp . seek ( seek_position ) if _is_partially_read_new_line ( fp . read ( 1 ) ) : seek_position -= 1 read_size += 1 # as we rewind further, let's make sure we read more to compensate else : break # take care of special case when we are back to the beginnin of the file read_size = min ( previously_read_position - seek_position , read_size ) return seek_position , read_size
251,306
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L113-L143
[ "def", "check_internal_consistency", "(", "self", ",", "*", "*", "kwargs", ")", ":", "inconsistent_vars", "=", "{", "}", "for", "variable", "in", "self", ".", "variables", "(", ")", ":", "diff_agg", "=", "self", ".", "check_aggregate", "(", "variable", ",", "*", "*", "kwargs", ")", "if", "diff_agg", "is", "not", "None", ":", "inconsistent_vars", "[", "variable", "+", "\"-aggregate\"", "]", "=", "diff_agg", "diff_regional", "=", "self", ".", "check_aggregate_region", "(", "variable", ",", "*", "*", "kwargs", ")", "if", "diff_regional", "is", "not", "None", ":", "inconsistent_vars", "[", "variable", "+", "\"-regional\"", "]", "=", "diff_regional", "return", "inconsistent_vars", "if", "inconsistent_vars", "else", "None" ]
Remove a single instance of new line at the end of l if it exists .
def _remove_trailing_new_line ( l ) : # replace only 1 instance of newline # match longest line first (hence the reverse=True), we want to match "\r\n" rather than "\n" if we can for n in sorted ( new_lines_bytes , key = lambda x : len ( x ) , reverse = True ) : if l . endswith ( n ) : remove_new_line = slice ( None , - len ( n ) ) return l [ remove_new_line ] return l
251,307
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L146-L158
[ "def", "author_info", "(", "name", ",", "contact", "=", "None", ",", "public_key", "=", "None", ")", ":", "return", "Storage", "(", "name", "=", "name", ",", "contact", "=", "contact", ",", "public_key", "=", "public_key", ")" ]
Return - 1 if read_buffer does not contain new line otherwise the position of the rightmost newline .
def _find_furthest_new_line ( read_buffer ) : new_line_positions = [ read_buffer . rfind ( n ) for n in new_lines_bytes ] return max ( new_line_positions )
251,308
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L161-L171
[ "def", "_persist_inplace", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# access .data to coerce everything to numpy or dask arrays", "lazy_data", "=", "{", "k", ":", "v", ".", "_data", "for", "k", ",", "v", "in", "self", ".", "variables", ".", "items", "(", ")", "if", "isinstance", "(", "v", ".", "_data", ",", "dask_array_type", ")", "}", "if", "lazy_data", ":", "import", "dask", "# evaluate all the dask arrays simultaneously", "evaluated_data", "=", "dask", ".", "persist", "(", "*", "lazy_data", ".", "values", "(", ")", ",", "*", "*", "kwargs", ")", "for", "k", ",", "data", "in", "zip", "(", "lazy_data", ",", "evaluated_data", ")", ":", "self", ".", "variables", "[", "k", "]", ".", "data", "=", "data", "return", "self" ]
Add additional bytes content as read from the read_position .
def add_to_buffer ( self , content , read_position ) : self . read_position = read_position if self . read_buffer is None : self . read_buffer = content else : self . read_buffer = content + self . read_buffer
251,309
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L29-L40
[ "def", "catalogFactory", "(", "name", ",", "*", "*", "kwargs", ")", ":", "fn", "=", "lambda", "member", ":", "inspect", ".", "isclass", "(", "member", ")", "and", "member", ".", "__module__", "==", "__name__", "catalogs", "=", "odict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "fn", ")", ")", "if", "name", "not", "in", "list", "(", "catalogs", ".", "keys", "(", ")", ")", ":", "msg", "=", "\"%s not found in catalogs:\\n %s\"", "%", "(", "name", ",", "list", "(", "kernels", ".", "keys", "(", ")", ")", ")", "logger", ".", "error", "(", "msg", ")", "msg", "=", "\"Unrecognized catalog: %s\"", "%", "name", "raise", "Exception", "(", "msg", ")", "return", "catalogs", "[", "name", "]", "(", "*", "*", "kwargs", ")" ]
Return True if there is a line that the buffer can return False otherwise .
def yieldable ( self ) : if self . read_buffer is None : return False t = _remove_trailing_new_line ( self . read_buffer ) n = _find_furthest_new_line ( t ) if n >= 0 : return True # we have read in entire file and have some unprocessed lines if self . read_position == 0 and self . read_buffer is not None : return True return False
251,310
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L42-L55
[ "def", "_read_config", "(", "config_location", ")", ":", "global", "LOGGING_CONFIG", "with", "open", "(", "config_location", ",", "\"r\"", ")", "as", "config_loc", ":", "cfg_file", "=", "json", ".", "load", "(", "config_loc", ")", "if", "\"logging\"", "in", "cfg_file", ":", "log_dict", "=", "cfg_file", ".", "get", "(", "\"logging\"", ")", "with", "open", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "__file__", ",", "os", ".", "path", ".", "pardir", ",", "'logging_schema.json'", ")", ")", ")", "as", "schema_file", ":", "logging_schema", "=", "json", ".", "load", "(", "schema_file", ")", "jsonschema", ".", "validate", "(", "log_dict", ",", "logging_schema", ")", "merged", "=", "jsonmerge", ".", "merge", "(", "LOGGING_CONFIG", ",", "log_dict", ")", "LOGGING_CONFIG", "=", "merged" ]
Return a new line if it is available .
def return_line ( self ) : assert ( self . yieldable ( ) ) t = _remove_trailing_new_line ( self . read_buffer ) i = _find_furthest_new_line ( t ) if i >= 0 : l = i + 1 after_new_line = slice ( l , None ) up_to_include_new_line = slice ( 0 , l ) r = t [ after_new_line ] self . read_buffer = t [ up_to_include_new_line ] else : # the case where we have read in entire file and at the "last" line r = t self . read_buffer = None return r
251,311
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L57-L76
[ "def", "setOverlayTransformOverlayRelative", "(", "self", ",", "ulOverlayHandle", ",", "ulOverlayHandleParent", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTransformOverlayRelative", "pmatParentOverlayToOverlayTransform", "=", "HmdMatrix34_t", "(", ")", "result", "=", "fn", "(", "ulOverlayHandle", ",", "ulOverlayHandleParent", ",", "byref", "(", "pmatParentOverlayToOverlayTransform", ")", ")", "return", "result", ",", "pmatParentOverlayToOverlayTransform" ]
Read in additional chunks until it is yieldable .
def read_until_yieldable ( self ) : while not self . yieldable ( ) : read_content , read_position = _get_next_chunk ( self . fp , self . read_position , self . chunk_size ) self . add_to_buffer ( read_content , read_position )
251,312
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L78-L82
[ "def", "register", "(", "cls", ",", "interface_type", ",", "resource_class", ")", ":", "def", "_internal", "(", "python_class", ")", ":", "if", "(", "interface_type", ",", "resource_class", ")", "in", "cls", ".", "_session_classes", ":", "logger", ".", "warning", "(", "'%s is already registered in the ResourceManager. '", "'Overwriting with %s'", "%", "(", "(", "interface_type", ",", "resource_class", ")", ",", "python_class", ")", ")", "python_class", ".", "session_type", "=", "(", "interface_type", ",", "resource_class", ")", "cls", ".", "_session_classes", "[", "(", "interface_type", ",", "resource_class", ")", "]", "=", "python_class", "return", "python_class", "return", "_internal" ]
Returns unicode string from the last line until the beginning of file .
def next ( self ) : # Using binary mode, because some encodings such as "utf-8" use variable number of # bytes to encode different Unicode points. # Without using binary mode, we would probably need to understand each encoding more # and do the seek operations to find the proper boundary before issuing read if self . closed : raise StopIteration if self . __buf . has_returned_every_line ( ) : self . close ( ) raise StopIteration self . __buf . read_until_yieldable ( ) r = self . __buf . return_line ( ) return r . decode ( self . encoding )
251,313
https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/file_read_backwards.py#L91-L112
[ "def", "query", "(", "self", ",", "terms", "=", "None", ",", "negated_terms", "=", "None", ")", ":", "if", "terms", "is", "None", ":", "terms", "=", "[", "]", "matches_all", "=", "'owl:Thing'", "in", "terms", "if", "negated_terms", "is", "None", ":", "negated_terms", "=", "[", "]", "termset", "=", "set", "(", "terms", ")", "negated_termset", "=", "set", "(", "negated_terms", ")", "matches", "=", "[", "]", "n_terms", "=", "len", "(", "termset", ")", "for", "subj", "in", "self", ".", "subjects", ":", "if", "matches_all", "or", "len", "(", "termset", ".", "intersection", "(", "self", ".", "inferred_types", "(", "subj", ")", ")", ")", "==", "n_terms", ":", "if", "len", "(", "negated_termset", ".", "intersection", "(", "self", ".", "inferred_types", "(", "subj", ")", ")", ")", "==", "0", ":", "matches", ".", "append", "(", "subj", ")", "return", "matches" ]
if we have a chat_channel_name kwarg have the response include that channel name so the javascript knows to subscribe to that channel ...
def home ( request , chat_channel_name = None ) : if not chat_channel_name : chat_channel_name = 'homepage' context = { 'address' : chat_channel_name , 'history' : [ ] , } if ChatMessage . objects . filter ( channel = chat_channel_name ) . exists ( ) : context [ 'history' ] = ChatMessage . objects . filter ( channel = chat_channel_name ) # TODO add https websocket_prefix = "ws" websocket_port = 9000 context [ 'websocket_prefix' ] = websocket_prefix context [ 'websocket_port' ] = websocket_port return render ( request , 'chat.html' , context )
251,314
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/examples/django_hx_chatserver/example_app/chat/views.py#L9-L37
[ "def", "setOverlayTexelAspect", "(", "self", ",", "ulOverlayHandle", ",", "fTexelAspect", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setOverlayTexelAspect", "result", "=", "fn", "(", "ulOverlayHandle", ",", "fTexelAspect", ")", "return", "result" ]
Decides which version of HendrixDeploy to use and then launches it .
def hendrixLauncher ( action , options , with_tiempo = False ) : if options [ 'key' ] and options [ 'cert' ] and options [ 'cache' ] : from hendrix . deploy import hybrid HendrixDeploy = hybrid . HendrixDeployHybrid elif options [ 'key' ] and options [ 'cert' ] : from hendrix . deploy import tls HendrixDeploy = tls . HendrixDeployTLS elif options [ 'cache' ] : HendrixDeploy = cache . HendrixDeployCache else : HendrixDeploy = base . HendrixDeploy if with_tiempo : deploy = HendrixDeploy ( action = 'start' , options = options ) deploy . run ( ) else : deploy = HendrixDeploy ( action , options ) deploy . run ( )
251,315
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L67-L87
[ "def", "exclude_types", "(", "self", ",", "*", "objs", ")", ":", "for", "o", "in", "objs", ":", "for", "t", "in", "_keytuple", "(", "o", ")", ":", "if", "t", "and", "t", "not", "in", "self", ".", "_excl_d", ":", "self", ".", "_excl_d", "[", "t", "]", "=", "0" ]
encompasses all the logic for reloading observer .
def logReload ( options ) : event_handler = Reload ( options ) observer = Observer ( ) observer . schedule ( event_handler , path = '.' , recursive = True ) observer . start ( ) try : while True : time . sleep ( 1 ) except KeyboardInterrupt : observer . stop ( ) pid = os . getpid ( ) chalk . eraser ( ) chalk . green ( '\nHendrix successfully closed.' ) os . kill ( pid , 15 ) observer . join ( ) exit ( '\n' )
251,316
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L100-L118
[ "def", "readTempC", "(", "self", ")", ":", "# Read temperature register value.", "t", "=", "self", ".", "_device", ".", "readU16BE", "(", "MCP9808_REG_AMBIENT_TEMP", ")", "self", ".", "_logger", ".", "debug", "(", "'Raw ambient temp register value: 0x{0:04X}'", ".", "format", "(", "t", "&", "0xFFFF", ")", ")", "# Scale and convert to signed value.", "temp", "=", "(", "t", "&", "0x0FFF", ")", "/", "16.0", "if", "t", "&", "0x1000", ":", "temp", "-=", "256.0", "return", "temp" ]
launch acts on the user specified action and options by executing Hedrix . run
def launch ( * args , * * options ) : action = args [ 0 ] if options [ 'reload' ] : logReload ( options ) else : assignDeploymentInstance ( action , options )
251,317
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L121-L130
[ "def", "get_inconsistent_fieldnames", "(", ")", ":", "field_name_list", "=", "[", "]", "for", "fieldset_title", ",", "fields_list", "in", "settings", ".", "CONFIG_FIELDSETS", ".", "items", "(", ")", ":", "for", "field_name", "in", "fields_list", ":", "field_name_list", ".", "append", "(", "field_name", ")", "if", "not", "field_name_list", ":", "return", "{", "}", "return", "set", "(", "set", "(", "settings", ".", "CONFIG", ".", "keys", "(", ")", ")", "-", "set", "(", "field_name_list", ")", ")" ]
Find the settings module dot path within django s manage . py file
def findSettingsModule ( ) : try : with open ( 'manage.py' , 'r' ) as manage : manage_contents = manage . read ( ) search = re . search ( r"([\"\'](?P<module>[a-z\.]+)[\"\'])" , manage_contents ) if search : # django version < 1.7 settings_mod = search . group ( "module" ) else : # in 1.7, manage.py settings declaration looks like: # os.environ.setdefault( # "DJANGO_SETTINGS_MODULE", "example_app.settings" # ) search = re . search ( "\".*?\"(,\\s)??\"(?P<module>.*?)\"\\)$" , manage_contents , re . I | re . S | re . M ) settings_mod = search . group ( "module" ) os . environ . setdefault ( 'DJANGO_SETTINGS_MODULE' , settings_mod ) except IOError as e : msg = ( str ( e ) + '\nPlease ensure that you are in the same directory ' 'as django\'s "manage.py" file.' ) raise IOError ( chalk . red ( msg ) , None , sys . exc_info ( ) [ 2 ] ) except AttributeError : settings_mod = '' return settings_mod
251,318
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L133-L165
[ "def", "generate_timeline", "(", "usnjrnl", ",", "filesystem_content", ")", ":", "journal_content", "=", "defaultdict", "(", "list", ")", "for", "event", "in", "usnjrnl", ":", "journal_content", "[", "event", ".", "inode", "]", ".", "append", "(", "event", ")", "for", "event", "in", "usnjrnl", ":", "try", ":", "dirent", "=", "lookup_dirent", "(", "event", ",", "filesystem_content", ",", "journal_content", ")", "yield", "UsnJrnlEvent", "(", "dirent", ".", "inode", ",", "dirent", ".", "path", ",", "dirent", ".", "size", ",", "dirent", ".", "allocated", ",", "event", ".", "timestamp", ",", "event", ".", "changes", ",", "event", ".", "attributes", ")", "except", "LookupError", "as", "error", ":", "LOGGER", ".", "debug", "(", "error", ")" ]
This function is called by the hxw script . It takes no arguments and returns an instance of HendrixDeploy
def subprocessLaunch ( ) : if not redis_available : raise RedisException ( "can't launch this subprocess without tiempo/redis." ) try : action = 'start' options = REDIS . get ( 'worker_args' ) assignDeploymentInstance ( action = 'start' , options = options ) except Exception : chalk . red ( '\n Encountered an unhandled exception while trying to %s hendrix.\n' % action , pipe = chalk . stderr ) raise
251,319
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L227-L240
[ "def", "validate_inferred_freq", "(", "freq", ",", "inferred_freq", ",", "freq_infer", ")", ":", "if", "inferred_freq", "is", "not", "None", ":", "if", "freq", "is", "not", "None", "and", "freq", "!=", "inferred_freq", ":", "raise", "ValueError", "(", "'Inferred frequency {inferred} from passed '", "'values does not conform to passed frequency '", "'{passed}'", ".", "format", "(", "inferred", "=", "inferred_freq", ",", "passed", "=", "freq", ".", "freqstr", ")", ")", "elif", "freq", "is", "None", ":", "freq", "=", "inferred_freq", "freq_infer", "=", "False", "return", "freq", ",", "freq_infer" ]
The function to execute when running hx
def main ( args = None ) : if args is None : args = sys . argv [ 1 : ] options , args = HendrixOptionParser . parse_args ( args ) options = vars ( options ) try : action = args [ 0 ] except IndexError : HendrixOptionParser . print_help ( ) return exposeProject ( options ) options = djangoVsWsgi ( options ) options = devFriendly ( options ) redirect = noiseControl ( options ) try : launch ( * args , * * options ) except Exception : chalk . red ( '\n Encountered an unhandled exception while trying to %s hendrix.\n' % action , pipe = chalk . stderr ) raise
251,320
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/ux.py#L243-L268
[ "def", "list_kadastrale_afdelingen", "(", "self", ")", ":", "def", "creator", "(", ")", ":", "gemeentes", "=", "self", ".", "list_gemeenten", "(", ")", "res", "=", "[", "]", "for", "g", "in", "gemeentes", ":", "res", "+=", "self", ".", "list_kadastrale_afdelingen_by_gemeente", "(", "g", ")", "return", "res", "if", "self", ".", "caches", "[", "'permanent'", "]", ".", "is_configured", ":", "key", "=", "'list_afdelingen_rest'", "afdelingen", "=", "self", ".", "caches", "[", "'permanent'", "]", ".", "get_or_create", "(", "key", ",", "creator", ")", "else", ":", "afdelingen", "=", "creator", "(", ")", "return", "afdelingen" ]
extends handleHeader to save headers to a local response object
def handleHeader ( self , key , value ) : key_lower = key . lower ( ) if key_lower == 'location' : value = self . modLocationPort ( value ) self . _response . headers [ key_lower ] = value if key_lower != 'cache-control' : # This causes us to not pass on the 'cache-control' parameter # to the browser # TODO: we should have a means of giving the user the option to # configure how they want to manage browser-side cache control proxy . ProxyClient . handleHeader ( self , key , value )
251,321
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L38-L49
[ "def", "beacon", "(", "config", ")", ":", "parts", "=", "psutil", ".", "disk_partitions", "(", "all", "=", "True", ")", "ret", "=", "[", "]", "for", "mounts", "in", "config", ":", "mount", "=", "next", "(", "iter", "(", "mounts", ")", ")", "# Because we're using regular expressions", "# if our mount doesn't end with a $, insert one.", "mount_re", "=", "mount", "if", "not", "mount", ".", "endswith", "(", "'$'", ")", ":", "mount_re", "=", "'{0}$'", ".", "format", "(", "mount", ")", "if", "salt", ".", "utils", ".", "platform", ".", "is_windows", "(", ")", ":", "# mount_re comes in formatted with a $ at the end", "# can be `C:\\\\$` or `C:\\\\\\\\$`", "# re string must be like `C:\\\\\\\\` regardless of \\\\ or \\\\\\\\", "# also, psutil returns uppercase", "mount_re", "=", "re", ".", "sub", "(", "r':\\\\\\$'", ",", "r':\\\\\\\\'", ",", "mount_re", ")", "mount_re", "=", "re", ".", "sub", "(", "r':\\\\\\\\\\$'", ",", "r':\\\\\\\\'", ",", "mount_re", ")", "mount_re", "=", "mount_re", ".", "upper", "(", ")", "for", "part", "in", "parts", ":", "if", "re", ".", "match", "(", "mount_re", ",", "part", ".", "mountpoint", ")", ":", "_mount", "=", "part", ".", "mountpoint", "try", ":", "_current_usage", "=", "psutil", ".", "disk_usage", "(", "_mount", ")", "except", "OSError", ":", "log", ".", "warning", "(", "'%s is not a valid mount point.'", ",", "_mount", ")", "continue", "current_usage", "=", "_current_usage", ".", "percent", "monitor_usage", "=", "mounts", "[", "mount", "]", "if", "'%'", "in", "monitor_usage", ":", "monitor_usage", "=", "re", ".", "sub", "(", "'%'", ",", "''", ",", "monitor_usage", ")", "monitor_usage", "=", "float", "(", "monitor_usage", ")", "if", "current_usage", ">=", "monitor_usage", ":", "ret", ".", "append", "(", "{", "'diskusage'", ":", "current_usage", ",", "'mount'", ":", "_mount", "}", ")", "return", "ret" ]
extends handleStatus to instantiate a local response object
def handleStatus ( self , version , code , message ) : proxy . ProxyClient . handleStatus ( self , version , code , message ) # client.Response is currently just a container for needed data self . _response = client . Response ( version , code , message , { } , None )
251,322
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L51-L55
[ "def", "sphere_volume", "(", "R", ",", "n", ")", ":", "return", "(", "(", "np", ".", "pi", "**", "(", "n", "/", "2.0", ")", ")", "/", "scipy", ".", "special", ".", "gamma", "(", "n", "/", "2.0", "+", "1", ")", ")", "*", "R", "**", "n" ]
Ensures that the location port is a the given port value Used in handleHeader
def modLocationPort ( self , location ) : components = urlparse . urlparse ( location ) reverse_proxy_port = self . father . getHost ( ) . port reverse_proxy_host = self . father . getHost ( ) . host # returns an ordered dict of urlparse.ParseResult components _components = components . _asdict ( ) _components [ 'netloc' ] = '%s:%d' % ( reverse_proxy_host , reverse_proxy_port ) return urlparse . urlunparse ( _components . values ( ) )
251,323
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L57-L70
[ "def", "execute_sql", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "_allow_sync", ",", "(", "\"Error, sync query is not allowed! Call the `.set_allow_sync()` \"", "\"or use the `.allow_sync()` context manager.\"", ")", "if", "self", ".", "_allow_sync", "in", "(", "logging", ".", "ERROR", ",", "logging", ".", "WARNING", ")", ":", "logging", ".", "log", "(", "self", ".", "_allow_sync", ",", "\"Error, sync query is not allowed: %s %s\"", "%", "(", "str", "(", "args", ")", ",", "str", "(", "kwargs", ")", ")", ")", "return", "super", "(", ")", ".", "execute_sql", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Sends the content to the browser and keeps a local copy of it . buffer is just a str of the content to be shown father is the intial request .
def handleResponsePart ( self , buffer ) : self . father . write ( buffer ) self . buffer . write ( buffer )
251,324
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L92-L99
[ "def", "any", "(", "self", ",", "array", ",", "role", "=", "None", ")", ":", "sum_in_entity", "=", "self", ".", "sum", "(", "array", ",", "role", "=", "role", ")", "return", "(", "sum_in_entity", ">", "0", ")" ]
This is necessary because the parent class would call proxy . ReverseProxyResource instead of CacheProxyResource
def getChild ( self , path , request ) : return CacheProxyResource ( self . host , self . port , self . path + '/' + urlquote ( path , safe = "" ) , self . reactor )
251,325
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L148-L156
[ "def", "listen", "(", "self", ")", ":", "import", "select", "while", "self", ".", "connected", ":", "r", ",", "w", ",", "e", "=", "select", ".", "select", "(", "(", "self", ".", "ws", ".", "sock", ",", ")", ",", "(", ")", ",", "(", ")", ")", "if", "r", ":", "self", ".", "on_message", "(", ")", "elif", "e", ":", "self", ".", "subscriber", ".", "on_sock_error", "(", "e", ")", "self", ".", "disconnect", "(", ")" ]
Retrieve a static or dynamically generated child resource from me .
def getChildWithDefault ( self , path , request ) : cached_resource = self . getCachedResource ( request ) if cached_resource : reactor . callInThread ( responseInColor , request , '200 OK' , cached_resource , 'Cached' , 'underscore' ) return cached_resource # original logic if path in self . children : return self . children [ path ] return self . getChild ( path , request )
251,326
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L158-L176
[ "def", "calc_update_events", "(", "self", ",", "asin_to_progress", ")", ":", "new_events", "=", "[", "]", "for", "asin", ",", "new_progress", "in", "asin_to_progress", ".", "iteritems", "(", ")", ":", "try", ":", "book_snapshot", "=", "self", ".", "get_book", "(", "asin", ")", "except", "KeyError", ":", "new_events", ".", "append", "(", "AddEvent", "(", "asin", ")", ")", "else", ":", "if", "book_snapshot", ".", "status", "==", "ReadingStatus", ".", "CURRENT", ":", "change", "=", "new_progress", "-", "book_snapshot", ".", "progress", "if", "change", ">", "0", ":", "new_events", ".", "append", "(", "ReadEvent", "(", "asin", ",", "change", ")", ")", "return", "new_events" ]
Render a request by forwarding it to the proxied server .
def render ( self , request ) : # set up and evaluate a connection to the target server if self . port == 80 : host = self . host else : host = "%s:%d" % ( self . host , self . port ) request . requestHeaders . addRawHeader ( 'host' , host ) request . content . seek ( 0 , 0 ) qs = urlparse . urlparse ( request . uri ) [ 4 ] if qs : rest = self . path + '?' + qs else : rest = self . path global_self = self . getGlobalSelf ( ) clientFactory = self . proxyClientFactoryClass ( request . method , rest , request . clientproto , request . getAllHeaders ( ) , request . content . read ( ) , request , global_self # this is new ) self . reactor . connectTCP ( self . host , self . port , clientFactory ) return NOT_DONE_YET
251,327
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L178-L204
[ "def", "materialize_directories", "(", "self", ",", "directories_paths_and_digests", ")", ":", "# Ensure there isn't more than one of the same directory paths and paths do not have the same prefix.", "dir_list", "=", "[", "dpad", ".", "path", "for", "dpad", "in", "directories_paths_and_digests", "]", "check_no_overlapping_paths", "(", "dir_list", ")", "result", "=", "self", ".", "_native", ".", "lib", ".", "materialize_directories", "(", "self", ".", "_scheduler", ",", "self", ".", "_to_value", "(", "_DirectoriesToMaterialize", "(", "directories_paths_and_digests", ")", ")", ",", ")", "return", "self", ".", "_raise_or_return", "(", "result", ")" ]
This searches the reactor for the original instance of CacheProxyResource . This is necessary because with each call of getChild a new instance of CacheProxyResource is created .
def getGlobalSelf ( self ) : transports = self . reactor . getReaders ( ) for transport in transports : try : resource = transport . factory . resource if isinstance ( resource , self . __class__ ) and resource . port == self . port : return resource except AttributeError : pass return
251,328
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/resource.py#L209-L223
[ "def", "read_fits_region", "(", "filename", ",", "errors", "=", "'strict'", ")", ":", "regions", "=", "[", "]", "hdul", "=", "fits", ".", "open", "(", "filename", ")", "for", "hdu", "in", "hdul", ":", "if", "hdu", ".", "name", "==", "'REGION'", ":", "table", "=", "Table", ".", "read", "(", "hdu", ")", "wcs", "=", "WCS", "(", "hdu", ".", "header", ",", "keysel", "=", "[", "'image'", ",", "'binary'", ",", "'pixel'", "]", ")", "regions_list", "=", "FITSRegionParser", "(", "table", ",", "errors", ")", ".", "shapes", ".", "to_regions", "(", ")", "for", "reg", "in", "regions_list", ":", "regions", ".", "append", "(", "reg", ".", "to_sky", "(", "wcs", ")", ")", "return", "regions" ]
Takes data which we assume is json encoded If data has a subject_id attribute we pass that to the dispatcher as the subject_id so it will get carried through into any return communications and be identifiable to the client
def dataReceived ( self , data ) : try : address = self . guid data = json . loads ( data ) threads . deferToThread ( send_signal , self . dispatcher , data ) if 'hx_subscribe' in data : return self . dispatcher . subscribe ( self . transport , data ) if 'address' in data : address = data [ 'address' ] else : address = self . guid self . dispatcher . send ( address , data ) except Exception as e : raise self . dispatcher . send ( self . guid , { 'message' : data , 'error' : str ( e ) } )
251,329
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/resources.py#L26-L57
[ "def", "overwrite", "(", "self", ",", "text", ",", "size", "=", "None", ")", ":", "self", ".", "_io", ".", "overwrite", "(", "text", ",", "size", "=", "size", ")" ]
establish the address of this new connection and add it to the list of sockets managed by the dispatcher
def connectionMade ( self ) : self . transport . uid = str ( uuid . uuid1 ( ) ) self . guid = self . dispatcher . add ( self . transport ) self . dispatcher . send ( self . guid , { 'setup_connection' : self . guid } )
251,330
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/resources.py#L59-L71
[ "def", "create", "(", "cls", ",", "destination", ")", ":", "mdb_gz_b64", "=", "\"\"\"\\\n H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a\n jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+\n qKgIIHL8Znb39u72znWJiWP3+9l473fzm/nNY3cdf2fmbBJEPdO9E+nebLq+fWC6vrWZOImen9D7\n 9sR+vPPNE0PZxo/TE5879mj+yNc3/OzAD2bXv3DmV9/o/8PZnxxr+/fDL2w79ulzN7e+/sS/zvzz\n w3+N1z28p3PTfQ3nfn/m2YmeFS2no89uWnvqwO5HUvd/5Phr938tes3j/zm5+qT41J8/P/iZx87/\n +qHrjgyduubG1t/+7eWB2XztTNuT+1clZt9c2/e7HRGizevWEwAAAAAAAACAhUEIwvE+PoRIO8K7\n FzT6obPPwTMBAAAAAAAAAABcfpzPXwya+Ispo1xlEO2KEEX9eaGyWnrqyKQ60tQ0AcNZRcR1RYuy\n +XZCxoqRzmaMI6cKGRJuJVrIEZUOQ9UrHStUYpyzKkdNmSPFDkM6aguhXMdVHCMuHXE2Suu4IFQJ\n l6CErNWUDouDlbdKOZIcrKLD4S5WdNhqIEodqlVaofKgVTHpiBQ6uLG0uaKsuYbf3IS8BmV1qFAm\n j1Z5Hbp06GWDKC+DTS00SRN8DFA/TXNfW6mXX3upj7+mOHWllzLAObN8du0gdSdlKO3ZcWqjMbaH\n uOQqtidViRF+P0HbOH2c3xm0lfMb1EH7uHZ5vp32c+ks+5PqfSeXS9NejjTAvZQpd7J3kuuJFqLE\n qYvuVa3Ocqk7OVXWNMFxZPRVtJ1zSXuCBrlkh+rjEF1Zlt5Dw6qN0xx5Bx3gGgbowVo56EIjkc9T\n xX9Jdd+5PKDOD6q3VQvwv7qiZ8st419cdYHlo6iuriF8X4HA590AsodXhvrsj0yMDPnAuI+ZvOrq\n 1o7K51Hdy7a8cdXNm5AedbfG5W3j3lOybxFZKb6zAgAAAAAAsNzQxAlbvnYJV3VcUU3/S2luBIKF\n ha+IlWp+wxW4IiRXRSXxKeNU1eOxUuUbSOIINbEM7WT506ZE3LASgCOeYJWCMcnCsI/u8eSsFEYR\n lnlbWa6+u0jTYqSkvuQL9G5CLFwTRBMAAAAAAAAAgMtW/79lyVdLKxW7oqDF3bXOniib0UD/m/xq\n loWqvFwt3DX/mrLNALIu3V35NkpK1JDmL+2XOmr9pf1gKiFY4I672wc0mveaf6zaenyKmljPT6t5\n hT7a6y13y0XqjFpwneJjRC0oRwvL3eUL2fHCcuyGIntjhTkDuZCd5Vc5j+HNUMyx+myYcpHW5YG5\n ZijUdbg2VFu4ZzzcHFM3seQLAAAAAAAAAMtc//9S6cm1emX97ytK1v81rHelhtfVfAFnseZXRdV9\n Ad7+dhGS5kbl3eqe/K8pU/nnYwX5X2VeoLbCZwHi7txD6aTELabnoLJ5AfPFC8JmFd3Pun+MlfM4\n q/846/4s62i5+8Dmc7EvSVN0UG2tL00p1uPXqZTt/G5QqX+5lbufz+mSctVzFce6upBrTG3Fd+cn\n pmiYrUyw8+GNfL4hn8/k83qZrVlyGzgPeqbhjcOqx7KMEZRpU/MPQ+rsldEtuYm8vExkznoMS+6b\n KC5TZRt8wVf4xEkFX4V5D/X2vYz1/EcR8yMAAAAAAACAJY0Qf/d3vLPUlb//b4Nzzv6W3Wevtl+1\n vmxts2LWTxOHErcm3jGfMUfNG0yMGQAAAAAAeJ/8rLwAMXIYRgCARFv8IIaYtKpGqCdqlN/2kupD\n /ob67qXhsi0lDh2Vp6728faO9tHuUflfWJ1wE0e6724f35XuG71r16Dr0FwH573by6rKi0N7RveN\n tnd6aTVBWrpjd3fnuJtsBMnDk90ju7zckSA5XGGtdGrK2dWhUnRcMgAAAAAAAAD4v2CIV6vqf82I\n Jusbcwsy7wkWSf/n1JQNq/Oc+uQGq/ecmsphYZ6Tn6XwRLjwxb7mTxDoakLgURUFshwAAAAAAAAA\n ljpCrHZ8W/f2/2NUAAAAAAAAAAAAhXH5RLm4IIbotqot7hbW/0MGWCp46/+pgpHwjZS3IyAlfMPy\n tgakNN+wfcPxNgukdN9I+kadt30gZfhGjW+s8I2V3s6CVNTbWZCK+Eatb3zAN1Z5mw5SMd+I+wZ+\n +QQAAAAAAAAA/K8IcdT27Zqi3/+HkQEAAAAAAAAAsGgkMQQLjSHqbQPDAAAAAAAAAAAALGuw/g8A\n AAAAAAAA4DJUqwsQI7cQDWlcLiMq1/9rcGMBAAAAAAAAAADLGuh/AAAAAAAAAAAA+h8AAAAAAAAA\n AABLHyHusDTPjtLzTtoxnRftUftqe8YatDA+AAAAAAAAAPDeqJN/KVt+et0R9PYnzz7W8PrZRv+V\n HblO6qEDNEXbaYDGqJemaYQmaYJThtnK8Gvzb1opfDRTPZmUlxUY86qgm/ZyFVkOOqCC3kLhoyEI\n qs8raBO10O0q3EYKH+uDcNq8wnVRH93D7evnYZhHG5kkB3a0OYO2ctCWV9ZR+FhT0l2HCzl6xVBz\n XZyPUvi4taTjcwRuVUF7uYW9HMy9MJspfGwMAoo5A+5Qwca8UHN2WogeU/fu0ito1vmjM+M85zzp\n fNG5zxl2djrNzk3O9+0m+yWrx2q0fpH4buJ4Yk3ig4lvmkfxx9gBAAAAAAC4OAylQfJ5h5pfSVCc\n f853gqSmWPSZux6xjUznltH2HT/flNu7++0NZ7/07cg/vnPbVu30y6d/NLvlabPh+j81v/Xc5g9l\n 1h2f+epn9+VPdN90OHHvU50fm94y/ZXvWQ/tP/yJG/NH3llz8A79tlNPG72DHSePHdzz2s3XPzVj\n vzSUvSHjVys1Rv5CSUv8pEvcEqkbV/KX35JaQ+npikmRS9o4rtYIt8RYnJa4Ou6SV6stTm+l7rcX\n q9qSy+23pCVIcgV/SZKuJj5CSRc4Y/PpkiesLJcI53J37NvFuQzv4peGL0/SypP+C+45xVAAMAEA\n \"\"\"", "pristine", "=", "StringIO", "(", ")", "pristine", ".", "write", "(", "base64", ".", "b64decode", "(", "mdb_gz_b64", ")", ")", "pristine", ".", "seek", "(", "0", ")", "pristine", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "pristine", ",", "mode", "=", "'rb'", ")", "with", "open", "(", "destination", ",", "'wb'", ")", "as", "handle", ":", "shutil", ".", "copyfileobj", "(", "pristine", ",", "handle", ")", "return", "cls", "(", "destination", ")" ]
Helper function to generate the text content needed to create an init . d executable
def generateInitd ( conf_file ) : allowed_opts = [ 'virtualenv' , 'project_path' , 'settings' , 'processes' , 'http_port' , 'cache' , 'cache_port' , 'https_port' , 'key' , 'cert' ] base_opts = [ '--daemonize' , ] # always daemonize options = base_opts with open ( conf_file , 'r' ) as cfg : conf = yaml . load ( cfg ) conf_specs = set ( conf . keys ( ) ) if len ( conf_specs - set ( allowed_opts ) ) : raise RuntimeError ( 'Improperly configured.' ) try : virtualenv = conf . pop ( 'virtualenv' ) project_path = conf . pop ( 'project_path' ) except : raise RuntimeError ( 'Improperly configured.' ) cache = False if 'cache' in conf : cache = conf . pop ( 'cache' ) if not cache : options . append ( '--nocache' ) workers = 0 if 'processes' in conf : processes = conf . pop ( 'processes' ) workers = int ( processes ) - 1 if workers > 0 : options += [ '--workers' , str ( workers ) ] for key , value in conf . iteritems ( ) : options += [ '--%s' % key , str ( value ) ] with open ( os . path . join ( SHARE_PATH , 'init.d.j2' ) , 'r' ) as f : TEMPLATE_FILE = f . read ( ) template = jinja2 . Template ( TEMPLATE_FILE ) initd_content = template . render ( { 'venv_path' : virtualenv , 'project_path' : project_path , 'hendrix_opts' : ' ' . join ( options ) } ) return initd_content
251,331
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/utils/conf.py#L9-L61
[ "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", ")" ]
extends startResponse to call speakerBox in a thread
def startResponse ( self , status , headers , excInfo = None ) : self . status = status self . headers = headers self . reactor . callInThread ( responseInColor , self . request , status , headers ) return self . write
251,332
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/facilities/response.py#L41-L50
[ "def", "grab_definition", "(", "self", ",", "url", ")", ":", "re_description", "=", "re", ".", "compile", "(", "'Description:(.+?\\\\n)'", ")", "re_table_name", "=", "re", ".", "compile", "(", "\"(\\w+ Table.+)\"", ")", "if", "url", ".", "startswith", "(", "'//'", ")", ":", "url", "=", "'http:'", "+", "url", "elif", "url", ".", "startswith", "(", "'/'", ")", ":", "url", "=", "'http://www.epa.gov'", "+", "url", "try", ":", "html", "=", "urlopen", "(", "url", ")", ".", "read", "(", ")", "doc", "=", "lh", ".", "fromstring", "(", "html", ")", "main", "=", "doc", ".", "cssselect", "(", "'#main'", ")", "[", "0", "]", "text", "=", "main", ".", "text_content", "(", ")", "definition", "=", "re_description", ".", "search", "(", "text", ")", ".", "group", "(", "1", ")", ".", "strip", "(", ")", "except", "(", "AttributeError", ",", "IndexError", ",", "TypeError", ",", "HTTPError", ")", ":", "print", "url", "else", ":", "value", "=", "re_table_name", ".", "sub", "(", "''", ",", "definition", ")", "return", "value", "return", "url" ]
Checks if the response should be cached . Caches the content in a gzipped format given that a cache_it flag is True To be used CacheClient
def cacheContent ( self , request , response , buffer ) : content = buffer . getvalue ( ) code = int ( response . code ) cache_it = False uri , bust = self . processURI ( request . uri , PREFIX ) # Conditions for adding uri response to cache: # * if it was successful i.e. status of in the 200s # * requested using GET # * not busted if request . method == "GET" and code / 100 == 2 and not bust : cache_control = response . headers . get ( 'cache-control' ) if cache_control : params = dict ( urlparse . parse_qsl ( cache_control ) ) if int ( params . get ( 'max-age' , '0' ) ) > 0 : cache_it = True if cache_it : content = compressBuffer ( content ) self . addResource ( content , uri , response . headers ) buffer . close ( )
251,333
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/backends/__init__.py#L70-L94
[ "def", "get_fptr", "(", "self", ")", ":", "cmpfunc", "=", "ctypes", ".", "CFUNCTYPE", "(", "ctypes", ".", "c_int", ",", "WPARAM", ",", "LPARAM", ",", "ctypes", ".", "POINTER", "(", "KBDLLHookStruct", ")", ")", "return", "cmpfunc", "(", "self", ".", "handle_input", ")" ]
if HENDRIX_SERVICES is specified in settings_module it should be a list twisted internet services
def get_additional_services ( settings_module ) : additional_services = [ ] if hasattr ( settings_module , 'HENDRIX_SERVICES' ) : for name , module_path in settings_module . HENDRIX_SERVICES : path_to_module , service_name = module_path . rsplit ( '.' , 1 ) resource_module = importlib . import_module ( path_to_module ) additional_services . append ( ( name , getattr ( resource_module , service_name ) ) ) return additional_services
251,334
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/facilities/gather.py#L4-L25
[ "def", "create_mon_path", "(", "path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "os", ".", "chown", "(", "path", ",", "uid", ",", "gid", ")" ]
if HENDRIX_CHILD_RESOURCES is specified in settings_module it should be a list resources subclassed from hendrix . contrib . NamedResource
def get_additional_resources ( settings_module ) : additional_resources = [ ] if hasattr ( settings_module , 'HENDRIX_CHILD_RESOURCES' ) : for module_path in settings_module . HENDRIX_CHILD_RESOURCES : path_to_module , resource_name = module_path . rsplit ( '.' , 1 ) resource_module = importlib . import_module ( path_to_module ) additional_resources . append ( getattr ( resource_module , resource_name ) ) return additional_resources
251,335
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/facilities/gather.py#L28-L52
[ "def", "_display_stream", "(", "normalized_data", ",", "stream", ")", ":", "try", ":", "stream", ".", "write", "(", "normalized_data", "[", "'stream'", "]", ")", "except", "UnicodeEncodeError", ":", "stream", ".", "write", "(", "normalized_data", "[", "'stream'", "]", ".", "encode", "(", "\"utf-8\"", ")", ")" ]
updates the options dict to use config options in the settings module
def getConf ( cls , settings , options ) : ports = [ 'http_port' , 'https_port' , 'cache_port' ] for port_name in ports : port = getattr ( settings , port_name . upper ( ) , None ) # only use the settings ports if the defaults were left unchanged default = getattr ( defaults , port_name . upper ( ) ) if port and options . get ( port_name ) == default : options [ port_name ] = port _opts = [ ( 'key' , 'hx_private_key' ) , ( 'cert' , 'hx_certficate' ) , ( 'wsgi' , 'wsgi_application' ) ] for opt_name , settings_name in _opts : opt = getattr ( settings , settings_name . upper ( ) , None ) if opt : options [ opt_name ] = opt if not options [ 'settings' ] : options [ 'settings' ] = environ [ 'DJANGO_SETTINGS_MODULE' ] return options
251,336
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L99-L121
[ "def", "strand", "(", "s1", ",", "s2", ")", ":", "return", "\"\"", ".", "join", "(", "map", "(", "lambda", "x", ",", "y", ":", "chr", "(", "ord", "(", "x", ")", "&", "ord", "(", "y", ")", ")", ",", "s1", ",", "s2", ")", ")" ]
Instantiates a HendrixService with this object s threadpool . It will be added as a service later .
def addHendrix ( self ) : self . hendrix = HendrixService ( self . application , threadpool = self . getThreadPool ( ) , resources = self . resources , services = self . services , loud = self . options [ 'loud' ] ) if self . options [ "https_only" ] is not True : self . hendrix . spawn_new_server ( self . options [ 'http_port' ] , HendrixTCPService )
251,337
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L144-L157
[ "def", "is_writable", "(", "path", ")", ":", "if", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")", ":", "LOGGER", ".", "debug", "(", "\"> '{0}' path is writable.\"", ".", "format", "(", "path", ")", ")", "return", "True", "else", ":", "LOGGER", ".", "debug", "(", "\"> '{0}' path is not writable.\"", ".", "format", "(", "path", ")", ")", "return", "False" ]
collects a list of service names serving on TCP or SSL
def catalogServers ( self , hendrix ) : for service in hendrix . services : if isinstance ( service , ( TCPServer , SSLServer ) ) : self . servers . append ( service . name )
251,338
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L159-L163
[ "def", "until", "(", "coro", ",", "coro_test", ",", "assert_coro", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "@", "asyncio", ".", "coroutine", "def", "assert_coro", "(", "value", ")", ":", "return", "not", "value", "return", "(", "yield", "from", "whilst", "(", "coro", ",", "coro_test", ",", "assert_coro", "=", "assert_coro", ",", "*", "args", ",", "*", "*", "kw", ")", ")" ]
sets up the desired services and runs the requested action
def run ( self ) : self . addServices ( ) self . catalogServers ( self . hendrix ) action = self . action fd = self . options [ 'fd' ] if action . startswith ( 'start' ) : chalk . blue ( self . _listening_message ( ) ) getattr ( self , action ) ( fd ) ########################### # annnnd run the reactor! # ########################### try : self . reactor . run ( ) finally : shutil . rmtree ( PID_DIR , ignore_errors = True ) # cleanup tmp PID dir elif action == 'restart' : getattr ( self , action ) ( fd = fd ) else : getattr ( self , action ) ( )
251,339
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L169-L191
[ "def", "sync", "(", "self", ")", ":", "if", "self", ".", "writeback", "and", "self", ".", "cache", ":", "super", "(", "_TimeoutMixin", ",", "self", ")", ".", "__delitem__", "(", "self", ".", "_INDEX", ")", "super", "(", "_TimeoutMixin", ",", "self", ")", ".", "sync", "(", ")", "self", ".", "writeback", "=", "False", "super", "(", "_TimeoutMixin", ",", "self", ")", ".", "__setitem__", "(", "self", ".", "_INDEX", ",", "self", ".", "_index", ")", "self", ".", "writeback", "=", "True", "if", "hasattr", "(", "self", ".", "dict", ",", "'sync'", ")", ":", "self", ".", "dict", ".", "sync", "(", ")" ]
Iterator for file descriptors . Seperated from launchworkers for clarity and readability .
def setFDs ( self ) : # 0 corresponds to stdin, 1 to stdout, 2 to stderr self . childFDs = { 0 : 0 , 1 : 1 , 2 : 2 } self . fds = { } for name in self . servers : self . port = self . hendrix . get_port ( name ) fd = self . port . fileno ( ) self . childFDs [ fd ] = fd self . fds [ name ] = fd
251,340
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L240-L252
[ "def", "s3_etag", "(", "url", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "s3_resource", "=", "boto3", ".", "resource", "(", "\"s3\"", ")", "bucket_name", ",", "s3_path", "=", "split_s3_path", "(", "url", ")", "s3_object", "=", "s3_resource", ".", "Object", "(", "bucket_name", ",", "s3_path", ")", "return", "s3_object", ".", "e_tag" ]
Public method for _addSubprocess . Wraps reactor . adoptStreamConnection in a simple DeferredLock to guarantee workers play well together .
def addSubprocess ( self , fds , name , factory ) : self . _lock . run ( self . _addSubprocess , self , fds , name , factory )
251,341
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L273-L280
[ "def", "by_type", "(", "blocks", ",", "slist", "=", "None", ")", ":", "layout", "=", "[", "]", "data", "=", "[", "]", "int_vol", "=", "[", "]", "unknown", "=", "[", "]", "for", "i", "in", "blocks", ":", "if", "slist", "and", "i", "not", "in", "slist", ":", "continue", "if", "blocks", "[", "i", "]", ".", "is_vtbl", "and", "blocks", "[", "i", "]", ".", "is_valid", ":", "layout", ".", "append", "(", "i", ")", "elif", "blocks", "[", "i", "]", ".", "is_internal_vol", "and", "blocks", "[", "i", "]", ".", "is_valid", ":", "int_vol", ".", "append", "(", "i", ")", "elif", "blocks", "[", "i", "]", ".", "is_valid", ":", "data", ".", "append", "(", "i", ")", "else", ":", "unknown", ".", "append", "(", "i", ")", "return", "layout", ",", "data", ",", "int_vol", ",", "unknown" ]
disowns a service on hendirix by name returns a factory for use in the adoptStreamPort part of setting up multiple processes
def disownService ( self , name ) : _service = self . hendrix . getServiceNamed ( name ) _service . disownServiceParent ( ) return _service . factory
251,342
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/base.py#L307-L315
[ "def", "ulocalized_gmt0_time", "(", "self", ",", "time", ",", "context", ",", "request", ")", ":", "value", "=", "get_date", "(", "context", ",", "time", ")", "if", "not", "value", ":", "return", "\"\"", "# DateTime is stored with TimeZone, but DateTimeWidget omits TZ", "value", "=", "value", ".", "toZone", "(", "\"GMT+0\"", ")", "return", "self", ".", "ulocalized_time", "(", "value", ",", "context", ",", "request", ")" ]
returns The default location of the pid file for process management
def get_pid ( options ) : namespace = options [ 'settings' ] if options [ 'settings' ] else options [ 'wsgi' ] return os . path . join ( '{}' , '{}_{}.pid' ) . format ( PID_DIR , options [ 'http_port' ] , namespace . replace ( '.' , '_' ) )
251,343
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/utils/__init__.py#L21-L24
[ "def", "layer_to_solr", "(", "self", ",", "layer", ")", ":", "success", "=", "True", "message", "=", "'Synced layer id %s to Solr'", "%", "layer", ".", "id", "layer_dict", ",", "message", "=", "layer2dict", "(", "layer", ")", "if", "not", "layer_dict", ":", "success", "=", "False", "else", ":", "layer_json", "=", "json", ".", "dumps", "(", "layer_dict", ")", "try", ":", "url_solr_update", "=", "'%s/solr/hypermap/update/json/docs'", "%", "SEARCH_URL", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", "}", "params", "=", "{", "\"commitWithin\"", ":", "1500", "}", "res", "=", "requests", ".", "post", "(", "url_solr_update", ",", "data", "=", "layer_json", ",", "params", "=", "params", ",", "headers", "=", "headers", ")", "res", "=", "res", ".", "json", "(", ")", "if", "'error'", "in", "res", ":", "success", "=", "False", "message", "=", "\"Error syncing layer id %s to Solr: %s\"", "%", "(", "layer", ".", "id", ",", "res", "[", "\"error\"", "]", ".", "get", "(", "\"msg\"", ")", ")", "except", "Exception", ",", "e", ":", "success", "=", "False", "message", "=", "\"Error syncing layer id %s to Solr: %s\"", "%", "(", "layer", ".", "id", ",", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", "LOGGER", ".", "error", "(", "e", ",", "exc_info", "=", "True", ")", "if", "success", ":", "LOGGER", ".", "info", "(", "message", ")", "else", ":", "LOGGER", ".", "error", "(", "message", ")", "return", "success", ",", "message" ]
Prints the response info in color
def responseInColor ( request , status , headers , prefix = 'Response' , opts = None ) : code , message = status . split ( None , 1 ) message = '%s [%s] => Request %s %s %s on pid %d' % ( prefix , code , str ( request . host ) , request . method , request . path , os . getpid ( ) ) signal = int ( code ) / 100 if signal == 2 : chalk . green ( message , opts = opts ) elif signal == 3 : chalk . blue ( message , opts = opts ) else : chalk . red ( message , opts = opts )
251,344
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/utils/__init__.py#L27-L44
[ "def", "_check_rest_version", "(", "self", ",", "version", ")", ":", "version", "=", "str", "(", "version", ")", "if", "version", "not", "in", "self", ".", "supported_rest_versions", ":", "msg", "=", "\"Library is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "array_rest_versions", "=", "self", ".", "_list_available_rest_versions", "(", ")", "if", "version", "not", "in", "array_rest_versions", ":", "msg", "=", "\"Array is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "return", "LooseVersion", "(", "version", ")" ]
adds a CacheService to the instatiated HendrixService
def addLocalCacheService ( self ) : _cache = self . getCacheService ( ) _cache . setName ( 'cache_proxy' ) _cache . setServiceParent ( self . hendrix )
251,345
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/cache.py#L24-L28
[ "def", "describe_message", "(", "message_definition", ")", ":", "message_descriptor", "=", "MessageDescriptor", "(", ")", "message_descriptor", ".", "name", "=", "message_definition", ".", "definition_name", "(", ")", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "fields", "=", "sorted", "(", "message_definition", ".", "all_fields", "(", ")", ",", "key", "=", "lambda", "v", ":", "v", ".", "number", ")", "if", "fields", ":", "message_descriptor", ".", "fields", "=", "[", "describe_field", "(", "field", ")", "for", "field", "in", "fields", "]", "try", ":", "nested_messages", "=", "message_definition", ".", "__messages__", "except", "AttributeError", ":", "pass", "else", ":", "message_descriptors", "=", "[", "]", "for", "name", "in", "nested_messages", ":", "value", "=", "getattr", "(", "message_definition", ",", "name", ")", "message_descriptors", ".", "append", "(", "describe_message", "(", "value", ")", ")", "message_descriptor", ".", "message_types", "=", "message_descriptors", "try", ":", "nested_enums", "=", "message_definition", ".", "__enums__", "except", "AttributeError", ":", "pass", "else", ":", "enum_descriptors", "=", "[", "]", "for", "name", "in", "nested_enums", ":", "value", "=", "getattr", "(", "message_definition", ",", "name", ")", "enum_descriptors", ".", "append", "(", "describe_enum", "(", "value", ")", ")", "message_descriptor", ".", "enum_types", "=", "enum_descriptors", "return", "message_descriptor" ]
This is where we put service that we don t want to be duplicated on worker subprocesses
def addGlobalServices ( self ) : if self . options . get ( 'global_cache' ) and self . options . get ( 'cache' ) : # only add the cache service here if the global_cache and cache # options were set to True _cache = self . getCacheService ( ) _cache . startService ( )
251,346
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/cache.py#L38-L47
[ "def", "_read_footer", "(", "file_obj", ")", ":", "footer_size", "=", "_get_footer_size", "(", "file_obj", ")", "if", "logger", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "logger", ".", "debug", "(", "\"Footer size in bytes: %s\"", ",", "footer_size", ")", "file_obj", ".", "seek", "(", "-", "(", "8", "+", "footer_size", ")", ",", "2", ")", "# seek to beginning of footer", "tin", "=", "TFileTransport", "(", "file_obj", ")", "pin", "=", "TCompactProtocolFactory", "(", ")", ".", "get_protocol", "(", "tin", ")", "fmd", "=", "parquet_thrift", ".", "FileMetaData", "(", ")", "fmd", ".", "read", "(", "pin", ")", "return", "fmd" ]
putNamedChild takes either an instance of hendrix . contrib . NamedResource or any resource . Resource with a namespace attribute as a means of allowing application level control of resource namespacing .
def putNamedChild ( self , res ) : try : EmptyResource = resource . Resource namespace = res . namespace parts = namespace . strip ( '/' ) . split ( '/' ) # initialise parent and children parent = self children = self . children # loop through all of the path parts except for the last one for name in parts [ : - 1 ] : child = children . get ( name ) if not child : # if the child does not exist then create an empty one # and associate it to the parent child = EmptyResource ( ) parent . putChild ( name , child ) # update parent and children for the next iteration parent = child children = parent . children name = parts [ - 1 ] # get the path part that we care about if children . get ( name ) : self . logger . warn ( 'A resource already exists at this path. Check ' 'your resources list to ensure each path is ' 'unique. The previous resource will be overridden.' ) parent . putChild ( name , res ) except AttributeError : # raise an attribute error if the resource `res` doesn't contain # the attribute `namespace` msg = ( '%r improperly configured. additional_resources instances must' ' have a namespace attribute' ) % resource raise AttributeError ( msg , None , sys . exc_info ( ) [ 2 ] )
251,347
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/facilities/resources.py#L59-L105
[ "def", "commit", "(", "self", ")", ":", "self", ".", "send_buffered_operations", "(", ")", "retry_until_ok", "(", "self", ".", "elastic", ".", "indices", ".", "refresh", ",", "index", "=", "\"\"", ")" ]
a shortcut for message sending
def send_json_message ( address , message , * * kwargs ) : data = { 'message' : message , } if not kwargs . get ( 'subject_id' ) : data [ 'subject_id' ] = address data . update ( kwargs ) hxdispatcher . send ( address , data )
251,348
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L125-L139
[ "def", "generate_citation_counter", "(", "self", ")", ":", "cite_counter", "=", "dict", "(", ")", "filename", "=", "'%s.aux'", "%", "self", ".", "project_name", "with", "open", "(", "filename", ")", "as", "fobj", ":", "main_aux", "=", "fobj", ".", "read", "(", ")", "cite_counter", "[", "filename", "]", "=", "_count_citations", "(", "filename", ")", "for", "match", "in", "re", ".", "finditer", "(", "r'\\\\@input\\{(.*.aux)\\}'", ",", "main_aux", ")", ":", "filename", "=", "match", ".", "groups", "(", ")", "[", "0", "]", "try", ":", "counter", "=", "_count_citations", "(", "filename", ")", "except", "IOError", ":", "pass", "else", ":", "cite_counter", "[", "filename", "]", "=", "counter", "return", "cite_counter" ]
useful for sending messages from callbacks as it puts the result of the callback in the dict for serialization
def send_callback_json_message ( value , * args , * * kwargs ) : if value : kwargs [ 'result' ] = value send_json_message ( args [ 0 ] , args [ 1 ] , * * kwargs ) return value
251,349
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L142-L153
[ "def", "secret_file", "(", "filename", ")", ":", "filestat", "=", "os", ".", "stat", "(", "abspath", "(", "filename", ")", ")", "if", "stat", ".", "S_ISREG", "(", "filestat", ".", "st_mode", ")", "==", "0", "and", "stat", ".", "S_ISLNK", "(", "filestat", ".", "st_mode", ")", "==", "0", ":", "e_msg", "=", "\"Secret file %s must be a real file or symlink\"", "%", "filename", "raise", "aomi", ".", "exceptions", ".", "AomiFile", "(", "e_msg", ")", "if", "platform", ".", "system", "(", ")", "!=", "\"Windows\"", ":", "if", "filestat", ".", "st_mode", "&", "stat", ".", "S_IROTH", "or", "filestat", ".", "st_mode", "&", "stat", ".", "S_IWOTH", "or", "filestat", ".", "st_mode", "&", "stat", ".", "S_IWGRP", ":", "e_msg", "=", "\"Secret file %s has too loose permissions\"", "%", "filename", "raise", "aomi", ".", "exceptions", ".", "AomiFile", "(", "e_msg", ")" ]
sends whatever it is to each transport
def send ( self , message ) : # usually a json string... for transport in self . transports . values ( ) : transport . protocol . sendMessage ( message )
251,350
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L34-L39
[ "def", "extract_notebook_metatab", "(", "nb_path", ":", "Path", ")", ":", "from", "metatab", ".", "rowgenerators", "import", "TextRowGenerator", "import", "nbformat", "with", "nb_path", ".", "open", "(", ")", "as", "f", ":", "nb", "=", "nbformat", ".", "read", "(", "f", ",", "as_version", "=", "4", ")", "lines", "=", "'\\n'", ".", "join", "(", "[", "'Declare: metatab-latest'", "]", "+", "[", "get_cell_source", "(", "nb", ",", "tag", ")", "for", "tag", "in", "[", "'metadata'", ",", "'resources'", ",", "'schema'", "]", "]", ")", "doc", "=", "MetapackDoc", "(", "TextRowGenerator", "(", "lines", ")", ")", "doc", "[", "'Root'", "]", ".", "get_or_new_term", "(", "'Root.Title'", ")", ".", "value", "=", "get_cell_source", "(", "nb", ",", "'Title'", ")", ".", "strip", "(", "'#'", ")", ".", "strip", "(", ")", "doc", "[", "'Root'", "]", ".", "get_or_new_term", "(", "'Root.Description'", ")", ".", "value", "=", "get_cell_source", "(", "nb", ",", "'Description'", ")", "doc", "[", "'Documentation'", "]", ".", "get_or_new_term", "(", "'Root.Readme'", ")", ".", "value", "=", "get_cell_source", "(", "nb", ",", "'readme'", ")", "return", "doc" ]
removes a transport if a member of this group
def remove ( self , transport ) : if transport . uid in self . transports : del ( self . transports [ transport . uid ] )
251,351
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L41-L46
[ "def", "init_db", "(", "self", ")", ":", "with", "self", ".", "conn", ".", "transaction", "(", ")", "as", "t", ":", "t", ".", "execute", "(", "'''\n CREATE TABLE temporal (\n tuid INTEGER,\n revision CHAR(12) NOT NULL,\n file TEXT,\n line INTEGER\n );'''", ")", "t", ".", "execute", "(", "'''\n CREATE TABLE annotations (\n revision CHAR(12) NOT NULL,\n file TEXT,\n annotation TEXT,\n PRIMARY KEY(revision, file)\n );'''", ")", "# Used in frontier updating", "t", ".", "execute", "(", "'''\n CREATE TABLE latestFileMod (\n file TEXT,\n revision CHAR(12) NOT NULL,\n PRIMARY KEY(file)\n );'''", ")", "t", ".", "execute", "(", "\"CREATE UNIQUE INDEX temporal_rev_file ON temporal(revision, file, line)\"", ")", "Log", ".", "note", "(", "\"Tables created successfully\"", ")" ]
add a new recipient to be addressable by this MessageDispatcher generate a new uuid address if one is not specified
def add ( self , transport , address = None ) : if not address : address = str ( uuid . uuid1 ( ) ) if address in self . recipients : self . recipients [ address ] . add ( transport ) else : self . recipients [ address ] = RecipientManager ( transport , address ) return address
251,352
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L69-L83
[ "def", "on_train_end", "(", "self", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "train_start", "print", "(", "'done, took {:.3f} seconds'", ".", "format", "(", "duration", ")", ")" ]
removes a transport from all channels to which it belongs .
def remove ( self , transport ) : recipients = copy . copy ( self . recipients ) for address , recManager in recipients . items ( ) : recManager . remove ( transport ) if not len ( recManager . transports ) : del self . recipients [ address ]
251,353
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L85-L93
[ "def", "user_exists", "(", "user", ",", "host", "=", "'localhost'", ",", "password", "=", "None", ",", "password_hash", "=", "None", ",", "passwordless", "=", "False", ",", "unix_socket", "=", "False", ",", "password_column", "=", "None", ",", "*", "*", "connection_args", ")", ":", "run_verify", "=", "False", "server_version", "=", "salt", ".", "utils", ".", "data", ".", "decode", "(", "version", "(", "*", "*", "connection_args", ")", ")", "if", "not", "server_version", ":", "last_err", "=", "__context__", "[", "'mysql.error'", "]", "err", "=", "'MySQL Error: Unable to fetch current server version. Last error was: \"{}\"'", ".", "format", "(", "last_err", ")", "log", ".", "error", "(", "err", ")", "return", "False", "compare_version", "=", "'10.2.0'", "if", "'MariaDB'", "in", "server_version", "else", "'8.0.11'", "dbc", "=", "_connect", "(", "*", "*", "connection_args", ")", "# Did we fail to connect with the user we are checking", "# Its password might have previously change with the same command/state", "if", "dbc", "is", "None", "and", "__context__", "[", "'mysql.error'", "]", ".", "startswith", "(", "\"MySQL Error 1045: Access denied for user '{0}'@\"", ".", "format", "(", "user", ")", ")", "and", "password", ":", "# Clear the previous error", "__context__", "[", "'mysql.error'", "]", "=", "None", "connection_args", "[", "'connection_pass'", "]", "=", "password", "dbc", "=", "_connect", "(", "*", "*", "connection_args", ")", "if", "dbc", "is", "None", ":", "return", "False", "if", "not", "password_column", ":", "password_column", "=", "__password_column", "(", "*", "*", "connection_args", ")", "cur", "=", "dbc", ".", "cursor", "(", ")", "qry", "=", "(", "'SELECT User,Host FROM mysql.user WHERE User = %(user)s AND '", "'Host = %(host)s'", ")", "args", "=", "{", "}", "args", "[", "'user'", "]", "=", "user", "args", "[", "'host'", "]", "=", "host", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "passwordless", ")", ":", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "unix_socket", ")", ":", "qry", "+=", "' AND plugin=%(unix_socket)s'", "args", "[", "'unix_socket'", "]", "=", "'unix_socket'", "else", ":", "qry", "+=", "' AND '", "+", "password_column", "+", "' = \\'\\''", "elif", "password", ":", "if", "salt", ".", "utils", ".", "versions", ".", "version_cmp", "(", "server_version", ",", "compare_version", ")", ">=", "0", ":", "run_verify", "=", "True", "else", ":", "_password", "=", "password", "qry", "+=", "' AND '", "+", "password_column", "+", "' = PASSWORD(%(password)s)'", "args", "[", "'password'", "]", "=", "six", ".", "text_type", "(", "_password", ")", "elif", "password_hash", ":", "qry", "+=", "' AND '", "+", "password_column", "+", "' = %(password)s'", "args", "[", "'password'", "]", "=", "password_hash", "if", "run_verify", ":", "if", "not", "verify_login", "(", "user", ",", "password", ",", "*", "*", "connection_args", ")", ":", "return", "False", "try", ":", "_execute", "(", "cur", ",", "qry", ",", "args", ")", "except", "MySQLdb", ".", "OperationalError", "as", "exc", ":", "err", "=", "'MySQL Error {0}: {1}'", ".", "format", "(", "*", "exc", ".", "args", ")", "__context__", "[", "'mysql.error'", "]", "=", "err", "log", ".", "error", "(", "err", ")", "return", "False", "return", "cur", ".", "rowcount", "==", "1" ]
address can either be a string or a list of strings
def send ( self , address , data_dict ) : if type ( address ) == list : recipients = [ self . recipients . get ( rec ) for rec in address ] else : recipients = [ self . recipients . get ( address ) ] if recipients : for recipient in recipients : if recipient : recipient . send ( json . dumps ( data_dict ) . encode ( ) )
251,354
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L95-L110
[ "def", "start_processing_handler", "(", "self", ",", "event", ")", ":", "results_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "configuration", "[", "'results_folder'", "]", ",", "\"filesystem.json\"", ")", "self", ".", "logger", ".", "debug", "(", "\"Event %s: start comparing %s with %s.\"", ",", "event", ",", "self", ".", "checkpoints", "[", "0", "]", ",", "self", ".", "checkpoints", "[", "1", "]", ")", "results", "=", "compare_disks", "(", "self", ".", "checkpoints", "[", "0", "]", ",", "self", ".", "checkpoints", "[", "1", "]", ",", "self", ".", "configuration", ")", "with", "open", "(", "results_path", ",", "'w'", ")", "as", "results_file", ":", "json", ".", "dump", "(", "results", ",", "results_file", ")", "self", ".", "processing_done", ".", "set", "(", ")" ]
adds a transport to a channel
def subscribe ( self , transport , data ) : self . add ( transport , address = data . get ( 'hx_subscribe' ) . encode ( ) ) self . send ( data [ 'hx_subscribe' ] , { 'message' : "%r is listening" % transport } )
251,355
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L112-L122
[ "def", "_search", "(", "prefix", "=", "\"latest/\"", ")", ":", "ret", "=", "{", "}", "linedata", "=", "http", ".", "query", "(", "os", ".", "path", ".", "join", "(", "HOST", ",", "prefix", ")", ",", "headers", "=", "True", ")", "if", "'body'", "not", "in", "linedata", ":", "return", "ret", "body", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "linedata", "[", "'body'", "]", ")", "if", "linedata", "[", "'headers'", "]", ".", "get", "(", "'Content-Type'", ",", "'text/plain'", ")", "==", "'application/octet-stream'", ":", "return", "body", "for", "line", "in", "body", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "endswith", "(", "'/'", ")", ":", "ret", "[", "line", "[", ":", "-", "1", "]", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "line", ")", ")", "elif", "prefix", "==", "'latest/'", ":", "# (gtmanfred) The first level should have a forward slash since", "# they have stuff underneath. This will not be doubled up though,", "# because lines ending with a slash are checked first.", "ret", "[", "line", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "line", "+", "'/'", ")", ")", "elif", "line", ".", "endswith", "(", "(", "'dynamic'", ",", "'meta-data'", ")", ")", ":", "ret", "[", "line", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "line", ")", ")", "elif", "'='", "in", "line", ":", "key", ",", "value", "=", "line", ".", "split", "(", "'='", ")", "ret", "[", "value", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "key", ")", ")", "else", ":", "retdata", "=", "http", ".", "query", "(", "os", ".", "path", ".", "join", "(", "HOST", ",", "prefix", ",", "line", ")", ")", ".", "get", "(", "'body'", ",", "None", ")", "# (gtmanfred) This try except block is slightly faster than", "# checking if the string starts with a curly brace", "if", "isinstance", "(", "retdata", ",", "six", ".", "binary_type", ")", ":", "try", ":", "ret", "[", "line", "]", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "retdata", ")", ")", "except", "ValueError", ":", "ret", "[", "line", "]", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "retdata", ")", "else", ":", "ret", "[", "line", "]", "=", "retdata", "return", "salt", ".", "utils", ".", "data", ".", "decode", "(", "ret", ")" ]
Takes an options dict and returns a tuple containing the daemonize boolean the reload boolean and the parsed list of cleaned options as would be expected to be passed to hx
def cleanOptions ( options ) : _reload = options . pop ( 'reload' ) dev = options . pop ( 'dev' ) opts = [ ] store_true = [ '--nocache' , '--global_cache' , '--quiet' , '--loud' ] store_false = [ ] for key , value in options . items ( ) : key = '--' + key if ( key in store_true and value ) or ( key in store_false and not value ) : opts += [ key , ] elif value : opts += [ key , str ( value ) ] return _reload , opts
251,356
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/options.py#L7-L26
[ "def", "get_progress", "(", "self", ")", ":", "pos", "=", "self", ".", "reader", ".", "reader", ".", "tell", "(", ")", "return", "min", "(", "(", "pos", "-", "self", ".", "region_start", ")", "/", "float", "(", "self", ".", "region_end", "-", "self", ".", "region_start", ")", ",", "1.0", ")" ]
A helper function that returns a dictionary of the default key - values pairs
def options ( argv = [ ] ) : parser = HendrixOptionParser parsed_args = parser . parse_args ( argv ) return vars ( parsed_args [ 0 ] )
251,357
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/options.py#L195-L201
[ "def", "addNoiseToVector", "(", "inputVector", ",", "noiseLevel", ",", "vectorType", ")", ":", "if", "vectorType", "==", "'sparse'", ":", "corruptSparseVector", "(", "inputVector", ",", "noiseLevel", ")", "elif", "vectorType", "==", "'dense'", ":", "corruptDenseVector", "(", "inputVector", ",", "noiseLevel", ")", "else", ":", "raise", "ValueError", "(", "\"vectorType must be 'sparse' or 'dense' \"", ")" ]
Unsubscribe this participant from all topic to which it is subscribed .
def remove ( self , participant ) : for topic , participants in list ( self . _participants_by_topic . items ( ) ) : self . unsubscribe ( participant , topic ) # It's possible that we just nixe the last subscriber. if not participants : # IE, nobody is still listening at this topic. del self . _participants_by_topic [ topic ]
251,358
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/experience/hey_joe.py#L67-L75
[ "def", "_set_max_value", "(", "self", ",", "max_value", ")", ":", "self", ".", "_external_max_value", "=", "max_value", "# Check that the current value of the parameter is still within the boundaries. If not, issue a warning", "if", "self", ".", "_external_max_value", "is", "not", "None", "and", "self", ".", "value", ">", "self", ".", "_external_max_value", ":", "warnings", ".", "warn", "(", "\"The current value of the parameter %s (%s) \"", "\"was above the new maximum %s.\"", "%", "(", "self", ".", "name", ",", "self", ".", "value", ",", "self", ".", "_external_max_value", ")", ",", "exceptions", ".", "RuntimeWarning", ")", "self", ".", "value", "=", "self", ".", "_external_max_value" ]
adds a SSLService to the instaitated HendrixService
def addSSLService ( self ) : https_port = self . options [ 'https_port' ] self . tls_service = HendrixTCPServiceWithTLS ( https_port , self . hendrix . site , self . key , self . cert , self . context_factory , self . context_factory_kwargs ) self . tls_service . setServiceParent ( self . hendrix )
251,359
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/deploy/tls.py#L61-L66
[ "def", "get_archive", "(", "self", ",", "container", ",", "path", ",", "chunk_size", "=", "DEFAULT_DATA_CHUNK_SIZE", ")", ":", "params", "=", "{", "'path'", ":", "path", "}", "url", "=", "self", ".", "_url", "(", "'/containers/{0}/archive'", ",", "container", ")", "res", "=", "self", ".", "_get", "(", "url", ",", "params", "=", "params", ",", "stream", "=", "True", ")", "self", ".", "_raise_for_status", "(", "res", ")", "encoded_stat", "=", "res", ".", "headers", ".", "get", "(", "'x-docker-container-path-stat'", ")", "return", "(", "self", ".", "_stream_raw_result", "(", "res", ",", "chunk_size", ",", "False", ")", ",", "utils", ".", "decode_json_header", "(", "encoded_stat", ")", "if", "encoded_stat", "else", "None", ")" ]
Adds the a hendrix . contrib . cache . resource . CachedResource to the ReverseProxy cache connection
def addResource ( self , content , uri , headers ) : self . cache [ uri ] = CachedResource ( content , headers )
251,360
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/backends/memory_cache.py#L15-L20
[ "def", "remove_pickle_problems", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "\"doc_loader\"", ")", ":", "obj", ".", "doc_loader", "=", "None", "if", "hasattr", "(", "obj", ",", "\"embedded_tool\"", ")", ":", "obj", ".", "embedded_tool", "=", "remove_pickle_problems", "(", "obj", ".", "embedded_tool", ")", "if", "hasattr", "(", "obj", ",", "\"steps\"", ")", ":", "obj", ".", "steps", "=", "[", "remove_pickle_problems", "(", "s", ")", "for", "s", "in", "obj", ".", "steps", "]", "return", "obj" ]
complements the compressBuffer function in CacheClient
def decompressBuffer ( buffer ) : zbuf = cStringIO . StringIO ( buffer ) zfile = gzip . GzipFile ( fileobj = zbuf ) deflated = zfile . read ( ) zfile . close ( ) return deflated
251,361
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/__init__.py#L30-L36
[ "def", "get_default_storage_policy_of_datastore", "(", "profile_manager", ",", "datastore", ")", ":", "# Retrieve all datastores visible", "hub", "=", "pbm", ".", "placement", ".", "PlacementHub", "(", "hubId", "=", "datastore", ".", "_moId", ",", "hubType", "=", "'Datastore'", ")", "log", ".", "trace", "(", "'placement_hub = %s'", ",", "hub", ")", "try", ":", "policy_id", "=", "profile_manager", ".", "QueryDefaultRequirementProfile", "(", "hub", ")", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "VMwareApiError", "(", "'Not enough permissions. Required privilege: '", "'{0}'", ".", "format", "(", "exc", ".", "privilegeId", ")", ")", "except", "vim", ".", "fault", ".", "VimFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "VMwareApiError", "(", "exc", ".", "msg", ")", "except", "vmodl", ".", "RuntimeFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "VMwareRuntimeError", "(", "exc", ".", "msg", ")", "policy_refs", "=", "get_policies_by_id", "(", "profile_manager", ",", "[", "policy_id", "]", ")", "if", "not", "policy_refs", ":", "raise", "VMwareObjectRetrievalError", "(", "'Storage policy with id \\'{0}\\' was '", "'not found'", ".", "format", "(", "policy_id", ")", ")", "return", "policy_refs", "[", "0", "]" ]
get the max - age in seconds from the saved headers data
def getMaxAge ( self ) : max_age = 0 cache_control = self . headers . get ( 'cache-control' ) if cache_control : params = dict ( urlparse . parse_qsl ( cache_control ) ) max_age = int ( params . get ( 'max-age' , '0' ) ) return max_age
251,362
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/__init__.py#L51-L58
[ "def", "umount", "(", "self", ",", "forced", "=", "True", ")", ":", "if", "self", ".", "is_mounted", "(", ")", ":", "if", "is_osx", "(", ")", ":", "cmd", "=", "[", "\"/usr/sbin/diskutil\"", ",", "\"unmount\"", ",", "self", ".", "connection", "[", "\"mount_point\"", "]", "]", "if", "forced", ":", "cmd", ".", "insert", "(", "2", ",", "\"force\"", ")", "subprocess", ".", "check_call", "(", "cmd", ")", "else", ":", "cmd", "=", "[", "\"umount\"", ",", "self", ".", "connection", "[", "\"mount_point\"", "]", "]", "if", "forced", ":", "cmd", ".", "insert", "(", "1", ",", "\"-f\"", ")", "subprocess", ".", "check_call", "(", "cmd", ")" ]
returns the GMT last - modified datetime or None
def getLastModified ( self ) : last_modified = self . headers . get ( 'last-modified' ) if last_modified : last_modified = self . convertTimeString ( last_modified ) return last_modified
251,363
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/__init__.py#L68-L73
[ "def", "_get_unit_data_from_expr", "(", "unit_expr", ",", "unit_symbol_lut", ")", ":", "# Now for the sympy possibilities", "if", "isinstance", "(", "unit_expr", ",", "Number", ")", ":", "if", "unit_expr", "is", "sympy_one", ":", "return", "(", "1.0", ",", "sympy_one", ")", "return", "(", "float", "(", "unit_expr", ")", ",", "sympy_one", ")", "if", "isinstance", "(", "unit_expr", ",", "Symbol", ")", ":", "return", "_lookup_unit_symbol", "(", "unit_expr", ".", "name", ",", "unit_symbol_lut", ")", "if", "isinstance", "(", "unit_expr", ",", "Pow", ")", ":", "unit_data", "=", "_get_unit_data_from_expr", "(", "unit_expr", ".", "args", "[", "0", "]", ",", "unit_symbol_lut", ")", "power", "=", "unit_expr", ".", "args", "[", "1", "]", "if", "isinstance", "(", "power", ",", "Symbol", ")", ":", "raise", "UnitParseError", "(", "\"Invalid unit expression '%s'.\"", "%", "unit_expr", ")", "conv", "=", "float", "(", "unit_data", "[", "0", "]", "**", "power", ")", "unit", "=", "unit_data", "[", "1", "]", "**", "power", "return", "(", "conv", ",", "unit", ")", "if", "isinstance", "(", "unit_expr", ",", "Mul", ")", ":", "base_value", "=", "1.0", "dimensions", "=", "1", "for", "expr", "in", "unit_expr", ".", "args", ":", "unit_data", "=", "_get_unit_data_from_expr", "(", "expr", ",", "unit_symbol_lut", ")", "base_value", "*=", "unit_data", "[", "0", "]", "dimensions", "*=", "unit_data", "[", "1", "]", "return", "(", "float", "(", "base_value", ")", ",", "dimensions", ")", "raise", "UnitParseError", "(", "\"Cannot parse for unit data from '%s'. Please supply\"", "\" an expression of only Unit, Symbol, Pow, and Mul\"", "\"objects.\"", "%", "str", "(", "unit_expr", ")", ")" ]
returns the GMT response datetime or None
def getDate ( self ) : date = self . headers . get ( 'date' ) if date : date = self . convertTimeString ( date ) return date
251,364
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/__init__.py#L75-L80
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
returns True if cached object is still fresh
def isFresh ( self ) : max_age = self . getMaxAge ( ) date = self . getDate ( ) is_fresh = False if max_age and date : delta_time = datetime . now ( ) - date is_fresh = delta_time . total_seconds ( ) < max_age return is_fresh
251,365
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/__init__.py#L82-L90
[ "def", "_decode", "(", "self", ",", "entries", ",", "entry_type", ")", ":", "def", "decode_blobs", "(", "row", ")", ":", "row", "=", "list", "(", "row", ")", "for", "index", ",", "value", "in", "zip", "(", "range", "(", "len", "(", "row", ")", ")", ",", "row", ")", ":", "if", "isinstance", "(", "value", ",", "types", ".", "BufferType", ")", ":", "value", "=", "str", "(", "value", ")", "if", "self", ".", "_encoding", ":", "value", "=", "value", ".", "decode", "(", "self", ".", "_encoding", ")", "row", "[", "index", "]", "=", "value", "return", "row", "decoded", "=", "map", "(", "decode_blobs", ",", "entries", ")", "if", "entry_type", "==", "'log'", ":", "mapping", "=", "[", "'hostname'", ",", "'message'", ",", "'level'", ",", "'category'", ",", "'log_name'", ",", "'file_path'", ",", "'line_num'", ",", "'timestamp'", "]", "elif", "entry_type", "==", "'journal'", ":", "mapping", "=", "[", "'agent_id'", ",", "'instance_id'", ",", "'journal_id'", ",", "'function_id'", ",", "'fiber_id'", ",", "'fiber_depth'", ",", "'args'", ",", "'kwargs'", ",", "'side_effects'", ",", "'result'", ",", "'timestamp'", "]", "else", ":", "raise", "ValueError", "(", "'Unknown entry_type %r'", "%", "(", "entry_type", ",", ")", ")", "def", "parse", "(", "row", ",", "mapping", ",", "entry_type", ")", ":", "resp", "=", "dict", "(", "zip", "(", "mapping", ",", "row", ")", ")", "resp", "[", "'entry_type'", "]", "=", "entry_type", "return", "resp", "parsed", "=", "[", "parse", "(", "row", ",", "mapping", ",", "entry_type", ")", "for", "row", "in", "decoded", "]", "return", "parsed" ]
Non - preflight CORS request response processor .
async def _on_response_prepare ( self , request : web . Request , response : web . StreamResponse ) : if ( not self . _router_adapter . is_cors_enabled_on_request ( request ) or self . _router_adapter . is_preflight_request ( request ) ) : # Either not CORS enabled route, or preflight request which is # handled in its own handler. return # Processing response of non-preflight CORS-enabled request. config = self . _router_adapter . get_non_preflight_request_config ( request ) # Handle according to part 6.1 of the CORS specification. origin = request . headers . get ( hdrs . ORIGIN ) if origin is None : # Terminate CORS according to CORS 6.1.1. return options = config . get ( origin , config . get ( "*" ) ) if options is None : # Terminate CORS according to CORS 6.1.2. return assert hdrs . ACCESS_CONTROL_ALLOW_ORIGIN not in response . headers assert hdrs . ACCESS_CONTROL_ALLOW_CREDENTIALS not in response . headers assert hdrs . ACCESS_CONTROL_EXPOSE_HEADERS not in response . headers # Process according to CORS 6.1.4. # Set exposed headers (server headers exposed to client) before # setting any other headers. if options . expose_headers == "*" : # Expose all headers that are set in response. exposed_headers = frozenset ( response . headers . keys ( ) ) - _SIMPLE_RESPONSE_HEADERS response . headers [ hdrs . ACCESS_CONTROL_EXPOSE_HEADERS ] = "," . join ( exposed_headers ) elif options . expose_headers : # Expose predefined list of headers. response . headers [ hdrs . ACCESS_CONTROL_EXPOSE_HEADERS ] = "," . join ( options . expose_headers ) # Process according to CORS 6.1.3. # Set allowed origin. response . headers [ hdrs . ACCESS_CONTROL_ALLOW_ORIGIN ] = origin if options . allow_credentials : # Set allowed credentials. response . headers [ hdrs . ACCESS_CONTROL_ALLOW_CREDENTIALS ] = _TRUE
251,366
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/cors_config.py#L141-L195
[ "def", "parse_url", "(", "url", ")", ":", "parsed", "=", "url", "if", "not", "url", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "# if url is like www.yahoo.com", "parsed", "=", "\"http://\"", "+", "parsed", "elif", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "parsed", "=", "parsed", "[", "8", ":", "]", "parsed", "=", "\"http://\"", "+", "parsed", "index_hash", "=", "parsed", ".", "rfind", "(", "\"#\"", ")", "# remove trailing #", "index_slash", "=", "parsed", ".", "rfind", "(", "\"/\"", ")", "if", "index_hash", ">", "index_slash", ":", "parsed", "=", "parsed", "[", "0", ":", "index_hash", "]", "return", "parsed" ]
Returns is seq is sequence and not string .
def _is_proper_sequence ( seq ) : return ( isinstance ( seq , collections . abc . Sequence ) and not isinstance ( seq , str ) )
251,367
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/resource_options.py#L25-L28
[ "def", "initialize_communities_bucket", "(", ")", ":", "bucket_id", "=", "UUID", "(", "current_app", ".", "config", "[", "'COMMUNITIES_BUCKET_UUID'", "]", ")", "if", "Bucket", ".", "query", ".", "get", "(", "bucket_id", ")", ":", "raise", "FilesException", "(", "\"Bucket with UUID {} already exists.\"", ".", "format", "(", "bucket_id", ")", ")", "else", ":", "storage_class", "=", "current_app", ".", "config", "[", "'FILES_REST_DEFAULT_STORAGE_CLASS'", "]", "location", "=", "Location", ".", "get_default", "(", ")", "bucket", "=", "Bucket", "(", "id", "=", "bucket_id", ",", "location", "=", "location", ",", "default_storage_class", "=", "storage_class", ")", "db", ".", "session", ".", "add", "(", "bucket", ")", "db", ".", "session", ".", "commit", "(", ")" ]
Setup CORS processing for the application .
def setup ( app : web . Application , * , defaults : Mapping [ str , Union [ ResourceOptions , Mapping [ str , Any ] ] ] = None ) -> CorsConfig : cors = CorsConfig ( app , defaults = defaults ) app [ APP_CONFIG_KEY ] = cors return cors
251,368
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/__init__.py#L40-L67
[ "def", "calculate_journal_volume", "(", "pub_date", ",", "year", ")", ":", "try", ":", "volume", "=", "str", "(", "pub_date", ".", "tm_year", "-", "year", "+", "1", ")", "except", "TypeError", ":", "volume", "=", "None", "except", "AttributeError", ":", "volume", "=", "None", "return", "volume" ]
Parse Access - Control - Request - Method header of the preflight request
def _parse_request_method ( request : web . Request ) : method = request . headers . get ( hdrs . ACCESS_CONTROL_REQUEST_METHOD ) if method is None : raise web . HTTPForbidden ( text = "CORS preflight request failed: " "'Access-Control-Request-Method' header is not specified" ) # FIXME: validate method string (ABNF: method = token), if parsing # fails, raise HTTPForbidden. return method
251,369
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/preflight_handler.py#L10-L22
[ "async", "def", "on_raw_422", "(", "self", ",", "message", ")", ":", "await", "self", ".", "_registration_completed", "(", "message", ")", "self", ".", "motd", "=", "None", "await", "self", ".", "on_connect", "(", ")" ]
Parse Access - Control - Request - Headers header or the preflight request
def _parse_request_headers ( request : web . Request ) : headers = request . headers . get ( hdrs . ACCESS_CONTROL_REQUEST_HEADERS ) if headers is None : return frozenset ( ) # FIXME: validate each header string, if parsing fails, raise # HTTPForbidden. # FIXME: check, that headers split and stripped correctly (according # to ABNF). headers = ( h . strip ( " \t" ) . upper ( ) for h in headers . split ( "," ) ) # pylint: disable=bad-builtin return frozenset ( filter ( None , headers ) )
251,370
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/preflight_handler.py#L25-L40
[ "def", "download", "(", "self", ",", "directory", "=", "'~/Music'", ",", "song_name", "=", "'%a - %s - %A'", ")", ":", "formatted", "=", "self", ".", "format", "(", "song_name", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "+", "os", ".", "path", ".", "sep", "+", "formatted", "+", "'.mp3'", "try", ":", "raw", "=", "self", ".", "safe_download", "(", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "raw", ")", "except", ":", "raise", "return", "formatted" ]
CORS preflight request handler
async def _preflight_handler ( self , request : web . Request ) : # Handle according to part 6.2 of the CORS specification. origin = request . headers . get ( hdrs . ORIGIN ) if origin is None : # Terminate CORS according to CORS 6.2.1. raise web . HTTPForbidden ( text = "CORS preflight request failed: " "origin header is not specified in the request" ) # CORS 6.2.3. Doing it out of order is not an error. request_method = self . _parse_request_method ( request ) # CORS 6.2.5. Doing it out of order is not an error. try : config = await self . _get_config ( request , origin , request_method ) except KeyError : raise web . HTTPForbidden ( text = "CORS preflight request failed: " "request method {!r} is not allowed " "for {!r} origin" . format ( request_method , origin ) ) if not config : # No allowed origins for the route. # Terminate CORS according to CORS 6.2.1. raise web . HTTPForbidden ( text = "CORS preflight request failed: " "no origins are allowed" ) options = config . get ( origin , config . get ( "*" ) ) if options is None : # No configuration for the origin - deny. # Terminate CORS according to CORS 6.2.2. raise web . HTTPForbidden ( text = "CORS preflight request failed: " "origin '{}' is not allowed" . format ( origin ) ) # CORS 6.2.4 request_headers = self . _parse_request_headers ( request ) # CORS 6.2.6 if options . allow_headers == "*" : pass else : disallowed_headers = request_headers - options . allow_headers if disallowed_headers : raise web . HTTPForbidden ( text = "CORS preflight request failed: " "headers are not allowed: {}" . format ( ", " . join ( disallowed_headers ) ) ) # Ok, CORS actual request with specified in the preflight request # parameters is allowed. # Set appropriate headers and return 200 response. response = web . Response ( ) # CORS 6.2.7 response . headers [ hdrs . ACCESS_CONTROL_ALLOW_ORIGIN ] = origin if options . allow_credentials : # Set allowed credentials. response . headers [ hdrs . ACCESS_CONTROL_ALLOW_CREDENTIALS ] = _TRUE # CORS 6.2.8 if options . max_age is not None : response . headers [ hdrs . ACCESS_CONTROL_MAX_AGE ] = str ( options . max_age ) # CORS 6.2.9 # TODO: more optimal for client preflight request cache would be to # respond with ALL allowed methods. response . headers [ hdrs . ACCESS_CONTROL_ALLOW_METHODS ] = request_method # CORS 6.2.10 if request_headers : # Note: case of the headers in the request is changed, but this # shouldn't be a problem, since the headers should be compared in # the case-insensitive way. response . headers [ hdrs . ACCESS_CONTROL_ALLOW_HEADERS ] = "," . join ( request_headers ) return response
251,371
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/preflight_handler.py#L45-L130
[ "def", "common_start", "(", "*", "args", ")", ":", "def", "_iter", "(", ")", ":", "for", "s", "in", "zip", "(", "*", "args", ")", ":", "if", "len", "(", "set", "(", "s", ")", ")", "<", "len", "(", "args", ")", ":", "yield", "s", "[", "0", "]", "else", ":", "return", "out", "=", "\"\"", ".", "join", "(", "_iter", "(", ")", ")", ".", "strip", "(", ")", "result", "=", "[", "s", "for", "s", "in", "args", "if", "not", "s", ".", "startswith", "(", "out", ")", "]", "result", ".", "insert", "(", "0", ",", "out", ")", "return", "', '", ".", "join", "(", "result", ")" ]
Add OPTIONS handler for all routes defined by routing_entity .
def add_preflight_handler ( self , routing_entity : Union [ web . Resource , web . StaticResource , web . ResourceRoute ] , handler ) : if isinstance ( routing_entity , web . Resource ) : resource = routing_entity # Add preflight handler for Resource, if not yet added. if resource in self . _resources_with_preflight_handlers : # Preflight handler already added for this resource. return for route_obj in resource : if route_obj . method == hdrs . METH_OPTIONS : if route_obj . handler is handler : return # already added else : raise ValueError ( "{!r} already has OPTIONS handler {!r}" . format ( resource , route_obj . handler ) ) elif route_obj . method == hdrs . METH_ANY : if _is_web_view ( route_obj ) : self . _preflight_routes . add ( route_obj ) self . _resources_with_preflight_handlers . add ( resource ) return else : raise ValueError ( "{!r} already has a '*' handler " "for all methods" . format ( resource ) ) preflight_route = resource . add_route ( hdrs . METH_OPTIONS , handler ) self . _preflight_routes . add ( preflight_route ) self . _resources_with_preflight_handlers . add ( resource ) elif isinstance ( routing_entity , web . StaticResource ) : resource = routing_entity # Add preflight handler for Resource, if not yet added. if resource in self . _resources_with_preflight_handlers : # Preflight handler already added for this resource. return resource . set_options_route ( handler ) preflight_route = resource . _routes [ hdrs . METH_OPTIONS ] self . _preflight_routes . add ( preflight_route ) self . _resources_with_preflight_handlers . add ( resource ) elif isinstance ( routing_entity , web . ResourceRoute ) : route = routing_entity if not self . is_cors_for_resource ( route . resource ) : self . add_preflight_handler ( route . resource , handler ) else : raise ValueError ( "Resource or ResourceRoute expected, got {!r}" . format ( routing_entity ) )
251,372
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/urldispatcher_router_adapter.py#L137-L200
[ "def", "template", "(", "client", ",", "src", ",", "dest", ",", "paths", ",", "opt", ")", ":", "key_map", "=", "cli_hash", "(", "opt", ".", "key_map", ")", "obj", "=", "{", "}", "for", "path", "in", "paths", ":", "response", "=", "client", ".", "read", "(", "path", ")", "if", "not", "response", ":", "raise", "aomi", ".", "exceptions", ".", "VaultData", "(", "\"Unable to retrieve %s\"", "%", "path", ")", "if", "is_aws", "(", "response", "[", "'data'", "]", ")", "and", "'sts'", "not", "in", "path", ":", "renew_secret", "(", "client", ",", "response", ",", "opt", ")", "for", "s_k", ",", "s_v", "in", "response", "[", "'data'", "]", ".", "items", "(", ")", ":", "o_key", "=", "s_k", "if", "s_k", "in", "key_map", ":", "o_key", "=", "key_map", "[", "s_k", "]", "k_name", "=", "secret_key_name", "(", "path", ",", "o_key", ",", "opt", ")", ".", "lower", "(", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", "obj", "[", "k_name", "]", "=", "s_v", "template_obj", "=", "blend_vars", "(", "obj", ",", "opt", ")", "output", "=", "render", "(", "grok_template_file", "(", "src", ")", ",", "template_obj", ")", "write_raw_file", "(", "output", ",", "abspath", "(", "dest", ")", ")" ]
Is request is a CORS preflight request .
def is_preflight_request ( self , request : web . Request ) -> bool : route = self . _request_route ( request ) if _is_web_view ( route , strict = False ) : return request . method == 'OPTIONS' return route in self . _preflight_routes
251,373
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/urldispatcher_router_adapter.py#L214-L219
[ "def", "follow", "(", "resources", ",", "*", "*", "kwargs", ")", ":", "# subscribe", "client", "=", "redis", ".", "Redis", "(", "decode_responses", "=", "True", ",", "*", "*", "kwargs", ")", "resources", "=", "resources", "if", "resources", "else", "find_resources", "(", "client", ")", "channels", "=", "[", "Keys", ".", "EXTERNAL", ".", "format", "(", "resource", ")", "for", "resource", "in", "resources", "]", "if", "resources", ":", "subscription", "=", "Subscription", "(", "client", ",", "*", "channels", ")", "# listen", "while", "resources", ":", "try", ":", "message", "=", "subscription", ".", "listen", "(", ")", "if", "message", "[", "'type'", "]", "==", "'message'", ":", "print", "(", "message", "[", "'data'", "]", ")", "except", "KeyboardInterrupt", ":", "break" ]
Is request is a request for CORS - enabled resource .
def is_cors_enabled_on_request ( self , request : web . Request ) -> bool : return self . _request_resource ( request ) in self . _resource_config
251,374
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/urldispatcher_router_adapter.py#L221-L224
[ "def", "delete_value", "(", "hive", ",", "key", ",", "vname", "=", "None", ",", "use_32bit_registry", "=", "False", ")", ":", "return", "__utils__", "[", "'reg.delete_value'", "]", "(", "hive", "=", "hive", ",", "key", "=", "key", ",", "vname", "=", "vname", ",", "use_32bit_registry", "=", "use_32bit_registry", ")" ]
Record configuration for resource or it s route .
def set_config_for_routing_entity ( self , routing_entity : Union [ web . Resource , web . StaticResource , web . ResourceRoute ] , config ) : if isinstance ( routing_entity , ( web . Resource , web . StaticResource ) ) : resource = routing_entity # Add resource configuration or fail if it's already added. if resource in self . _resource_config : raise ValueError ( "CORS is already configured for {!r} resource." . format ( resource ) ) self . _resource_config [ resource ] = _ResourceConfig ( default_config = config ) elif isinstance ( routing_entity , web . ResourceRoute ) : route = routing_entity # Add resource's route configuration or fail if it's already added. if route . resource not in self . _resource_config : self . set_config_for_routing_entity ( route . resource , config ) if route . resource not in self . _resource_config : raise ValueError ( "Can't setup CORS for {!r} request, " "CORS must be enabled for route's resource first." . format ( route ) ) resource_config = self . _resource_config [ route . resource ] if route . method in resource_config . method_config : raise ValueError ( "Can't setup CORS for {!r} route: CORS already " "configured on resource {!r} for {} method" . format ( route , route . resource , route . method ) ) resource_config . method_config [ route . method ] = config else : raise ValueError ( "Resource or ResourceRoute expected, got {!r}" . format ( routing_entity ) )
251,375
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/urldispatcher_router_adapter.py#L226-L271
[ "def", "set_contents", "(", "self", ",", "stream", ",", "progress_callback", "=", "None", ")", ":", "size", ",", "checksum", "=", "self", ".", "multipart", ".", "file", ".", "update_contents", "(", "stream", ",", "seek", "=", "self", ".", "start_byte", ",", "size", "=", "self", ".", "part_size", ",", "progress_callback", "=", "progress_callback", ",", ")", "self", ".", "checksum", "=", "checksum", "return", "self" ]
Get stored CORS configuration for routing entity that handles specified request .
def get_non_preflight_request_config ( self , request : web . Request ) : assert self . is_cors_enabled_on_request ( request ) resource = self . _request_resource ( request ) resource_config = self . _resource_config [ resource ] # Take Route config (if any) with defaults from Resource CORS # configuration and global defaults. route = request . match_info . route if _is_web_view ( route , strict = False ) : method_config = request . match_info . handler . get_request_config ( request , request . method ) else : method_config = resource_config . method_config . get ( request . method , { } ) defaulted_config = collections . ChainMap ( method_config , resource_config . default_config , self . _default_config ) return defaulted_config
251,376
https://github.com/aio-libs/aiohttp-cors/blob/14affbd95c88c675eb513c1d295ede1897930f94/aiohttp_cors/urldispatcher_router_adapter.py#L302-L324
[ "def", "show_progress", "(", "total_duration", ")", ":", "with", "tqdm", "(", "total", "=", "round", "(", "total_duration", ",", "2", ")", ")", "as", "bar", ":", "def", "handler", "(", "key", ",", "value", ")", ":", "if", "key", "==", "'out_time_ms'", ":", "time", "=", "round", "(", "float", "(", "value", ")", "/", "1000000.", ",", "2", ")", "bar", ".", "update", "(", "time", "-", "bar", ".", "n", ")", "elif", "key", "==", "'progress'", "and", "value", "==", "'end'", ":", "bar", ".", "update", "(", "bar", ".", "total", "-", "bar", ".", "n", ")", "with", "_watch_progress", "(", "handler", ")", "as", "socket_filename", ":", "yield", "socket_filename" ]
Adds a data center resource based upon the attributes specified .
def add ( self , information , timeout = - 1 ) : return self . _client . create ( information , timeout = timeout )
251,377
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/facilities/datacenters.py#L138-L150
[ "def", "start_indexing", "(", "self", ")", ":", "for", "filepath", "in", "self", ".", "filepaths", ":", "with", "open", "(", "filepath", ")", "as", "fp", ":", "blob", "=", "fp", ".", "read", "(", ")", "self", ".", "words", ".", "extend", "(", "self", ".", "tokenize", "(", "blob", ")", ")" ]
Updates the specified data center resource .
def update ( self , resource , timeout = - 1 ) : return self . _client . update ( resource , timeout = timeout )
251,378
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/facilities/datacenters.py#L152-L164
[ "def", "merge", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "merge", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"-w\"", ",", "\"--weightsfile\"", ",", "default", "=", "\"weights.txt\"", ",", "help", "=", "\"Write weights to file\"", ")", "p", ".", "set_outfile", "(", "\"out.bed\"", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "<", "1", ":", "sys", ".", "exit", "(", "not", "p", ".", "print_help", "(", ")", ")", "maps", "=", "args", "outfile", "=", "opts", ".", "outfile", "fp", "=", "must_open", "(", "maps", ")", "b", "=", "Bed", "(", ")", "mapnames", "=", "set", "(", ")", "for", "row", "in", "fp", ":", "mapname", "=", "filename_to_mapname", "(", "fp", ".", "filename", "(", ")", ")", "mapnames", ".", "add", "(", "mapname", ")", "try", ":", "m", "=", "CSVMapLine", "(", "row", ",", "mapname", "=", "mapname", ")", "if", "m", ".", "cm", "<", "0", ":", "logging", ".", "error", "(", "\"Ignore marker with negative genetic distance\"", ")", "print", "(", "row", ".", "strip", "(", ")", ",", "file", "=", "sys", ".", "stderr", ")", "else", ":", "b", ".", "append", "(", "BedLine", "(", "m", ".", "bedline", ")", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "# header or mal-formed line", "continue", "b", ".", "print_to_file", "(", "filename", "=", "outfile", ",", "sorted", "=", "True", ")", "logging", ".", "debug", "(", "\"A total of {0} markers written to `{1}`.\"", ".", "format", "(", "len", "(", "b", ")", ",", "outfile", ")", ")", "assert", "len", "(", "maps", ")", "==", "len", "(", "mapnames", ")", ",", "\"You have a collision in map names\"", "write_weightsfile", "(", "mapnames", ",", "weightsfile", "=", "opts", ".", "weightsfile", ")" ]
Deletes the set of datacenters according to the specified parameters . A filter is required to identify the set of resources to be deleted .
def remove_all ( self , filter , force = False , timeout = - 1 ) : return self . _client . delete_all ( filter = filter , force = force , timeout = timeout )
251,379
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/facilities/datacenters.py#L166-L184
[ "def", "defer", "(", "coro", ",", "delay", "=", "1", ")", ":", "assert_corofunction", "(", "coro", "=", "coro", ")", "@", "asyncio", ".", "coroutine", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "# Wait until we're done", "yield", "from", "asyncio", ".", "sleep", "(", "delay", ")", "return", "(", "yield", "from", "coro", "(", "*", "args", ",", "*", "*", "kw", ")", ")", "return", "wrapper" ]
Gets all drive enclosures that match the filter .
def get_by ( self , field , value ) : return self . _client . get_by ( field = field , value = value )
251,380
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/drive_enclosures.py#L91-L104
[ "def", "_get_api_id", "(", "self", ",", "event_properties", ")", ":", "api_id", "=", "event_properties", ".", "get", "(", "\"RestApiId\"", ")", "if", "isinstance", "(", "api_id", ",", "dict", ")", "and", "\"Ref\"", "in", "api_id", ":", "api_id", "=", "api_id", "[", "\"Ref\"", "]", "return", "api_id" ]
Refreshes a drive enclosure .
def refresh_state ( self , id_or_uri , configuration , timeout = - 1 ) : uri = self . _client . build_uri ( id_or_uri ) + self . REFRESH_STATE_PATH return self . _client . update ( resource = configuration , uri = uri , timeout = timeout )
251,381
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/drive_enclosures.py#L119-L133
[ "def", "keep_sources", "(", "self", ",", "keep", ")", ":", "if", "self", ".", "unmixing_", "is", "None", "or", "self", ".", "mixing_", "is", "None", ":", "raise", "RuntimeError", "(", "\"No sources available (run do_mvarica first)\"", ")", "n_sources", "=", "self", ".", "mixing_", ".", "shape", "[", "0", "]", "self", ".", "remove_sources", "(", "np", ".", "setdiff1d", "(", "np", ".", "arange", "(", "n_sources", ")", ",", "np", ".", "array", "(", "keep", ")", ")", ")", "return", "self" ]
Gets a list of Deployment Servers based on optional sorting and filtering and constrained by start and count parameters .
def get_all ( self , start = 0 , count = - 1 , filter = '' , fields = '' , query = '' , sort = '' , view = '' ) : return self . _client . get_all ( start , count , filter = filter , sort = sort , query = query , fields = fields , view = view )
251,382
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/os_deployment_servers.py#L43-L75
[ "def", "invalidate", "(", "self", ",", "key", ")", ":", "path", "=", "self", ".", "path", "(", "self", ".", "xform_key", "(", "key", ")", ")", "try", ":", "LOG", ".", "debug", "(", "'invalidate %s (%s)'", ",", "key", ",", "path", ")", "path", ".", "unlink", "(", ")", "except", "OSError", ":", "pass" ]
Deletes a Deployment Server object based on its UUID or URI .
def delete ( self , resource , force = False , timeout = - 1 ) : return self . _client . delete ( resource , force = force , timeout = timeout )
251,383
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/os_deployment_servers.py#L153-L171
[ "def", "parse_journal", "(", "journal", ")", ":", "events", "=", "[", "e", "for", "e", "in", "journal", "if", "not", "isinstance", "(", "e", ",", "CorruptedUsnRecord", ")", "]", "keyfunc", "=", "lambda", "e", ":", "str", "(", "e", ".", "file_reference_number", ")", "+", "e", ".", "file_name", "+", "e", ".", "timestamp", "event_groups", "=", "(", "tuple", "(", "g", ")", "for", "k", ",", "g", "in", "groupby", "(", "events", ",", "key", "=", "keyfunc", ")", ")", "if", "len", "(", "events", ")", "<", "len", "(", "list", "(", "journal", ")", ")", ":", "LOGGER", ".", "debug", "(", "\"Corrupted records in UsnJrnl, some events might be missing.\"", ")", "return", "[", "journal_event", "(", "g", ")", "for", "g", "in", "event_groups", "]" ]
Gets a list of all the Image Streamer resources based on optional sorting and filtering and constrained by start and count parameters .
def get_appliances ( self , start = 0 , count = - 1 , filter = '' , fields = '' , query = '' , sort = '' , view = '' ) : uri = self . URI + '/image-streamer-appliances' return self . _client . get_all ( start , count , filter = filter , sort = sort , query = query , fields = fields , view = view , uri = uri )
251,384
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/os_deployment_servers.py#L183-L217
[ "def", "expire_hit", "(", "self", ",", "hit_id", ")", ":", "try", ":", "self", ".", "mturk", ".", "update_expiration_for_hit", "(", "HITId", "=", "hit_id", ",", "ExpireAt", "=", "0", ")", "except", "Exception", "as", "ex", ":", "raise", "MTurkServiceException", "(", "\"Failed to expire HIT {}: {}\"", ".", "format", "(", "hit_id", ",", "str", "(", "ex", ")", ")", ")", "return", "True" ]
Gets the particular Image Streamer resource based on its ID or URI .
def get_appliance ( self , id_or_uri , fields = '' ) : uri = self . URI + '/image-streamer-appliances/' + extract_id_from_uri ( id_or_uri ) if fields : uri += '?fields=' + fields return self . _client . get ( uri )
251,385
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/os_deployment_servers.py#L219-L236
[ "def", "on_end_validation", "(", "self", ",", "event", ")", ":", "self", ".", "Enable", "(", ")", "self", ".", "Show", "(", ")", "self", ".", "magic_gui_frame", ".", "Destroy", "(", ")" ]
Gets the particular Image Streamer resource based on its name .
def get_appliance_by_name ( self , appliance_name ) : appliances = self . get_appliances ( ) if appliances : for appliance in appliances : if appliance [ 'name' ] == appliance_name : return appliance return None
251,386
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/os_deployment_servers.py#L238-L255
[ "def", "on_end_validation", "(", "self", ",", "event", ")", ":", "self", ".", "Enable", "(", ")", "self", ".", "Show", "(", ")", "self", ".", "magic_gui_frame", ".", "Destroy", "(", ")" ]
Gets all ports or a specific managed target port for the specified storage system .
def get_managed_ports ( self , id_or_uri , port_id_or_uri = '' ) : if port_id_or_uri : uri = self . _client . build_uri ( port_id_or_uri ) if "/managedPorts" not in uri : uri = self . _client . build_uri ( id_or_uri ) + "/managedPorts" + "/" + port_id_or_uri else : uri = self . _client . build_uri ( id_or_uri ) + "/managedPorts" return self . _client . get_collection ( uri )
251,387
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/storage_systems.py#L163-L182
[ "def", "real_main", "(", "release_url", "=", "None", ",", "tests_json_path", "=", "None", ",", "upload_build_id", "=", "None", ",", "upload_release_name", "=", "None", ")", ":", "coordinator", "=", "workers", ".", "get_coordinator", "(", ")", "fetch_worker", ".", "register", "(", "coordinator", ")", "coordinator", ".", "start", "(", ")", "data", "=", "open", "(", "FLAGS", ".", "tests_json_path", ")", ".", "read", "(", ")", "tests", "=", "load_tests", "(", "data", ")", "item", "=", "DiffMyImages", "(", "release_url", ",", "tests", ",", "upload_build_id", ",", "upload_release_name", ",", "heartbeat", "=", "workers", ".", "PrintWorkflow", ")", "item", ".", "root", "=", "True", "coordinator", ".", "input_queue", ".", "put", "(", "item", ")", "coordinator", ".", "wait_one", "(", ")", "coordinator", ".", "stop", "(", ")", "coordinator", ".", "join", "(", ")" ]
Retrieve a storage system by its IP .
def get_by_ip_hostname ( self , ip_hostname ) : resources = self . _client . get_all ( ) resources_filtered = [ x for x in resources if x [ 'credentials' ] [ 'ip_hostname' ] == ip_hostname ] if resources_filtered : return resources_filtered [ 0 ] else : return None
251,388
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/storage_systems.py#L211-L230
[ "def", "add_arrows", "(", "self", ",", "cent", ",", "direction", ",", "mag", "=", "1", ",", "*", "*", "kwargs", ")", ":", "direction", "=", "direction", ".", "copy", "(", ")", "if", "cent", ".", "ndim", "!=", "2", ":", "cent", "=", "cent", ".", "reshape", "(", "(", "-", "1", ",", "3", ")", ")", "if", "direction", ".", "ndim", "!=", "2", ":", "direction", "=", "direction", ".", "reshape", "(", "(", "-", "1", ",", "3", ")", ")", "direction", "[", ":", ",", "0", "]", "*=", "mag", "direction", "[", ":", ",", "1", "]", "*=", "mag", "direction", "[", ":", ",", "2", "]", "*=", "mag", "pdata", "=", "vtki", ".", "vector_poly_data", "(", "cent", ",", "direction", ")", "# Create arrow object", "arrow", "=", "vtk", ".", "vtkArrowSource", "(", ")", "arrow", ".", "Update", "(", ")", "glyph3D", "=", "vtk", ".", "vtkGlyph3D", "(", ")", "glyph3D", ".", "SetSourceData", "(", "arrow", ".", "GetOutput", "(", ")", ")", "glyph3D", ".", "SetInputData", "(", "pdata", ")", "glyph3D", ".", "SetVectorModeToUseVector", "(", ")", "glyph3D", ".", "Update", "(", ")", "arrows", "=", "wrap", "(", "glyph3D", ".", "GetOutput", "(", ")", ")", "return", "self", ".", "add_mesh", "(", "arrows", ",", "*", "*", "kwargs", ")" ]
Retrieve a storage system by its hostname .
def get_by_hostname ( self , hostname ) : resources = self . _client . get_all ( ) resources_filtered = [ x for x in resources if x [ 'hostname' ] == hostname ] if resources_filtered : return resources_filtered [ 0 ] else : return None
251,389
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/storage_systems.py#L232-L251
[ "def", "silence", "(", "self", ",", "seq_set", ":", "SequenceSet", ",", "flag_set", ":", "AbstractSet", "[", "Flag", "]", ",", "flag_op", ":", "FlagOp", ")", "->", "None", ":", "session_flags", "=", "self", ".", "session_flags", "permanent_flag_set", "=", "self", ".", "permanent_flags", "&", "flag_set", "session_flag_set", "=", "session_flags", "&", "flag_set", "for", "seq", ",", "msg", "in", "self", ".", "_messages", ".", "get_all", "(", "seq_set", ")", ":", "msg_flags", "=", "msg", ".", "permanent_flags", "msg_sflags", "=", "session_flags", ".", "get", "(", "msg", ".", "uid", ")", "updated_flags", "=", "flag_op", ".", "apply", "(", "msg_flags", ",", "permanent_flag_set", ")", "updated_sflags", "=", "flag_op", ".", "apply", "(", "msg_sflags", ",", "session_flag_set", ")", "if", "msg_flags", "!=", "updated_flags", ":", "self", ".", "_silenced_flags", ".", "add", "(", "(", "msg", ".", "uid", ",", "updated_flags", ")", ")", "if", "msg_sflags", "!=", "updated_sflags", ":", "self", ".", "_silenced_sflags", ".", "add", "(", "(", "msg", ".", "uid", ",", "updated_sflags", ")", ")" ]
Gets the storage ports that are connected on the specified networks based on the storage system port s expected network connectivity .
def get_reachable_ports ( self , id_or_uri , start = 0 , count = - 1 , filter = '' , query = '' , sort = '' , networks = [ ] ) : uri = self . _client . build_uri ( id_or_uri ) + "/reachable-ports" if networks : elements = "\'" for n in networks : elements += n + ',' elements = elements [ : - 1 ] + "\'" uri = uri + "?networks=" + elements return self . _client . get ( self . _client . build_query_uri ( start = start , count = count , filter = filter , query = query , sort = sort , uri = uri ) )
251,390
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/storage_systems.py#L253-L271
[ "def", "append_request_id", "(", "req", ",", "resp", ",", "resource", ",", "params", ")", ":", "def", "get_headers", "(", "resp", ")", ":", "if", "hasattr", "(", "resp", ",", "'headers'", ")", ":", "return", "resp", ".", "headers", "if", "hasattr", "(", "resp", ",", "'_headers'", ")", ":", "return", "resp", ".", "_headers", "return", "None", "if", "(", "isinstance", "(", "resp", ",", "Response", ")", "or", "(", "get_headers", "(", "resp", ")", "is", "not", "None", ")", ")", ":", "# Extract 'x-request-id' from headers if", "# response is a Response object.", "request_id", "=", "get_headers", "(", "resp", ")", ".", "get", "(", "'x-request-id'", ")", "else", ":", "# If resp is of type string or None.", "request_id", "=", "resp", "if", "resource", ".", "req_ids", "is", "None", ":", "resource", ".", "req_ids", "=", "[", "]", "if", "request_id", "not", "in", "resource", ".", "req_ids", ":", "resource", ".", "req_ids", ".", "append", "(", "request_id", ")" ]
Gets a list of volume templates . Returns a list of storage templates belonging to the storage system .
def get_templates ( self , id_or_uri , start = 0 , count = - 1 , filter = '' , query = '' , sort = '' ) : uri = self . _client . build_uri ( id_or_uri ) + "/templates" return self . _client . get ( self . _client . build_query_uri ( start = start , count = count , filter = filter , query = query , sort = sort , uri = uri ) )
251,391
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/storage_systems.py#L273-L282
[ "def", "get_snpeff_info", "(", "snpeff_string", ",", "snpeff_header", ")", ":", "snpeff_annotations", "=", "[", "dict", "(", "zip", "(", "snpeff_header", ",", "snpeff_annotation", ".", "split", "(", "'|'", ")", ")", ")", "for", "snpeff_annotation", "in", "snpeff_string", ".", "split", "(", "','", ")", "]", "return", "snpeff_annotations" ]
Gets the reserved vlan ID range for the fabric .
def get_reserved_vlan_range ( self , id_or_uri ) : uri = self . _client . build_uri ( id_or_uri ) + "/reserved-vlan-range" return self . _client . get ( uri )
251,392
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/fabrics.py#L107-L121
[ "def", "restore", "(", "archive", ",", "oqdata", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "oqdata", ")", ":", "sys", ".", "exit", "(", "'%s exists already'", "%", "oqdata", ")", "if", "'://'", "in", "archive", ":", "# get the zip archive from an URL", "resp", "=", "requests", ".", "get", "(", "archive", ")", "_", ",", "archive", "=", "archive", ".", "rsplit", "(", "'/'", ",", "1", ")", "with", "open", "(", "archive", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "resp", ".", "content", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "archive", ")", ":", "sys", ".", "exit", "(", "'%s does not exist'", "%", "archive", ")", "t0", "=", "time", ".", "time", "(", ")", "oqdata", "=", "os", ".", "path", ".", "abspath", "(", "oqdata", ")", "assert", "archive", ".", "endswith", "(", "'.zip'", ")", ",", "archive", "os", ".", "mkdir", "(", "oqdata", ")", "zipfile", ".", "ZipFile", "(", "archive", ")", ".", "extractall", "(", "oqdata", ")", "dbpath", "=", "os", ".", "path", ".", "join", "(", "oqdata", ",", "'db.sqlite3'", ")", "db", "=", "Db", "(", "sqlite3", ".", "connect", ",", "dbpath", ",", "isolation_level", "=", "None", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "n", "=", "0", "for", "fname", "in", "os", ".", "listdir", "(", "oqdata", ")", ":", "mo", "=", "re", ".", "match", "(", "'calc_(\\d+)\\.hdf5'", ",", "fname", ")", "if", "mo", ":", "job_id", "=", "int", "(", "mo", ".", "group", "(", "1", ")", ")", "fullname", "=", "os", ".", "path", ".", "join", "(", "oqdata", ",", "fname", ")", "[", ":", "-", "5", "]", "# strip .hdf5", "db", "(", "\"UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x\"", ",", "getpass", ".", "getuser", "(", ")", ",", "fullname", ",", "job_id", ")", "safeprint", "(", "'Restoring '", "+", "fname", ")", "n", "+=", "1", "dt", "=", "time", ".", "time", "(", ")", "-", "t0", "safeprint", "(", "'Extracted %d calculations into %s in %d seconds'", "%", "(", "n", ",", "oqdata", ",", "dt", ")", ")" ]
Updates the reserved vlan ID range for the fabric .
def update_reserved_vlan_range ( self , id_or_uri , vlan_pool , force = False ) : uri = self . _client . build_uri ( id_or_uri ) + "/reserved-vlan-range" return self . _client . update ( resource = vlan_pool , uri = uri , force = force , default_values = self . DEFAULT_VALUES )
251,393
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/fabrics.py#L123-L140
[ "def", "restore", "(", "archive", ",", "oqdata", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "oqdata", ")", ":", "sys", ".", "exit", "(", "'%s exists already'", "%", "oqdata", ")", "if", "'://'", "in", "archive", ":", "# get the zip archive from an URL", "resp", "=", "requests", ".", "get", "(", "archive", ")", "_", ",", "archive", "=", "archive", ".", "rsplit", "(", "'/'", ",", "1", ")", "with", "open", "(", "archive", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "resp", ".", "content", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "archive", ")", ":", "sys", ".", "exit", "(", "'%s does not exist'", "%", "archive", ")", "t0", "=", "time", ".", "time", "(", ")", "oqdata", "=", "os", ".", "path", ".", "abspath", "(", "oqdata", ")", "assert", "archive", ".", "endswith", "(", "'.zip'", ")", ",", "archive", "os", ".", "mkdir", "(", "oqdata", ")", "zipfile", ".", "ZipFile", "(", "archive", ")", ".", "extractall", "(", "oqdata", ")", "dbpath", "=", "os", ".", "path", ".", "join", "(", "oqdata", ",", "'db.sqlite3'", ")", "db", "=", "Db", "(", "sqlite3", ".", "connect", ",", "dbpath", ",", "isolation_level", "=", "None", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "n", "=", "0", "for", "fname", "in", "os", ".", "listdir", "(", "oqdata", ")", ":", "mo", "=", "re", ".", "match", "(", "'calc_(\\d+)\\.hdf5'", ",", "fname", ")", "if", "mo", ":", "job_id", "=", "int", "(", "mo", ".", "group", "(", "1", ")", ")", "fullname", "=", "os", ".", "path", ".", "join", "(", "oqdata", ",", "fname", ")", "[", ":", "-", "5", "]", "# strip .hdf5", "db", "(", "\"UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x\"", ",", "getpass", ".", "getuser", "(", ")", ",", "fullname", ",", "job_id", ")", "safeprint", "(", "'Restoring '", "+", "fname", ")", "n", "+=", "1", "dt", "=", "time", ".", "time", "(", ")", "-", "t0", "safeprint", "(", "'Extracted %d calculations into %s in %d seconds'", "%", "(", "n", ",", "oqdata", ",", "dt", ")", ")" ]
Get the role by its URI or Name .
def get ( self , name_or_uri ) : name_or_uri = quote ( name_or_uri ) return self . _client . get ( name_or_uri )
251,394
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/security/roles.py#L74-L86
[ "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" ]
Gets the list of drives allocated to this SAS logical JBOD .
def get_drives ( self , id_or_uri ) : uri = self . _client . build_uri ( id_or_uri = id_or_uri ) + self . DRIVES_PATH return self . _client . get ( id_or_uri = uri )
251,395
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/storage/sas_logical_jbods.py#L104-L115
[ "def", "commit", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "model", "is", "None", "or", "self", ".", "model", ".", "json", "is", "None", ":", "raise", "MissingModelError", "(", ")", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "before_record_update", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "record", "=", "self", ")", "self", ".", "validate", "(", "*", "*", "kwargs", ")", "self", ".", "model", ".", "json", "=", "dict", "(", "self", ")", "flag_modified", "(", "self", ".", "model", ",", "'json'", ")", "db", ".", "session", ".", "merge", "(", "self", ".", "model", ")", "after_record_update", ".", "send", "(", "current_app", ".", "_get_current_object", "(", ")", ",", "record", "=", "self", ")", "return", "self" ]
Enables or disables a range .
def enable ( self , information , id_or_uri , timeout = - 1 ) : uri = self . _client . build_uri ( id_or_uri ) return self . _client . update ( information , uri , timeout = timeout )
251,396
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/id_pools_ranges.py#L86-L102
[ "def", "add_to_package_numpy", "(", "self", ",", "root", ",", "ndarray", ",", "node_path", ",", "target", ",", "source_path", ",", "transform", ",", "custom_meta", ")", ":", "filehash", "=", "self", ".", "save_numpy", "(", "ndarray", ")", "metahash", "=", "self", ".", "save_metadata", "(", "custom_meta", ")", "self", ".", "_add_to_package_contents", "(", "root", ",", "node_path", ",", "[", "filehash", "]", ",", "target", ",", "source_path", ",", "transform", ",", "metahash", ")" ]
Gets all fragments that have been allocated in range .
def get_allocated_fragments ( self , id_or_uri , count = - 1 , start = 0 ) : uri = self . _client . build_uri ( id_or_uri ) + "/allocated-fragments?start={0}&count={1}" . format ( start , count ) return self . _client . get_collection ( uri )
251,397
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/id_pools_ranges.py#L123-L142
[ "def", "_get_npcap_config", "(", "param_key", ")", ":", "hkey", "=", "winreg", ".", "HKEY_LOCAL_MACHINE", "node", "=", "r\"SYSTEM\\CurrentControlSet\\Services\\npcap\\Parameters\"", "try", ":", "key", "=", "winreg", ".", "OpenKey", "(", "hkey", ",", "node", ")", "dot11_adapters", ",", "_", "=", "winreg", ".", "QueryValueEx", "(", "key", ",", "param_key", ")", "winreg", ".", "CloseKey", "(", "key", ")", "except", "WindowsError", ":", "return", "None", "return", "dot11_adapters" ]
Gets a list of logical interconnects based on optional sorting and filtering and is constrained by start and count parameters .
def get_all ( self , start = 0 , count = - 1 , sort = '' ) : return self . _helper . get_all ( start , count , sort = sort )
251,398
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/logical_interconnects.py#L89-L109
[ "def", "make_response", "(", "response", ")", ":", "if", "isinstance", "(", "response", ",", "unicode", ")", "or", "isinstance", "(", "response", ",", "str", ")", ":", "response", "=", "(", "response", ",", "'text/html'", ")", "return", "response" ]
Returns logical interconnects to a consistent state . The current logical interconnect state is compared to the associated logical interconnect group .
def update_compliance ( self , timeout = - 1 ) : uri = "{}/compliance" . format ( self . data [ "uri" ] ) return self . _helper . update ( None , uri , timeout = timeout )
251,399
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/logical_interconnects.py#L131-L150
[ "def", "get_info", "(", "self", ")", "->", "dict", ":", "with", "suppress_stdout", "(", ")", ":", "with", "youtube_dl", ".", "YoutubeDL", "(", ")", "as", "ydl", ":", "info_dict", "=", "ydl", ".", "extract_info", "(", "self", ".", "url", ",", "download", "=", "False", ")", "return", "info_dict" ]