query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
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", ".", "a...
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", "=...
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", "=", "argtype...
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", ",", "lpA...
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'", ",...
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",...
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", ","...
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", ...
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", ...
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", ...
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", "(", "...
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", ".", "warn...
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", ":", ...
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"...
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}'", ".", ...
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...
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", "...
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", "(", "'Infe...
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_a...
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", ")", ")", "# Becau...
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", "...
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", ",", ")", ",", "(", ")", ",", "(", ")", ")", ...
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"...
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_pat...
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'", ":", ...
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+9l...
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_spe...
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", "(", "...
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", ".", "ha...
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", "(", "pa...
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...
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", ":", ...
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", "(", ...
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", ...
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"...
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", ...
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 omit...
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", ":", ...
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", ...
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"...
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\"", ",", "foot...
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", ...
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", "(", "filest...
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...
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 ...
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", ",", "*", "*", ...
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"...
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'", "n...
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...
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'", ":", "corruptDenseVe...
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", "no...
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"...
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", "=", ...
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", "=", "'...
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", "[", "\"...
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_...
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'", ":", ...
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", ")", ")...
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://...
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", "("...
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", ":", ...
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", ")...
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", ...
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", ".", "...
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...
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", "=", "v...
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", "...
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'", ...
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...
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\"", ")", ...
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"...
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_...
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", "=", "s...
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", ".", ...
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_...
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", "MTurkServiceExcept...
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", "...
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", ".", ...
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", "=", ...
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", "("...
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", "snpe...
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 fr...
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 fr...
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", ...
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...
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", "=", ...
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", ")", "...
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"...