idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
250,300
def decode_uuid ( value ) : return uuid . UUID ( bytes = bytes ( bytearray ( ffi . unpack ( value . data , 16 ) ) ) )
Decodes the given uuid value .
40
8
250,301
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
Runs a quick check to see if cargo fmt is installed .
80
13
250,302
def get_modified_files ( ) : c = subprocess . Popen ( [ "git" , "diff-index" , "--cached" , "--name-only" , "HEAD" ] , stdout = subprocess . PIPE ) return c . communicate ( ) [ 0 ] . splitlines ( )
Returns a list of all modified files .
70
8
250,303
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
Return next chunk of data that we would from the file pointer .
92
13
250,304
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
Return information on which file pointer position to read from and how many bytes .
275
15
250,305
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
Remove a single instance of new line at the end of l if it exists .
115
16
250,306
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 )
Return - 1 if read_buffer does not contain new line otherwise the position of the rightmost newline .
53
22
250,307
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
Add additional bytes content as read from the read_position .
56
12
250,308
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
Return True if there is a line that the buffer can return False otherwise .
94
15
250,309
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
Return a new line if it is available .
147
9
250,310
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 )
Read in additional chunks until it is yieldable .
70
10
250,311
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 )
Returns unicode string from the last line until the beginning of file .
134
14
250,312
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 )
if we have a chat_channel_name kwarg have the response include that channel name so the javascript knows to subscribe to that channel ...
158
29
250,313
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 ( )
Decides which version of HendrixDeploy to use and then launches it .
173
15
250,314
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' )
encompasses all the logic for reloading observer .
112
11
250,315
def launch ( * args , * * options ) : action = args [ 0 ] if options [ 'reload' ] : logReload ( options ) else : assignDeploymentInstance ( action , options )
launch acts on the user specified action and options by executing Hedrix . run
43
15
250,316
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
Find the settings module dot path within django s manage . py file
306
14
250,317
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
This function is called by the hxw script . It takes no arguments and returns an instance of HendrixDeploy
111
23
250,318
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
The function to execute when running hx
150
8
250,319
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 )
extends handleHeader to save headers to a local response object
124
12
250,320
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 )
extends handleStatus to instantiate a local response object
61
11
250,321
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 ( ) )
Ensures that the location port is a the given port value Used in handleHeader
123
17
250,322
def handleResponsePart ( self , buffer ) : self . father . write ( buffer ) self . buffer . write ( buffer )
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 .
26
33
250,323
def getChild ( self , path , request ) : return CacheProxyResource ( self . host , self . port , self . path + '/' + urlquote ( path , safe = "" ) , self . reactor )
This is necessary because the parent class would call proxy . ReverseProxyResource instead of CacheProxyResource
45
19
250,324
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 )
Retrieve a static or dynamically generated child resource from me .
93
12
250,325
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
Render a request by forwarding it to the proxied server .
203
12
250,326
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
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 .
63
33
250,327
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 ) } )
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
131
44
250,328
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 } )
establish the address of this new connection and add it to the list of sockets managed by the dispatcher
61
19
250,329
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
Helper function to generate the text content needed to create an init . d executable
419
15
250,330
def startResponse ( self , status , headers , excInfo = None ) : self . status = status self . headers = headers self . reactor . callInThread ( responseInColor , self . request , status , headers ) return self . write
extends startResponse to call speakerBox in a thread
50
11
250,331
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 ( )
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
200
33
250,332
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
if HENDRIX_SERVICES is specified in settings_module it should be a list twisted internet services
124
23
250,333
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
if HENDRIX_CHILD_RESOURCES is specified in settings_module it should be a list resources subclassed from hendrix . contrib . NamedResource
126
37
250,334
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
updates the options dict to use config options in the settings module
230
13
250,335
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 )
Instantiates a HendrixService with this object s threadpool . It will be added as a service later .
103
23
250,336
def catalogServers ( self , hendrix ) : for service in hendrix . services : if isinstance ( service , ( TCPServer , SSLServer ) ) : self . servers . append ( service . name )
collects a list of service names serving on TCP or SSL
48
12
250,337
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 ) ( )
sets up the desired services and runs the requested action
161
10
250,338
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
Iterator for file descriptors . Seperated from launchworkers for clarity and readability .
107
18
250,339
def addSubprocess ( self , fds , name , factory ) : self . _lock . run ( self . _addSubprocess , self , fds , name , factory )
Public method for _addSubprocess . Wraps reactor . adoptStreamConnection in a simple DeferredLock to guarantee workers play well together .
38
28
250,340
def disownService ( self , name ) : _service = self . hendrix . getServiceNamed ( name ) _service . disownServiceParent ( ) return _service . factory
disowns a service on hendirix by name returns a factory for use in the adoptStreamPort part of setting up multiple processes
40
28
250,341
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 ( '.' , '_' ) )
returns The default location of the pid file for process management
79
12
250,342
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 )
Prints the response info in color
142
7
250,343
def addLocalCacheService ( self ) : _cache = self . getCacheService ( ) _cache . setName ( 'cache_proxy' ) _cache . setServiceParent ( self . hendrix )
adds a CacheService to the instatiated HendrixService
44
13
250,344
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 ( )
This is where we put service that we don t want to be duplicated on worker subprocesses
70
20
250,345
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 ] )
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 .
281
41
250,346
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 )
a shortcut for message sending
73
5
250,347
def send_callback_json_message ( value , * args , * * kwargs ) : if value : kwargs [ 'result' ] = value send_json_message ( args [ 0 ] , args [ 1 ] , * * kwargs ) return value
useful for sending messages from callbacks as it puts the result of the callback in the dict for serialization
58
22
250,348
def send ( self , message ) : # usually a json string... for transport in self . transports . values ( ) : transport . protocol . sendMessage ( message )
sends whatever it is to each transport
34
8
250,349
def remove ( self , transport ) : if transport . uid in self . transports : del ( self . transports [ transport . uid ] )
removes a transport if a member of this group
30
10
250,350
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
add a new recipient to be addressable by this MessageDispatcher generate a new uuid address if one is not specified
66
25
250,351
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 ]
removes a transport from all channels to which it belongs .
54
12
250,352
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 ( ) )
address can either be a string or a list of strings
78
11
250,353
def subscribe ( self , transport , data ) : self . add ( transport , address = data . get ( 'hx_subscribe' ) . encode ( ) ) self . send ( data [ 'hx_subscribe' ] , { 'message' : "%r is listening" % transport } )
adds a transport to a channel
64
7
250,354
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
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
140
34
250,355
def options ( argv = [ ] ) : parser = HendrixOptionParser parsed_args = parser . parse_args ( argv ) return vars ( parsed_args [ 0 ] )
A helper function that returns a dictionary of the default key - values pairs
40
14
250,356
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 ]
Unsubscribe this participant from all topic to which it is subscribed .
81
14
250,357
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 )
adds a SSLService to the instaitated HendrixService
95
15
250,358
def addResource ( self , content , uri , headers ) : self . cache [ uri ] = CachedResource ( content , headers )
Adds the a hendrix . contrib . cache . resource . CachedResource to the ReverseProxy cache connection
30
23
250,359
def decompressBuffer ( buffer ) : zbuf = cStringIO . StringIO ( buffer ) zfile = gzip . GzipFile ( fileobj = zbuf ) deflated = zfile . read ( ) zfile . close ( ) return deflated
complements the compressBuffer function in CacheClient
54
10
250,360
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
get the max - age in seconds from the saved headers data
76
12
250,361
def getLastModified ( self ) : last_modified = self . headers . get ( 'last-modified' ) if last_modified : last_modified = self . convertTimeString ( last_modified ) return last_modified
returns the GMT last - modified datetime or None
48
11
250,362
def getDate ( self ) : date = self . headers . get ( 'date' ) if date : date = self . convertTimeString ( date ) return date
returns the GMT response datetime or None
34
9
250,363
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
returns True if cached object is still fresh
71
9
250,364
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
Non - preflight CORS request response processor .
535
10
250,365
def _is_proper_sequence ( seq ) : return ( isinstance ( seq , collections . abc . Sequence ) and not isinstance ( seq , str ) )
Returns is seq is sequence and not string .
36
9
250,366
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
Setup CORS processing for the application .
66
8
250,367
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
Parse Access - Control - Request - Method header of the preflight request
104
15
250,368
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 ) )
Parse Access - Control - Request - Headers header or the preflight request
139
16
250,369
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
CORS preflight request handler
751
6
250,370
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 ) )
Add OPTIONS handler for all routes defined by routing_entity .
518
13
250,371
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
Is request is a CORS preflight request .
67
10
250,372
def is_cors_enabled_on_request ( self , request : web . Request ) -> bool : return self . _request_resource ( request ) in self . _resource_config
Is request is a request for CORS - enabled resource .
40
12
250,373
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 ) )
Record configuration for resource or it s route .
359
9
250,374
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
Get stored CORS configuration for routing entity that handles specified request .
186
13
250,375
def add ( self , information , timeout = - 1 ) : return self . _client . create ( information , timeout = timeout )
Adds a data center resource based upon the attributes specified .
27
11
250,376
def update ( self , resource , timeout = - 1 ) : return self . _client . update ( resource , timeout = timeout )
Updates the specified data center resource .
27
8
250,377
def remove_all ( self , filter , force = False , timeout = - 1 ) : return self . _client . delete_all ( filter = filter , force = force , timeout = timeout )
Deletes the set of datacenters according to the specified parameters . A filter is required to identify the set of resources to be deleted .
41
28
250,378
def get_by ( self , field , value ) : return self . _client . get_by ( field = field , value = value )
Gets all drive enclosures that match the filter .
30
11
250,379
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 )
Refreshes a drive enclosure .
71
7
250,380
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 )
Gets a list of Deployment Servers based on optional sorting and filtering and constrained by start and count parameters .
71
23
250,381
def delete ( self , resource , force = False , timeout = - 1 ) : return self . _client . delete ( resource , force = force , timeout = timeout )
Deletes a Deployment Server object based on its UUID or URI .
35
15
250,382
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 )
Gets a list of all the Image Streamer resources based on optional sorting and filtering and constrained by start and count parameters .
96
25
250,383
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 )
Gets the particular Image Streamer resource based on its ID or URI .
76
15
250,384
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
Gets the particular Image Streamer resource based on its name .
53
13
250,385
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 )
Gets all ports or a specific managed target port for the specified storage system .
140
16
250,386
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
Retrieve a storage system by its IP .
82
9
250,387
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
Retrieve a storage system by its hostname .
67
10
250,388
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 ) )
Gets the storage ports that are connected on the specified networks based on the storage system port s expected network connectivity .
156
23
250,389
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 ) )
Gets a list of volume templates . Returns a list of storage templates belonging to the storage system .
105
20
250,390
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 )
Gets the reserved vlan ID range for the fabric .
59
12
250,391
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 )
Updates the reserved vlan ID range for the fabric .
94
12
250,392
def get ( self , name_or_uri ) : name_or_uri = quote ( name_or_uri ) return self . _client . get ( name_or_uri )
Get the role by its URI or Name .
40
9
250,393
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 )
Gets the list of drives allocated to this SAS logical JBOD .
63
15
250,394
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 )
Enables or disables a range .
54
8
250,395
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 )
Gets all fragments that have been allocated in range .
84
11
250,396
def get_all ( self , start = 0 , count = - 1 , sort = '' ) : return self . _helper . get_all ( start , count , sort = sort )
Gets a list of logical interconnects based on optional sorting and filtering and is constrained by start and count parameters .
40
24
250,397
def update_compliance ( self , timeout = - 1 ) : uri = "{}/compliance" . format ( self . data [ "uri" ] ) return self . _helper . update ( None , uri , timeout = timeout )
Returns logical interconnects to a consistent state . The current logical interconnect state is compared to the associated logical interconnect group .
51
26
250,398
def update_ethernet_settings ( self , configuration , force = False , timeout = - 1 ) : uri = "{}/ethernetSettings" . format ( self . data [ "uri" ] ) return self . _helper . update ( configuration , uri = uri , force = force , timeout = timeout )
Updates the Ethernet interconnect settings for the logical interconnect .
71
13
250,399
def update_internal_networks ( self , network_uri_list , force = False , timeout = - 1 ) : uri = "{}/internalNetworks" . format ( self . data [ "uri" ] ) return self . _helper . update ( network_uri_list , uri = uri , force = force , timeout = timeout )
Updates internal networks on the logical interconnect .
77
10