idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
58,400 | def with_updated_configuration ( self , options = None , attribute_options = None ) : new_cfg = self . __configurations [ - 1 ] . copy ( ) if not options is None : for o_name , o_value in iteritems_ ( options ) : new_cfg . set_option ( o_name , o_value ) if not attribute_options is None : for attr_name , ao_opts in iteritems_ ( attribute_options ) : for ao_name , ao_value in iteritems_ ( ao_opts ) : new_cfg . set_attribute_option ( attr_name , ao_name , ao_value ) return MappingConfigurationContext ( self , new_cfg ) | Returns a context in which this mapping is updated with the given options and attribute options . |
58,401 | def _attribute_iterator ( self , mapped_class , key ) : for attr in itervalues_ ( self . __get_attribute_map ( mapped_class , key , 0 ) ) : if self . is_pruning : do_ignore = attr . should_ignore ( key ) else : do_ignore = False if not do_ignore : yield attr | Returns an iterator over the attributes in this mapping for the given mapped class and attribute key . |
58,402 | def create_mapping ( self , mapped_class , configuration = None ) : cfg = self . __configuration . copy ( ) if not configuration is None : cfg . update ( configuration ) provided_ifcs = provided_by ( object . __new__ ( mapped_class ) ) if IMemberResource in provided_ifcs : base_data_element_class = self . member_data_element_base_class elif ICollectionResource in provided_ifcs : base_data_element_class = self . collection_data_element_base_class elif IResourceLink in provided_ifcs : base_data_element_class = self . linked_data_element_base_class else : raise ValueError ( 'Mapped class for data element class does not ' 'implement one of the required interfaces.' ) name = "%s%s" % ( mapped_class . __name__ , base_data_element_class . __name__ ) de_cls = type ( name , ( base_data_element_class , ) , { } ) mp = self . mapping_class ( self , mapped_class , de_cls , cfg ) de_cls . mapping = mp return mp | Creates a new mapping for the given mapped class and representer configuration . |
58,403 | def find_mapping ( self , mapped_class ) : if not self . __is_initialized : self . __is_initialized = True self . _initialize ( ) mapping = None for base_cls in mapped_class . __mro__ : try : mapping = self . __mappings [ base_cls ] except KeyError : continue else : break return mapping | Returns the mapping registered for the given mapped class or any of its base classes . Returns None if no mapping can be found . |
58,404 | def eachMethod ( decorator , methodFilter = lambda fName : True ) : if isinstance ( methodFilter , basestring ) : prefix = methodFilter methodFilter = lambda fName : fName . startswith ( prefix ) ismethod = lambda fn : inspect . ismethod ( fn ) or inspect . isfunction ( fn ) def innerDeco ( cls ) : assert inspect . isclass ( cls ) , "eachMethod is designed to be used only on classes" for fName , fn in inspect . getmembers ( cls ) : if methodFilter ( fName ) : if ismethod ( fn ) : if getargspec ( fn ) . args [ 0 ] not in [ 'cls' , 'self' ] : continue setattr ( cls , fName , decorator ( fn ) ) return cls return innerDeco | Class decorator that wraps every single method in its own method decorator |
58,405 | def _sibpath ( path , sibling ) : return os . path . join ( os . path . dirname ( os . path . abspath ( path ) ) , sibling ) | Return the path to a sibling of a file in the filesystem . |
58,406 | def cache ( cls , func ) : @ functools . wraps ( func ) def func_wrapper ( * args , ** kwargs ) : func_key = cls . get_key ( func ) val_cache = cls . get_cache ( func_key ) lock = cls . get_cache_lock ( func_key ) return cls . _get_value_from_cache ( func , val_cache , lock , * args , ** kwargs ) return func_wrapper | Global cache decorator |
58,407 | def instance_cache ( cls , func ) : @ functools . wraps ( func ) def func_wrapper ( * args , ** kwargs ) : if not args : raise ValueError ( '`self` is not available.' ) else : the_self = args [ 0 ] func_key = cls . get_key ( func ) val_cache = cls . get_self_cache ( the_self , func_key ) lock = cls . get_self_cache_lock ( the_self , func_key ) return cls . _get_value_from_cache ( func , val_cache , lock , * args , ** kwargs ) return func_wrapper | Save the cache to self |
58,408 | def clear_instance_cache ( cls , func ) : @ functools . wraps ( func ) def func_wrapper ( * args , ** kwargs ) : if not args : raise ValueError ( '`self` is not available.' ) else : the_self = args [ 0 ] cls . clear_self_cache ( the_self ) return func ( * args , ** kwargs ) return func_wrapper | clear the instance cache |
58,409 | def persisted ( cls , seconds = 0 , minutes = 0 , hours = 0 , days = 0 , weeks = 0 ) : days += weeks * 7 hours += days * 24 minutes += hours * 60 seconds += minutes * 60 if seconds == 0 : seconds = 24 * 60 * 60 def get_persisted_file ( hash_number ) : folder = cls . get_persist_folder ( ) if not os . path . exists ( folder ) : os . makedirs ( folder ) return os . path . join ( folder , '{}.pickle' . format ( hash_number ) ) def is_expired ( filename ) : if os . path . exists ( filename ) : file_age = cls . get_file_age ( filename ) if file_age > seconds : log . debug ( 'persisted cache expired: {}' . format ( filename ) ) ret = True else : ret = False else : ret = True return ret def decorator ( func ) : def func_wrapper ( * args , ** kwargs ) : def _key_gen ( ) : string = '{}-{}-{}-{}' . format ( func . __module__ , func . __name__ , args , kwargs . items ( ) ) return hashlib . sha256 ( string . encode ( 'utf-8' ) ) . hexdigest ( ) key = _key_gen ( ) persisted_file = get_persisted_file ( key ) if is_expired ( persisted_file ) : ret = func ( * args , ** kwargs ) with open ( persisted_file , 'wb' ) as f : pickle . dump ( ret , f ) else : with open ( persisted_file , 'rb' ) as f : ret = pickle . load ( f ) return ret return func_wrapper return decorator | Cache the return of the function for given time . |
58,410 | def getEvents ( self , repo_user , repo_name , until_id = None ) : done = False page = 0 events = [ ] while not done : new_events = yield self . api . makeRequest ( [ 'repos' , repo_user , repo_name , 'events' ] , page ) if new_events : for event in new_events : if event [ 'id' ] == until_id : done = True break events . append ( event ) else : done = True page += 1 defer . returnValue ( events ) | Get all repository events following paging until the end or until UNTIL_ID is seen . Returns a Deferred . |
58,411 | def from_project_path ( cls , path ) : path = vistir . compat . Path ( path ) if path . name == 'Pipfile' : pipfile_path = path path = path . parent else : pipfile_path = path / 'Pipfile' pipfile_location = cls . normalize_path ( pipfile_path ) venv_path = path / '.venv' if venv_path . exists ( ) : if not venv_path . is_dir ( ) : possible_path = vistir . compat . Path ( venv_path . read_text ( ) . strip ( ) ) if possible_path . exists ( ) : return cls ( possible_path . as_posix ( ) ) else : if venv_path . joinpath ( 'lib' ) . exists ( ) : return cls ( venv_path . as_posix ( ) ) sanitized = re . sub ( r'[ $`!*@"\\\r\n\t]' , "_" , path . name ) [ 0 : 42 ] hash_ = hashlib . sha256 ( pipfile_location . encode ( ) ) . digest ( ) [ : 6 ] encoded_hash = base64 . urlsafe_b64encode ( hash_ ) . decode ( ) hash_fragment = encoded_hash [ : 8 ] venv_name = "{0}-{1}" . format ( sanitized , hash_fragment ) return cls ( cls . get_workon_home ( ) . joinpath ( venv_name ) . as_posix ( ) ) | Utility for finding a virtualenv location based on a project path |
58,412 | def get_setup_install_args ( self , pkgname , setup_py , develop = False ) : headers = self . base_paths [ "headers" ] headers = headers / "python{0}" . format ( self . python_version ) / pkgname install_arg = "install" if not develop else "develop" return [ self . python , "-u" , "-c" , SETUPTOOLS_SHIM % setup_py , install_arg , "--single-version-externally-managed" , "--install-headers={0}" . format ( self . base_paths [ "headers" ] ) , "--install-purelib={0}" . format ( self . base_paths [ "purelib" ] ) , "--install-platlib={0}" . format ( self . base_paths [ "platlib" ] ) , "--install-scripts={0}" . format ( self . base_paths [ "scripts" ] ) , "--install-data={0}" . format ( self . base_paths [ "data" ] ) , ] | Get setup . py install args for installing the supplied package in the virtualenv |
58,413 | def setuptools_install ( self , chdir_to , pkg_name , setup_py_path = None , editable = False ) : install_options = [ "--prefix={0}" . format ( self . prefix . as_posix ( ) ) , ] with vistir . contextmanagers . cd ( chdir_to ) : c = self . run ( self . get_setup_install_args ( pkg_name , setup_py_path , develop = editable ) + install_options , cwd = chdir_to ) return c . returncode | Install an sdist or an editable package into the virtualenv |
58,414 | def install ( self , req , editable = False , sources = [ ] ) : try : packagebuilder = self . safe_import ( "packagebuilder" ) except ImportError : packagebuilder = None with self . activated ( include_extras = False ) : if not packagebuilder : return 2 ireq = req . as_ireq ( ) sources = self . filter_sources ( req , sources ) cache_dir = os . environ . get ( 'PASSA_CACHE_DIR' , os . environ . get ( 'PIPENV_CACHE_DIR' , vistir . path . create_tracked_tempdir ( prefix = "passabuild" ) ) ) built = packagebuilder . build . build ( ireq , sources , cache_dir ) if isinstance ( built , distlib . wheel . Wheel ) : maker = distlib . scripts . ScriptMaker ( None , None ) built . install ( self . paths , maker ) else : path = vistir . compat . Path ( built . path ) cd_path = path . parent setup_py = cd_path . joinpath ( "setup.py" ) return self . setuptools_install ( cd_path . as_posix ( ) , req . name , setup_py . as_posix ( ) , editable = req . editable ) return 0 | Install a package into the virtualenv |
58,415 | def activated ( self , include_extras = True , extra_dists = [ ] ) : original_path = sys . path original_prefix = sys . prefix original_user_base = os . environ . get ( "PYTHONUSERBASE" , None ) original_venv = os . environ . get ( "VIRTUAL_ENV" , None ) parent_path = vistir . compat . Path ( __file__ ) . absolute ( ) . parent . parent . as_posix ( ) prefix = self . prefix . as_posix ( ) with vistir . contextmanagers . temp_environ ( ) , vistir . contextmanagers . temp_path ( ) : os . environ [ "PATH" ] = os . pathsep . join ( [ vistir . compat . fs_str ( self . scripts_dir ) , vistir . compat . fs_str ( self . prefix . as_posix ( ) ) , os . environ . get ( "PATH" , "" ) ] ) os . environ [ "PYTHONIOENCODING" ] = vistir . compat . fs_str ( "utf-8" ) os . environ [ "PYTHONDONTWRITEBYTECODE" ] = vistir . compat . fs_str ( "1" ) os . environ [ "PATH" ] = self . base_paths [ "PATH" ] os . environ [ "PYTHONPATH" ] = self . base_paths [ "PYTHONPATH" ] if self . is_venv : os . environ [ "VIRTUAL_ENV" ] = vistir . compat . fs_str ( prefix ) sys . path = self . sys_path sys . prefix = self . sys_prefix site . addsitedir ( self . base_paths [ "purelib" ] ) if include_extras : site . addsitedir ( parent_path ) extra_dists = list ( self . extra_dists ) + extra_dists for extra_dist in extra_dists : if extra_dist not in self . get_working_set ( ) : extra_dist . activate ( self . sys_path ) sys . modules [ "recursive_monkey_patch" ] = self . recursive_monkey_patch try : yield finally : del os . environ [ "VIRTUAL_ENV" ] if original_user_base : os . environ [ "PYTHONUSERBASE" ] = original_user_base if original_venv : os . environ [ "VIRTUAL_ENV" ] = original_venv sys . path = original_path sys . prefix = original_prefix six . moves . reload_module ( pkg_resources ) | A context manager which activates the virtualenv . |
58,416 | def get_monkeypatched_pathset ( self ) : from pip_shims . shims import InstallRequirement uninstall_path = InstallRequirement . __module__ . replace ( "req_install" , "req_uninstall" ) req_uninstall = self . safe_import ( uninstall_path ) self . recursive_monkey_patch . monkey_patch ( PatchedUninstaller , req_uninstall . UninstallPathSet ) return req_uninstall . UninstallPathSet | Returns a monkeypatched UninstallPathset for using to uninstall packages from the virtualenv |
58,417 | def uninstall ( self , pkgname , * args , ** kwargs ) : auto_confirm = kwargs . pop ( "auto_confirm" , True ) verbose = kwargs . pop ( "verbose" , False ) with self . activated ( ) : pathset_base = self . get_monkeypatched_pathset ( ) dist = next ( iter ( filter ( lambda d : d . project_name == pkgname , self . get_working_set ( ) ) ) , None ) pathset = pathset_base . from_dist ( dist ) if pathset is not None : pathset . remove ( auto_confirm = auto_confirm , verbose = verbose ) try : yield pathset except Exception as e : if pathset is not None : pathset . rollback ( ) else : if pathset is not None : pathset . commit ( ) if pathset is None : return | A context manager which allows uninstallation of packages from the virtualenv |
58,418 | def getRootNode ( nodes ) : max = 0 root = None for i in nodes : if len ( i . children ) > max : max = len ( i . children ) root = i return root | Return the node with the most children |
58,419 | def getNextNode ( nodes , usednodes , parent ) : for e in edges : if e . source == parent : if e . target in usednodes : x = e . target break elif e . target == parent : if e . source in usednoes : x = e . source break return x | Get next node in a breadth - first traversal of nodes that have not been used yet |
58,420 | def calcPosition ( self , parent_circle ) : if r not in self : raise AttributeError ( "radius must be calculated before position." ) if theta not in self : raise AttributeError ( "theta must be set before position can be calculated." ) x_offset = math . cos ( t_radians ) * ( parent_circle . r + self . r ) y_offset = math . sin ( t_radians ) * ( parent_circle . r + self . r ) self . x = parent_circle . x + x_offset self . y = parent_circle . y + y_offset | Position the circle tangent to the parent circle with the line connecting the centers of the two circles meeting the x axis at angle theta . |
58,421 | def upload_progress ( request ) : if 'X-Progress-ID' in request . GET : progress_id = request . GET [ 'X-Progress-ID' ] elif 'X-Progress-ID' in request . META : progress_id = request . META [ 'X-Progress-ID' ] if progress_id : cache_key = "%s_%s" % ( request . META [ 'REMOTE_ADDR' ] , progress_id ) data = cache . get ( cache_key ) return HttpResponse ( simplejson . dumps ( data ) ) | Used by Ajax calls |
58,422 | def pre_save ( self , model_instance , add ) : value = super ( UserField , self ) . pre_save ( model_instance , add ) if not value and not add : value = self . get_os_username ( ) setattr ( model_instance , self . attname , value ) return value return value | Updates username created on ADD only . |
58,423 | def sys_toolbox_dir ( ) : return os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , 'esri' , 'toolboxes' ) | Returns this site - package esri toolbox directory . |
58,424 | def appdata_roaming_dir ( ) : install = arcpy . GetInstallInfo ( 'desktop' ) app_data = arcpy . GetSystemEnvironment ( "APPDATA" ) product_dir = '' . join ( ( install [ 'ProductName' ] , major_version ( ) ) ) return os . path . join ( app_data , 'ESRI' , product_dir ) | Returns the roaming AppData directory for the installed ArcGIS Desktop . |
58,425 | def add_route ( self , handler , uri , methods = frozenset ( { 'GET' } ) , host = None , strict_slashes = False ) : stream = False if hasattr ( handler , 'view_class' ) : http_methods = ( 'GET' , 'POST' , 'PUT' , 'HEAD' , 'OPTIONS' , 'PATCH' , 'DELETE' ) methods = set ( ) for method in http_methods : _handler = getattr ( handler . view_class , method . lower ( ) , None ) if _handler : methods . add ( method ) if hasattr ( _handler , 'is_stream' ) : stream = True if isinstance ( handler , self . composition_view_class ) : methods = handler . handlers . keys ( ) for _handler in handler . handlers . values ( ) : if hasattr ( _handler , 'is_stream' ) : stream = True break self . route ( uri = uri , methods = methods , host = host , strict_slashes = strict_slashes , stream = stream ) ( handler ) return handler | A helper method to register class instance or functions as a handler to the application url routes . |
58,426 | def middleware ( self , middleware_or_request ) : def register_middleware ( middleware , attach_to = 'request' ) : if attach_to == 'request' : self . request_middleware . append ( middleware ) if attach_to == 'response' : self . response_middleware . appendleft ( middleware ) return middleware if callable ( middleware_or_request ) : return register_middleware ( middleware_or_request ) else : return partial ( register_middleware , attach_to = middleware_or_request ) | Decorate and register middleware to be called before a request . Can either be called as |
58,427 | def static ( self , uri , file_or_directory , pattern = r'/?.+' , use_modified_since = True , use_content_range = False ) : static_register ( self , uri , file_or_directory , pattern , use_modified_since , use_content_range ) | Register a root to serve files from . The input can either be a file or a directory . See |
58,428 | def url_for ( self , view_name : str , ** kwargs ) : uri , route = self . router . find_route_by_view_name ( view_name ) if not uri or not route : raise URLBuildError ( 'Endpoint with name `{}` was not found' . format ( view_name ) ) if uri != '/' and uri . endswith ( '/' ) : uri = uri [ : - 1 ] out = uri matched_params = re . findall ( self . router . parameter_pattern , uri ) kwargs . pop ( '_method' , None ) anchor = kwargs . pop ( '_anchor' , '' ) external = kwargs . pop ( '_external' , False ) scheme = kwargs . pop ( '_scheme' , '' ) if scheme and not external : raise ValueError ( 'When specifying _scheme, _external must be True' ) netloc = kwargs . pop ( '_server' , None ) if netloc is None and external : netloc = self . config . get ( 'SERVER_NAME' , '' ) for match in matched_params : name , _type , pattern = self . router . parse_parameter_string ( match ) specific_pattern = '^{}$' . format ( pattern ) supplied_param = None if kwargs . get ( name ) : supplied_param = kwargs . get ( name ) del kwargs [ name ] else : raise URLBuildError ( 'Required parameter `{}` was not passed to url_for' . format ( name ) ) supplied_param = str ( supplied_param ) passes_pattern = re . match ( specific_pattern , supplied_param ) if not passes_pattern : if _type != str : msg = ( 'Value "{}" for parameter `{}` does not ' 'match pattern for type `{}`: {}' . format ( supplied_param , name , _type . __name__ , pattern ) ) else : msg = ( 'Value "{}" for parameter `{}` ' 'does not satisfy pattern {}' . format ( supplied_param , name , pattern ) ) raise URLBuildError ( msg ) replacement_regex = '(<{}.*?>)' . format ( name ) out = re . sub ( replacement_regex , supplied_param , out ) query_string = urlencode ( kwargs , doseq = True ) if kwargs else '' out = urlunparse ( ( scheme , netloc , out , '' , query_string , anchor ) ) return out | Build a URL based on a view name and the values provided . |
58,429 | def i2osp ( self , long_integer , block_size ) : 'Convert a long integer into an octet string.' hex_string = '%X' % long_integer if len ( hex_string ) > 2 * block_size : raise ValueError ( 'integer %i too large to encode in %i octets' % ( long_integer , block_size ) ) return a2b_hex ( hex_string . zfill ( 2 * block_size ) ) | Convert a long integer into an octet string . |
58,430 | def random_output ( self , max = 100 ) : output = [ ] item1 = item2 = MarkovChain . START for i in range ( max - 3 ) : item3 = self [ ( item1 , item2 ) ] . roll ( ) if item3 is MarkovChain . END : break output . append ( item3 ) item1 = item2 item2 = item3 return output | Generate a list of elements from the markov chain . The max value is in place in order to prevent excessive iteration . |
58,431 | def start ( self ) : if self . _isRunning : return if self . _cease . is_set ( ) : self . _cease . clear ( ) class Runner ( threading . Thread ) : @ classmethod def run ( cls ) : nextRunAt = cls . setNextRun ( ) while not self . _cease . is_set ( ) : if datetime . now ( ) >= nextRunAt : self . _run ( ) nextRunAt = cls . setNextRun ( ) @ classmethod def setNextRun ( cls ) : return self . _interval . nextRunAt ( ) runner = Runner ( ) runner . setDaemon ( True ) runner . start ( ) self . _isRunning = True | Start the periodic runner |
58,432 | def useThis ( self , * args , ** kwargs ) : self . _callback = functools . partial ( self . _callback , * args , ** kwargs ) | Change parameter of the callback function . |
58,433 | def stop ( self ) : self . _cease . set ( ) time . sleep ( 0.1 ) self . _isRunning = False | Stop the periodic runner |
58,434 | def condition ( self ) -> bool : jwt = JWT ( ) if jwt . verify_http_auth_token ( ) : if not current_app . config [ 'AUTH' ] [ 'FAST_SESSIONS' ] : session = SessionModel . where_session_id ( jwt . data [ 'session_id' ] ) if session is None : return False Session . set_current_session ( jwt . data [ 'session_id' ] ) return True return False | check JWT then check session for validity |
58,435 | def render_hidden ( name , value ) : if isinstance ( value , list ) : return MultipleHiddenInput ( ) . render ( name , value ) return HiddenInput ( ) . render ( name , value ) | render as hidden widget |
58,436 | def next_task ( self , item , raise_exceptions = None , ** kwargs ) : filename = os . path . basename ( item ) batch = self . get_batch ( filename ) tx_deserializer = self . tx_deserializer_cls ( allow_self = self . allow_self , override_role = self . override_role ) try : tx_deserializer . deserialize_transactions ( transactions = batch . saved_transactions ) except ( DeserializationError , TransactionDeserializerError ) as e : raise TransactionsFileQueueError ( e ) from e else : batch . close ( ) self . archive ( filename ) | Deserializes all transactions for this batch and archives the file . |
58,437 | def get_batch ( self , filename = None ) : try : history = self . history_model . objects . get ( filename = filename ) except self . history_model . DoesNotExist as e : raise TransactionsFileQueueError ( f"Batch history not found for '{filename}'." ) from e if history . consumed : raise TransactionsFileQueueError ( f"Batch closed for '{filename}'. Got consumed=True" ) batch = self . batch_cls ( ) batch . batch_id = history . batch_id batch . filename = history . filename return batch | Returns a batch instance given the filename . |
58,438 | def get_items ( self , html ) : captcha_patterns = [ "https://www.google.com/recaptcha/api.js" , "I'm not a robot" ] for captcha_pattern in captcha_patterns : if captcha_pattern in html : raise exc . CaptchaError ( "Found %r in html!" % captcha_pattern ) data = list ( ) soup = self . to_soup ( html ) div = soup . find ( "div" , class_ = "zsg-lg-1-2 zsg-sm-1-1" ) for li in div . find_all ( "li" ) : a = li . find_all ( "a" ) [ 0 ] href = a [ "href" ] name = a . text . strip ( ) data . append ( ( href , name ) ) return data | Get state county zipcode address code from lists page . |
58,439 | def get_time ( self , loc4d = None ) : if loc4d is None : raise ValueError ( "Location4D object can not be None" ) if self . pattern == self . PATTERN_CYCLE : c = SunCycles . cycles ( loc = loc4d ) if self . cycle == self . CYCLE_SUNRISE : r = c [ SunCycles . RISING ] elif self . cycle == self . CYCLE_SUNSET : r = c [ SunCycles . SETTING ] td = timedelta ( hours = self . time_delta ) if self . plus_or_minus == self . HOURS_PLUS : r = r + td elif self . plus_or_minus == self . HOURS_MINUS : r = r - td return r elif self . pattern == self . PATTERN_SPECIFICTIME : return self . _time . replace ( year = loc4d . time . year , month = loc4d . time . month , day = loc4d . time . day ) | Based on a Location4D object and this Diel object calculate the time at which this Diel migration is actually happening |
58,440 | def move ( self , particle , u , v , w , modelTimestep , ** kwargs ) : if particle . settled : return { 'u' : 0 , 'v' : 0 , 'w' : 0 } if particle . halted : return { 'u' : 0 , 'v' : 0 , 'w' : 0 } vertical_potential = w * modelTimestep if particle . location . depth < self . max_depth : logger . debug ( "DIEL: %s - Moving UP to desired depth from %f" % ( self . logstring ( ) , particle . location . depth ) ) overshoot_distance = abs ( particle . location . depth - self . min_depth ) if overshoot_distance < abs ( vertical_potential ) : halfway_distance = abs ( ( self . max_depth - self . min_depth ) / 2 ) w = ( ( overshoot_distance - halfway_distance ) / modelTimestep ) return { 'u' : u , 'v' : v , 'w' : w } if particle . location . depth > self . min_depth : logger . debug ( "DIEL: %s - Moving DOWN to desired depth from %f" % ( self . logstring ( ) , particle . location . depth ) ) overshoot_distance = abs ( particle . location . depth - self . max_depth ) if overshoot_distance < abs ( vertical_potential ) : halfway_distance = abs ( ( self . max_depth - self . min_depth ) / 2 ) w = ( ( overshoot_distance - halfway_distance ) / modelTimestep ) return { 'u' : u , 'v' : v , 'w' : - w } return { 'u' : u , 'v' : v , 'w' : 0 } | This only works if min is less than max . No checks are done here so it should be done before calling this function . |
58,441 | def make_relationship_aggregate ( self , relationship ) : if not self . _session . IS_MANAGING_BACKREFERENCES : relationship . direction &= ~ RELATIONSHIP_DIRECTIONS . REVERSE return RelationshipAggregate ( self , relationship ) | Returns a new relationship aggregate for the given relationship . |
58,442 | def register_new ( self , entity_class , entity ) : EntityState . manage ( entity , self ) EntityState . get_state ( entity ) . status = ENTITY_STATUS . NEW self . __entity_set_map [ entity_class ] . add ( entity ) | Registers the given entity for the given class as NEW . |
58,443 | def register_clean ( self , entity_class , entity ) : EntityState . manage ( entity , self ) EntityState . get_state ( entity ) . status = ENTITY_STATUS . CLEAN self . __entity_set_map [ entity_class ] . add ( entity ) | Registers the given entity for the given class as CLEAN . |
58,444 | def register_deleted ( self , entity_class , entity ) : EntityState . manage ( entity , self ) EntityState . get_state ( entity ) . status = ENTITY_STATUS . DELETED self . __entity_set_map [ entity_class ] . add ( entity ) | Registers the given entity for the given class as DELETED . |
58,445 | def unregister ( self , entity_class , entity ) : EntityState . release ( entity , self ) self . __entity_set_map [ entity_class ] . remove ( entity ) | Unregisters the given entity for the given class and discards its state information . |
58,446 | def is_marked_new ( self , entity ) : try : result = EntityState . get_state ( entity ) . status == ENTITY_STATUS . NEW except ValueError : result = False return result | Checks if the given entity is marked with status NEW . Returns False if the entity has no state information . |
58,447 | def is_marked_deleted ( self , entity ) : try : result = EntityState . get_state ( entity ) . status == ENTITY_STATUS . DELETED except ValueError : result = False return result | Checks if the given entity is marked with status DELETED . Returns False if the entity has no state information . |
58,448 | def mark_clean ( self , entity ) : state = EntityState . get_state ( entity ) state . status = ENTITY_STATUS . CLEAN state . is_persisted = True | Marks the given entity as CLEAN . |
58,449 | def iterator ( self ) : for ent_cls in list ( self . __entity_set_map . keys ( ) ) : for ent in self . __entity_set_map [ ent_cls ] : yield EntityState . get_state ( ent ) | Returns an iterator over all entity states held by this Unit Of Work . |
58,450 | def file_save ( self , name , filename = None , folder = "" , keep_ext = True ) -> bool : if name in self . files : file_object = self . files [ name ] clean_filename = secure_filename ( file_object . filename ) if filename is not None and keep_ext : clean_filename = filename + ".%s" % ( clean_filename . rsplit ( '.' , 1 ) [ 1 ] . lower ( ) ) elif filename is not None and not keep_ext : clean_filename = filename file_object . save ( os . path . join ( current_app . config [ 'UPLOADS' ] [ 'FOLDER' ] , folder , clean_filename ) ) return None | Easy save of a file |
58,451 | def parse ( self , fail_callback = None ) : for field in self . field_arguments : self . values [ field [ 'name' ] ] = self . __get_value ( field [ 'name' ] ) if self . values [ field [ 'name' ] ] is None and field [ 'required' ] : if fail_callback is not None : fail_callback ( ) self . __invalid_request ( field [ 'error' ] ) for file in self . file_arguments : self . files [ file [ 'name' ] ] = self . __get_file ( file ) if self . files [ file [ 'name' ] ] is None and file [ 'required' ] : if fail_callback is not None : fail_callback ( ) self . __invalid_request ( file [ 'error' ] ) | Parse text fields and file fields for values and files |
58,452 | def __get_value ( self , field_name ) : value = request . values . get ( field_name ) if value is None : if self . json_form_data is None : value = None elif field_name in self . json_form_data : value = self . json_form_data [ field_name ] return value | Get request Json value by field name |
58,453 | def __get_file ( self , file ) : file_object = None if file [ 'name' ] in request . files : file_object = request . files [ file [ 'name' ] ] clean_filename = secure_filename ( file_object . filename ) if clean_filename == '' : return file_object if file_object and self . __allowed_extension ( clean_filename , file [ 'extensions' ] ) : return file_object elif file [ 'name' ] not in request . files and file [ 'required' ] : return file_object return file_object | Get request file and do a security check |
58,454 | def __allowed_extension ( self , filename , extensions ) : allowed_extensions = current_app . config [ 'UPLOADS' ] [ 'EXTENSIONS' ] if extensions is not None : allowed_extensions = extensions return '.' in filename and filename . rsplit ( '.' , 1 ) [ 1 ] . lower ( ) in allowed_extensions | Check allowed file extensions |
58,455 | def __invalid_request ( self , error ) : error = { 'error' : { 'message' : error } } abort ( JsonResponse ( status_code = 400 , data = error ) ) | Error response on failure |
58,456 | def get_field ( self , offset , length , format ) : return struct . unpack ( format , self . data [ offset : offset + length ] ) [ 0 ] | Returns unpacked Python struct array . |
58,457 | def export ( self , filename , offset = 0 , length = None ) : self . __validate_offset ( filename = filename , offset = offset , length = length ) with open ( filename , 'w' ) as f : if length is None : length = len ( self . data ) - offset if offset > 0 : output = self . data [ offset : length ] else : output = self . data [ : length ] f . write ( output ) | Exports byte array to specified destination |
58,458 | def tmpdir ( ) : target = None try : with _tmpdir_extant ( ) as target : yield target finally : if target is not None : shutil . rmtree ( target , ignore_errors = True ) | Create a tempdir context for the cwd and remove it after . |
58,459 | def run ( command , verbose = False ) : def do_nothing ( * args , ** kwargs ) : return None v_print = print if verbose else do_nothing p = subprocess . Popen ( command , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True , ) v_print ( "run:" , command ) def log_and_yield ( line ) : if six . PY2 : if isinstance ( line , str ) : line = line . decode ( 'utf8' , 'replace' ) v_print ( line ) return line output = '' . join ( map ( log_and_yield , p . stdout ) ) status_code = p . wait ( ) return CommandResult ( command , output , status_code ) | Run a shell command . Capture the stdout and stderr as a single stream . Capture the status code . |
58,460 | def get_lxc_version ( ) : runner = functools . partial ( subprocess . check_output , stderr = subprocess . STDOUT , universal_newlines = True , ) try : result = runner ( [ 'lxc-version' ] ) . rstrip ( ) return parse_version ( result . replace ( "lxc version: " , "" ) ) except ( OSError , subprocess . CalledProcessError ) : pass return parse_version ( runner ( [ 'lxc-start' , '--version' ] ) . rstrip ( ) ) | Asks the current host what version of LXC it has . Returns it as a string . If LXC is not installed raises subprocess . CalledProcessError |
58,461 | def get_qpimage ( self , idx = 0 ) : if self . _bgdata : qpi = super ( SingleHdf5Qpimage , self ) . get_qpimage ( ) else : qpi = qpimage . QPImage ( h5file = self . path , h5mode = "r" , h5dtype = self . as_type , ) . copy ( ) for key in self . meta_data : qpi [ key ] = self . meta_data [ key ] qpi [ "identifier" ] = self . get_identifier ( idx ) return qpi | Return background - corrected QPImage |
58,462 | def simulate ( s0 , transmat , steps = 1 ) : if steps == 1 : return np . dot ( s0 , transmat ) out = np . zeros ( shape = ( steps + 1 , len ( s0 ) ) , order = 'C' ) out [ 0 , : ] = s0 for i in range ( 1 , steps + 1 ) : out [ i , : ] = np . dot ( out [ i - 1 , : ] , transmat ) return out | Simulate the next state |
58,463 | def verify ( path ) : path = pathlib . Path ( path ) valid = False if path . suffix == ".npy" : try : nf = np . load ( str ( path ) , mmap_mode = "r" , allow_pickle = False ) except ( OSError , ValueError , IsADirectoryError ) : pass else : if len ( nf . shape ) == 2 : valid = True return valid | Verify that path has a supported numpy file format |
58,464 | def _get_stem ( self ) : filename = os . path . basename ( self . src_path ) stem , ext = os . path . splitext ( filename ) return "index" if stem in ( "index" , "README" , "__init__" ) else stem | Return the name of the file without it s extension . |
58,465 | def type_check ( thetype , data , bindings = None ) : if not bindings : bindings = Bindings ( ) if isinstance ( thetype , core . RecordType ) : for name , child in zip ( thetype . child_names , thetype . child_types ) : value = data [ name ] type_check ( child , value , bindings ) elif isinstance ( thetype , core . TupleType ) : assert isinstance ( data , tuple ) assert len ( data ) == len ( thetype . child_types ) for value , child_type in zip ( data , thetype . child_types ) : type_check ( child_type , value , bindings ) elif isinstance ( thetype , core . UnionType ) : assert isinstance ( thetype , dict ) children = [ ( name , child ) for name , child in zip ( thetype . child_names , thetype . child_types ) if name in data ] assert len ( fields ) == 1 , "0 or more than 1 entry in Union" child_name , child_type = children [ 0 ] type_check ( child_type , data [ child_name ] , bindings ) elif isinstance ( thetype , core . TypeApp ) : bindings . push ( ) for k , v in thetype . param_values . items ( ) : bindings [ k ] = v type_check ( thetype . root_type , data , bindings ) bindings . pop ( ) elif isinstance ( thetype , core . TypeVar ) : bound_type = bindings [ thetype . name ] if bound_type is None : raise errors . ValidationError ( "TypeVar(%s) is not bound to a type." % thetype . name ) type_check ( bound_type , data , bindings ) elif isinstance ( thetype , core . NativeType ) : if thetype . args and thetype . mapper_functor : def type_check_functor ( * values ) : for arg , value in zip ( thetype . args , values ) : bound_type = bindings [ arg ] if bound_type is None : raise errors . ValidationError ( "Arg(%s) is not bound to a type." % arg ) type_check ( bound_type , value ) thetype . mapper_functor ( type_check_functor , data ) if thetype . validator : thetype . validator ( thetype , data , bindings ) | Checks that a given bit of data conforms to the type provided |
58,466 | def parse_setup ( filepath ) : setup_kwargs = { } def setup_interceptor ( ** kwargs ) : setup_kwargs . update ( kwargs ) import setuptools setuptools_setup = setuptools . setup setuptools . setup = setup_interceptor with open ( filepath , 'r' ) as f : code = compile ( f . read ( ) , '' , 'exec' ) setup = ModuleType ( 'setup' ) exec ( code , setup . __dict__ ) setuptools . setup = setuptools_setup return setup_kwargs | Get the kwargs from the setup function in setup . py |
58,467 | def get_console_scripts ( setup_data ) : if 'entry_points' not in setup_data : return [ ] console_scripts = setup_data [ 'entry_points' ] . get ( 'console_scripts' , [ ] ) return [ script . split ( '=' ) [ 0 ] . strip ( ) for script in console_scripts ] | Parse and return a list of console_scripts from setup_data |
58,468 | def install_programmer ( programmer_id , programmer_options , replace_existing = False ) : doaction = 0 if programmer_id in programmers ( ) . keys ( ) : log . debug ( 'programmer already exists: %s' , programmer_id ) if replace_existing : log . debug ( 'remove programmer: %s' , programmer_id ) remove_programmer ( programmer_id ) doaction = 1 else : doaction = 1 if doaction : lines = bunch2properties ( programmer_id , programmer_options ) programmers_txt ( ) . write_lines ( [ '' ] + lines , append = 1 ) | install programmer in programmers . txt . |
58,469 | def schedule ( self , job , when ) : pjob = pickle . dumps ( job ) self . _redis . zadd ( 'ss:scheduled' , when , pjob ) | Schedule job to run at when nanoseconds since the UNIX epoch . |
58,470 | def schedule_in ( self , job , timedelta ) : now = long ( self . _now ( ) * 1e6 ) when = now + timedelta . total_seconds ( ) * 1e6 self . schedule ( job , when ) | Schedule job to run at datetime . timedelta from now . |
58,471 | def schedule_now ( self , job ) : now = long ( self . _now ( ) * 1e6 ) self . schedule ( job , now ) | Schedule job to run as soon as possible . |
58,472 | def _get_aria_autocomplete ( self , field ) : tag_name = field . get_tag_name ( ) input_type = None if field . has_attribute ( 'type' ) : input_type = field . get_attribute ( 'type' ) . lower ( ) if ( ( tag_name == 'TEXTAREA' ) or ( ( tag_name == 'INPUT' ) and ( not ( ( input_type == 'button' ) or ( input_type == 'submit' ) or ( input_type == 'reset' ) or ( input_type == 'image' ) or ( input_type == 'file' ) or ( input_type == 'checkbox' ) or ( input_type == 'radio' ) or ( input_type == 'hidden' ) ) ) ) ) : value = None if field . has_attribute ( 'autocomplete' ) : value = field . get_attribute ( 'autocomplete' ) . lower ( ) else : form = self . parser . find ( field ) . find_ancestors ( 'form' ) . first_result ( ) if ( form is None ) and ( field . has_attribute ( 'form' ) ) : form = self . parser . find ( '#' + field . get_attribute ( 'form' ) ) . first_result ( ) if ( form is not None ) and ( form . has_attribute ( 'autocomplete' ) ) : value = form . get_attribute ( 'autocomplete' ) . lower ( ) if value == 'on' : return 'both' elif ( ( field . has_attribute ( 'list' ) ) and ( self . parser . find ( 'datalist[id="' + field . get_attribute ( 'list' ) + '"]' ) . first_result ( ) is not None ) ) : return 'list' elif value == 'off' : return 'none' return None | Returns the appropriate value for attribute aria - autocomplete of field . |
58,473 | def _validate ( self , field , list_attribute ) : if not self . scripts_added : self . _generate_validation_scripts ( ) self . id_generator . generate_id ( field ) self . script_list_fields_with_validation . append_text ( 'hatemileValidationList.' + list_attribute + '.push("' + field . get_attribute ( 'id' ) + '");' ) | Validate the field when its value change . |
58,474 | def remove ( item ) : if os . path . isdir ( item ) : shutil . rmtree ( item ) else : os . remove ( item ) | Delete item whether it s a file a folder or a folder full of other files and folders . |
58,475 | def get_slugignores ( root , fname = '.slugignore' ) : try : with open ( os . path . join ( root , fname ) ) as f : return [ l . rstrip ( '\n' ) for l in f ] except IOError : return [ ] | Given a root path read any . slugignore file inside and return a list of patterns that should be removed prior to slug compilation . |
58,476 | def clean_slug_dir ( root ) : if not root . endswith ( '/' ) : root += '/' for pattern in get_slugignores ( root ) : print ( "pattern" , pattern ) remove_pattern ( root , pattern ) | Given a path delete anything specified in . slugignore . |
58,477 | def export ( self , folder_path , format = None ) : if format is None : raise ValueError ( "Must export to a specific format, no format specified." ) format = format . lower ( ) if format == "trackline" or format [ - 4 : ] == "trkl" : ex . Trackline . export ( folder = folder_path , particles = self . particles , datetimes = self . datetimes ) elif format == "shape" or format == "shapefile" or format [ - 3 : ] == "shp" : ex . GDALShapefile . export ( folder = folder_path , particles = self . particles , datetimes = self . datetimes ) elif format == "netcdf" or format [ - 2 : ] == "nc" : ex . NetCDF . export ( folder = folder_path , particles = self . particles , datetimes = self . datetimes , summary = str ( self ) ) elif format == "pickle" or format [ - 3 : ] == "pkl" or format [ - 6 : ] == "pickle" : ex . Pickle . export ( folder = folder_path , particles = self . particles , datetimes = self . datetimes ) | General purpose export method gets file type from filepath extension |
58,478 | def _parse ( args ) : ordered = [ ] opt_full = dict ( ) opt_abbrev = dict ( ) args = args + [ '' ] i = 0 while i < len ( args ) - 1 : arg = args [ i ] arg_next = args [ i + 1 ] if arg . startswith ( '--' ) : if arg_next . startswith ( '-' ) : raise ValueError ( '{} lacks value' . format ( arg ) ) else : opt_full [ arg [ 2 : ] ] = arg_next i += 2 elif arg . startswith ( '-' ) : if arg_next . startswith ( '-' ) : raise ValueError ( '{} lacks value' . format ( arg ) ) else : opt_abbrev [ arg [ 1 : ] ] = arg_next i += 2 else : ordered . append ( arg ) i += 1 return ordered , opt_full , opt_abbrev | Parse passed arguments from shell . |
58,479 | def _construct_optional ( params ) : args = [ ] filtered = { key : arg . default for key , arg in params . items ( ) if arg . default != inspect . _empty } for key , default in filtered . items ( ) : arg = OptionalArg ( full = key , abbrev = key [ 0 ] . lower ( ) , default = default ) args . append ( arg ) args_full , args_abbrev = dict ( ) , dict ( ) known_count = defaultdict ( int ) for arg in args : args_full [ arg . full ] = arg if known_count [ arg . abbrev ] == 0 : args_abbrev [ arg . abbrev ] = arg elif known_count [ arg . abbrev ] == 1 : new_abbrev = arg . abbrev . upper ( ) args_full [ arg . full ] = OptionalArg ( full = arg . full , abbrev = new_abbrev , default = arg . default ) args_abbrev [ new_abbrev ] = args_full [ arg . full ] else : new_abbrev = arg . abbrev . upper ( ) + str ( known_count [ arg . abbrev ] ) args_full [ arg . full ] = OptionalArg ( full = arg . full , abbrev = new_abbrev , default = arg . default ) args_abbrev [ new_abbrev ] = args_full [ arg . full ] known_count [ arg . abbrev ] += 1 return args_full , args_abbrev | Construct optional args key and abbreviated key from signature . |
58,480 | def _keyboard_access ( self , element ) : if not element . has_attribute ( 'tabindex' ) : tag = element . get_tag_name ( ) if ( tag == 'A' ) and ( not element . has_attribute ( 'href' ) ) : element . set_attribute ( 'tabindex' , '0' ) elif ( ( tag != 'A' ) and ( tag != 'INPUT' ) and ( tag != 'BUTTON' ) and ( tag != 'SELECT' ) and ( tag != 'TEXTAREA' ) ) : element . set_attribute ( 'tabindex' , '0' ) | Provide keyboard access for element if it not has . |
58,481 | def _add_event_in_element ( self , element , event ) : if not self . main_script_added : self . _generate_main_scripts ( ) if self . script_list is not None : self . id_generator . generate_id ( element ) self . script_list . append_text ( event + "Elements.push('" + element . get_attribute ( 'id' ) + "');" ) | Add a type of event in element . |
58,482 | def tee ( process , filter ) : lines = [ ] while True : line = process . stdout . readline ( ) if line : if sys . version_info [ 0 ] >= 3 : line = decode ( line ) stripped_line = line . rstrip ( ) if filter ( stripped_line ) : sys . stdout . write ( line ) lines . append ( stripped_line ) elif process . poll ( ) is not None : process . stdout . close ( ) break return lines | Read lines from process . stdout and echo them to sys . stdout . |
58,483 | def tee2 ( process , filter ) : while True : line = process . stderr . readline ( ) if line : if sys . version_info [ 0 ] >= 3 : line = decode ( line ) stripped_line = line . rstrip ( ) if filter ( stripped_line ) : sys . stderr . write ( line ) elif process . returncode is not None : process . stderr . close ( ) break | Read lines from process . stderr and echo them to sys . stderr . |
58,484 | def run ( args , echo = True , echo2 = True , shell = False , cwd = None , env = None ) : if not callable ( echo ) : echo = On ( ) if echo else Off ( ) if not callable ( echo2 ) : echo2 = On ( ) if echo2 else Off ( ) process = Popen ( args , stdout = PIPE , stderr = PIPE , shell = shell , cwd = cwd , env = env ) with background_thread ( tee2 , ( process , echo2 ) ) : lines = tee ( process , echo ) return process . returncode , lines | Run args and return a two - tuple of exit code and lines read . |
58,485 | def register_representer_class ( self , representer_class ) : if representer_class in self . __rpr_classes . values ( ) : raise ValueError ( 'The representer class "%s" has already been ' 'registered.' % representer_class ) self . __rpr_classes [ representer_class . content_type ] = representer_class if issubclass ( representer_class , MappingResourceRepresenter ) : mp_reg = representer_class . make_mapping_registry ( ) self . __mp_regs [ representer_class . content_type ] = mp_reg | Registers the given representer class with this registry using its MIME content type as the key . |
58,486 | def register ( self , resource_class , content_type , configuration = None ) : if not issubclass ( resource_class , Resource ) : raise ValueError ( 'Representers can only be registered for ' 'resource classes (got: %s).' % resource_class ) if not content_type in self . __rpr_classes : raise ValueError ( 'No representer class has been registered for ' 'content type "%s".' % content_type ) rpr_cls = self . __rpr_classes [ content_type ] self . __rpr_factories [ ( resource_class , content_type ) ] = rpr_cls . create_from_resource_class if issubclass ( rpr_cls , MappingResourceRepresenter ) : mp_reg = self . __mp_regs [ content_type ] mp = mp_reg . find_mapping ( resource_class ) if mp is None : new_mp = mp_reg . create_mapping ( resource_class , configuration ) elif not configuration is None : if resource_class is mp . mapped_class : mp . configuration . update ( configuration ) new_mp = mp else : new_mp = mp_reg . create_mapping ( resource_class , configuration = mp . configuration ) new_mp . configuration . update ( configuration ) elif not resource_class is mp . mapped_class : new_mp = mp_reg . create_mapping ( resource_class , configuration = mp . configuration ) else : new_mp = None if not new_mp is None : mp_reg . set_mapping ( new_mp ) | Registers a representer factory for the given combination of resource class and content type . |
58,487 | def create ( self , resource_class , content_type ) : rpr_fac = self . __find_representer_factory ( resource_class , content_type ) if rpr_fac is None : self . register ( resource_class , content_type ) rpr_fac = self . __find_representer_factory ( resource_class , content_type ) return rpr_fac ( resource_class ) | Creates a representer for the given combination of resource and content type . This will also find representer factories that were registered for a base class of the given resource . |
58,488 | def make_gpg_home ( appname , config_dir = None ) : assert is_valid_appname ( appname ) config_dir = get_config_dir ( config_dir ) path = os . path . join ( config_dir , "gpgkeys" , appname ) if not os . path . exists ( path ) : os . makedirs ( path , 0700 ) else : os . chmod ( path , 0700 ) return path | Make GPG keyring dir for a particular application . Return the path . |
58,489 | def get_gpg_home ( appname , config_dir = None ) : assert is_valid_appname ( appname ) config_dir = get_config_dir ( config_dir ) path = os . path . join ( config_dir , "gpgkeys" , appname ) return path | Get the GPG keyring directory for a particular application . Return the path . |
58,490 | def make_gpg_tmphome ( prefix = None , config_dir = None ) : if prefix is None : prefix = "tmp" config_dir = get_config_dir ( config_dir ) tmppath = os . path . join ( config_dir , "tmp" ) if not os . path . exists ( tmppath ) : os . makedirs ( tmppath , 0700 ) tmpdir = tempfile . mkdtemp ( prefix = ( "%s-" % prefix ) , dir = tmppath ) return tmpdir | Make a temporary directory to hold GPG keys that are not going to be stored to the application s keyring . |
58,491 | def gpg_stash_key ( appname , key_bin , config_dir = None , gpghome = None ) : assert is_valid_appname ( appname ) key_bin = str ( key_bin ) assert len ( key_bin ) > 0 if gpghome is None : config_dir = get_config_dir ( config_dir ) keydir = make_gpg_home ( appname , config_dir = config_dir ) else : keydir = gpghome gpg = gnupg . GPG ( homedir = keydir ) res = gpg . import_keys ( key_bin ) try : assert res . count == 1 , "Failed to store key (%s)" % res except AssertionError , e : log . exception ( e ) log . error ( "Failed to store key to %s" % keydir ) log . debug ( "res: %s" % res . __dict__ ) log . debug ( "(%s)\n%s" % ( len ( key_bin ) , key_bin ) ) return None return res . fingerprints [ 0 ] | Store a key locally to our app keyring . Does NOT put it into a blockchain ID Return the key ID on success Return None on error |
58,492 | def gpg_unstash_key ( appname , key_id , config_dir = None , gpghome = None ) : assert is_valid_appname ( appname ) if gpghome is None : config_dir = get_config_dir ( config_dir ) keydir = get_gpg_home ( appname , config_dir = config_dir ) else : keydir = gpghome gpg = gnupg . GPG ( homedir = keydir ) res = gpg . delete_keys ( [ key_id ] ) if res . status == 'Must delete secret key first' : res = gpg . delete_keys ( [ key_id ] , secret = True ) try : assert res . status == 'ok' , "Failed to delete key (%s)" % res except AssertionError , e : log . exception ( e ) log . error ( "Failed to delete key '%s'" % key_id ) log . debug ( "res: %s" % res . __dict__ ) return False return True | Remove a public key locally from our local app keyring Return True on success Return False on error |
58,493 | def gpg_download_key ( key_id , key_server , config_dir = None ) : config_dir = get_config_dir ( config_dir ) tmpdir = make_gpg_tmphome ( prefix = "download" , config_dir = config_dir ) gpg = gnupg . GPG ( homedir = tmpdir ) recvdat = gpg . recv_keys ( key_server , key_id ) fingerprint = None try : assert recvdat . count == 1 assert len ( recvdat . fingerprints ) == 1 fingerprint = recvdat . fingerprints [ 0 ] except AssertionError , e : log . exception ( e ) log . error ( "Failed to fetch key '%s' from '%s'" % ( key_id , key_server ) ) shutil . rmtree ( tmpdir ) return None keydat = gpg . export_keys ( [ fingerprint ] ) shutil . rmtree ( tmpdir ) return str ( keydat ) | Download a GPG key from a key server . Do not import it into any keyrings . Return the ASCII - armored key |
58,494 | def gpg_key_fingerprint ( key_data , config_dir = None ) : key_data = str ( key_data ) config_dir = get_config_dir ( config_dir ) tmpdir = make_gpg_tmphome ( prefix = "key_id-" , config_dir = config_dir ) gpg = gnupg . GPG ( homedir = tmpdir ) res = gpg . import_keys ( key_data ) try : assert res . count == 1 , "Failed to import key" assert len ( res . fingerprints ) == 1 , "Nonsensical GPG response: wrong number of fingerprints" fingerprint = res . fingerprints [ 0 ] shutil . rmtree ( tmpdir ) return fingerprint except AssertionError , e : log . exception ( e ) shutil . rmtree ( tmpdir ) return None | Get the key ID of a given serialized key Return the fingerprint on success Return None on error |
58,495 | def gpg_verify_key ( key_id , key_data , config_dir = None ) : key_data = str ( key_data ) config_dir = get_config_dir ( config_dir ) sanitized_key_id = "" . join ( key_id . upper ( ) . split ( " " ) ) if len ( sanitized_key_id ) < 16 : log . debug ( "Fingerprint is too short to be secure" ) return False fingerprint = gpg_key_fingerprint ( key_data , config_dir = config_dir ) if fingerprint is None : log . debug ( "Failed to fingerprint key" ) return False if sanitized_key_id != fingerprint and not fingerprint . endswith ( sanitized_key_id ) : log . debug ( "Imported key does not match the given ID" ) return False else : return True | Verify that a given serialized key when imported has the given key ID . Return True on success Return False on error |
58,496 | def gpg_export_key ( appname , key_id , config_dir = None , include_private = False ) : assert is_valid_appname ( appname ) config_dir = get_config_dir ( config_dir ) keydir = get_gpg_home ( appname , config_dir = config_dir ) gpg = gnupg . GPG ( homedir = keydir ) keydat = gpg . export_keys ( [ key_id ] , secret = include_private ) if not keydat : log . debug ( "Failed to export key %s from '%s'" % ( key_id , keydir ) ) assert keydat return keydat | Get the ASCII - armored key given the ID |
58,497 | def gpg_fetch_key ( key_url , key_id = None , config_dir = None ) : dat = None from_blockstack = False try : urlparse . urlparse ( key_url ) except : log . error ( "Invalid URL" ) return None if "://" in key_url and not key_url . lower ( ) . startswith ( "iks://" ) : opener = None key_data = None if key_url . startswith ( "blockstack://" ) : blockstack_opener = BlockstackHandler ( config_path = os . path . join ( config_dir , blockstack_client . CONFIG_FILENAME ) ) opener = urllib2 . build_opener ( blockstack_opener ) from_blockstack = True elif key_url . lower ( ) . startswith ( "http://" ) or key_url . lower ( ) . startswith ( "https://" ) : opener = urllib2 . build_opener ( ) opener . addheaders = [ ( 'User-agent' , 'Mozilla/5.0' ) ] else : opener = urllib2 . build_opener ( ) try : f = opener . open ( key_url ) key_data_str = f . read ( ) key_data = None if from_blockstack : key_data_dict = json . loads ( key_data_str ) assert len ( key_data_dict ) == 1 , "Got multiple keys" key_data = str ( key_data_dict [ key_data_dict . keys ( ) [ 0 ] ] ) else : key_data = key_data_str f . close ( ) except Exception , e : log . exception ( e ) if key_id is not None : log . error ( "Failed to fetch key '%s' from '%s'" % ( key_id , key_url ) ) else : log . error ( "Failed to fetch key from '%s'" % key_url ) return None if not from_blockstack and key_id is None : log . error ( "No key ID given for key located at %s" % key_url ) return None if key_id is not None : rc = gpg_verify_key ( key_id , key_data , config_dir = config_dir ) if not rc : log . error ( "Failed to verify key %s" % key_id ) return None dat = key_data else : key_server = key_url if '://' in key_server : key_server = urlparse . urlparse ( key_server ) . netloc dat = gpg_download_key ( key_id , key_server , config_dir = config_dir ) assert dat is not None and len ( dat ) > 0 , "BUG: no key data received for '%s' from '%s'" % ( key_id , key_url ) return dat | Fetch a GPG public key from the given URL . Supports anything urllib2 supports . If the URL has no scheme then assume it s a PGP key server and use GPG to go get it . The key is not accepted into any keyrings . Return the key data on success . If key_id is given verify the key matches . Return None on error or on failure to carry out any key verification |
58,498 | def gpg_app_put_key ( blockchain_id , appname , keyname , key_data , txid = None , immutable = False , proxy = None , wallet_keys = None , config_dir = None ) : assert is_valid_appname ( appname ) assert is_valid_keyname ( keyname ) try : keydir = make_gpg_home ( appname , config_dir = config_dir ) key_id = gpg_stash_key ( appname , key_data , config_dir = config_dir , gpghome = keydir ) assert key_id is not None , "Failed to stash key" log . debug ( "Stashed app key '%s:%s' (%s) under '%s'" % ( appname , keyname , key_id , keydir ) ) except Exception , e : log . exception ( e ) log . error ( "Failed to store GPG key '%s'" % keyname ) return { 'error' : "Failed to store GPG key locally" } assert is_valid_appname ( appname ) try : pubkey_data = gpg_export_key ( appname , key_id , config_dir = config_dir ) except : return { 'error' : 'Failed to load key' } fq_key_name = "gpg.%s.%s" % ( appname , keyname ) key_url = None if not immutable : res = client . put_mutable ( blockchain_id , fq_key_name , { fq_key_name : pubkey_data } , txid = txid , proxy = proxy , wallet_keys = wallet_keys ) if 'error' in res : return res key_url = client . make_mutable_data_url ( blockchain_id , fq_key_name , res [ 'version' ] ) else : res = client . put_immutable ( blockchain_id , fq_key_name , { fq_key_name : pubkey_data } , txid = txid , proxy = proxy , wallet_keys = wallet_keys ) if 'error' in res : return res key_url = client . make_immutable_data_url ( blockchain_id , fq_key_name , res [ 'immutable_data_hash' ] ) res [ 'key_url' ] = key_url res [ 'key_data' ] = pubkey_data res [ 'key_id' ] = gpg_key_fingerprint ( pubkey_data , config_dir = config_dir ) log . debug ( "Put key %s:%s (%s) to %s" % ( appname , keyname , res [ 'key_id' ] , key_url ) ) return res | Put an application GPG key . Stash the private key locally to an app - specific keyring . |
58,499 | def gpg_app_delete_key ( blockchain_id , appname , keyname , txid = None , immutable = False , proxy = None , wallet_keys = None , config_dir = None ) : assert is_valid_appname ( appname ) assert is_valid_keyname ( keyname ) fq_key_name = "gpg.%s.%s" % ( appname , keyname ) result = { } dead_pubkey_dict = None dead_pubkey = None key_id = None if not immutable : dead_pubkey_dict = client . get_mutable ( blockchain_id , fq_key_name , proxy = proxy , wallet_keys = wallet_keys ) if 'error' in dead_pubkey_dict : return dead_pubkey_dict else : dead_pubkey_dict = client . get_immutable ( blockchain_id , None , data_id = fq_key_name , proxy = proxy ) if 'error' in dead_pubkey_dict : return dead_pubkey_dict dead_pubkey_kv = dead_pubkey_dict [ 'data' ] assert len ( dead_pubkey_kv . keys ( ) ) == 1 , "Not a public key we wrote: %s" % dead_pubkey_kv dead_pubkey = dead_pubkey_kv [ dead_pubkey_kv . keys ( ) [ 0 ] ] key_id = gpg_key_fingerprint ( dead_pubkey , config_dir = config_dir ) assert key_id is not None , "Failed to load pubkey fingerprint" if not immutable : result = client . delete_mutable ( blockchain_id , fq_key_name , proxy = proxy , wallet_keys = wallet_keys ) else : result = client . delete_immutable ( blockchain_id , None , data_id = fq_key_name , wallet_keys = wallet_keys , proxy = proxy ) if 'error' in result : return result try : rc = gpg_unstash_key ( appname , key_id , config_dir = config_dir ) assert rc , "Failed to unstash key" except : log . warning ( "Failed to remove private key for '%s'" % key_id ) result [ 'warning' ] = "Failed to remove private key" if os . environ . get ( 'BLOCKSTACK_TEST' ) is not None : raise return result | Remove an application GPG key . Unstash the local private key . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.