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 ite... | 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_e... | 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 . isc... | 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_loc... | 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 ( fo... | 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 ... | 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 . i... | 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 , in... | 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 = edita... | 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 , s... | 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 ( ) ... | 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... | 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_wor... | 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 = ma... | 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 (... | 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... | 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_... | 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_param... | 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_siz... | 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 ... | 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' ] ) retu... | 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 ( t... | 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"... | 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 ... | 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 [ ... | 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 - Movi... | 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 ( '.' ,... | 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 [ 'err... | 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 [ '... | 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 .... | 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_yiel... | 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... | 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" ] = s... | 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 . Tup... | 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 ( '... | 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 ( progr... | 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 == 'subm... | 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 , datet... | 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 ... | 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 , ... | 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 != 'SE... | 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... | 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 b... | 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 ( re... | 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... | 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 ) ... | 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... | 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 . delet... | 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 . cou... | 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... | 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 = ... | 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 = inc... | 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 . startswit... | 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 failu... |
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_k... | 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_pub... | 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.