idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
240,100
def product_version ( self ) : version_separator = '+' if version_separator in self . version : return self . version . split ( version_separator ) [ 0 ] return self . version . split ( '-' ) [ 0 ]
Swimlane product version
240,101
def build_number ( self ) : version_separator = '+' if version_separator in self . version : return self . version . split ( version_separator ) [ 2 ] return self . version . split ( '-' ) [ 1 ]
Swimlane build number
240,102
def authenticate ( self ) : self . _swimlane . _session . auth = None resp = self . _swimlane . request ( 'post' , 'user/login' , json = { 'userName' : self . _username , 'password' : self . _password } , ) self . _swimlane . _session . auth = self json_content = resp . json ( ) token = json_content . pop ( 'token' , N...
Send login request and update User instance login headers and token expiration
240,103
def _evaluate ( self ) : if self . _elements : for element in self . _elements : yield element else : for page in itertools . count ( ) : raw_elements = self . _retrieve_raw_elements ( page ) for raw_element in raw_elements : element = self . _parse_raw_element ( raw_element ) self . _elements . append ( element ) yiel...
Lazily retrieve and paginate report results and build Record instances from returned data
240,104
def _validate_user ( self , user ) : if self . _show_all_users : return if user . id in self . _allowed_user_ids : return user_member_group_ids = set ( [ g [ 'id' ] for g in user . _raw [ 'groups' ] ] ) if user_member_group_ids & self . _allowed_member_ids : return raise ValidationError ( self . record , 'User `{}` is ...
Validate a User instance against allowed user IDs or membership in a group
240,105
def _validate_group ( self , group ) : if self . _show_all_groups : return if group . id in self . _allowed_group_ids : return for parent_group_id in self . _allowed_subgroup_ids : parent_group = self . _swimlane . groups . get ( id = parent_group_id ) parent_group_child_ids = set ( [ g [ 'id' ] for g in parent_group ....
Validate a Group instance against allowed group IDs or subgroup of a parent group
240,106
def cast_to_python ( self , value ) : if value is not None : value = UserGroup ( self . _swimlane , value ) return value
Convert JSON definition to UserGroup object
240,107
def cursor ( self ) : if self . _cursor is None : self . _cursor = self . cursor_class ( self , self . get_initial_elements ( ) ) return self . _cursor
Cache and return cursor_class instance
240,108
def comment ( self , message ) : message = str ( message ) sw_repr = { '$type' : 'Core.Models.Record.Comments, Core' , 'createdByUser' : self . _record . _swimlane . user . as_usergroup_selection ( ) , 'createdDate' : pendulum . now ( ) . to_rfc3339_string ( ) , 'message' : message } comment = Comment ( self . _swimlan...
Add new comment to record comment field
240,109
def get_recursive_subclasses ( cls ) : return cls . __subclasses__ ( ) + [ g for s in cls . __subclasses__ ( ) for g in get_recursive_subclasses ( s ) ]
Return list of all subclasses for a class including subclasses of direct subclasses
240,110
def import_submodules ( package ) : if isinstance ( package , str ) : package = importlib . import_module ( package ) results = { } for _ , full_name , is_pkg in pkgutil . walk_packages ( package . __path__ , package . __name__ + '.' ) : results [ full_name ] = importlib . import_module ( full_name ) if is_pkg : result...
Return list of imported module instances from beneath root_package
240,111
def one_of_keyword_only ( * valid_keywords ) : def decorator ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : sentinel = object ( ) values = { } for key in valid_keywords : kwarg_value = kwargs . pop ( key , sentinel ) if kwarg_value is not sentinel : values [ key ] = kwarg_value if kwargs :...
Decorator to help make one - and - only - one keyword - only argument functions more reusable
240,112
def get_python ( self ) : value = super ( DatetimeField , self ) . get_python ( ) if value is not None : if self . input_type == self . _type_time : value = value . time ( ) if self . input_type == self . _type_date : value = value . date ( ) return value
Coerce to best date type representation for the field subtype
240,113
def cast_to_swimlane ( self , value ) : if value is None : return value if self . input_type == self . _type_interval : return value . in_seconds ( ) * 1000 return self . format_datetime ( value )
Return datetimes formatted as expected by API and timespans as millisecond epochs
240,114
def for_json ( self ) : value = super ( DatetimeField , self ) . for_json ( ) if isinstance ( value , pendulum . Interval ) : return value . in_seconds ( ) * 1000 if isinstance ( value , datetime ) : return self . format_datetime ( value ) if isinstance ( value , pendulum . Time ) : return str ( value ) if isinstance (...
Return date ISO8601 string formats for datetime date and time values milliseconds for intervals
240,115
def report_factory ( app , report_name , ** kwargs ) : created = pendulum . now ( ) . to_rfc3339_string ( ) user_model = app . _swimlane . user . as_usergroup_selection ( ) return Report ( app , { "$type" : Report . _type , "groupBys" : [ ] , "aggregates" : [ ] , "applicationIds" : [ app . id ] , "columns" : [ ] , "sor...
Report instance factory populating boilerplate raw data
240,116
def filter ( self , field_name , operand , value ) : if operand not in self . _FILTER_OPERANDS : raise ValueError ( 'Operand must be one of {}' . format ( ', ' . join ( self . _FILTER_OPERANDS ) ) ) record_stub = record_factory ( self . _app ) field = record_stub . get_field ( field_name ) self . _raw [ 'filters' ] . a...
Adds a filter to report
240,117
def list ( self ) : raw_reports = self . _swimlane . request ( 'get' , "reports?appId={}" . format ( self . _app . id ) ) . json ( ) return [ Report ( self . _app , raw_report ) for raw_report in raw_reports if raw_report [ '$type' ] == Report . _type ]
Retrieve all reports for parent app
240,118
def get ( self , report_id ) : return Report ( self . _app , self . _swimlane . request ( 'get' , "reports/{0}" . format ( report_id ) ) . json ( ) )
Retrieve report by ID
240,119
def get ( self , key , value ) : if key == 'id' : response = self . _swimlane . request ( 'get' , 'groups/{}' . format ( value ) ) return Group ( self . _swimlane , response . json ( ) ) else : response = self . _swimlane . request ( 'get' , 'groups/lookup?name={}' . format ( value ) ) matched_groups = response . json ...
Retrieve single group record by id or name
240,120
def get ( self , arg , value ) : if arg == 'id' : response = self . _swimlane . request ( 'get' , 'user/{}' . format ( value ) ) try : user_data = response . json ( ) except ValueError : raise ValueError ( 'Unable to find user with ID "{}"' . format ( value ) ) return User ( self . _swimlane , user_data ) else : respon...
Retrieve single user record by id or username
240,121
def _evaluate ( self ) : if not self . __retrieved : self . _elements = self . _retrieve_revisions ( ) self . __retrieved = True return super ( RevisionCursor , self ) . _evaluate ( )
Lazily retrieves caches and returns the list of record _revisions
240,122
def _retrieve_revisions ( self ) : response = self . _swimlane . request ( 'get' , 'history' , params = { 'type' : 'Records' , 'id' : self . _record . id } ) raw_revisions = response . json ( ) return [ Revision ( self . _record , raw ) for raw in raw_revisions ]
Retrieve and populate Revision instances from history API endpoint
240,123
def validate_value ( self , value ) : super ( ValuesListField , self ) . validate_value ( value ) if value is not None : if value not in self . selection_to_id_map : raise ValidationError ( self . record , 'Field "{}" invalid value "{}". Valid options: {}' . format ( self . name , value , ', ' . join ( self . selection...
Validate provided value is one of the valid options
240,124
def cast_to_report ( self , value ) : value = super ( ValuesListField , self ) . cast_to_report ( value ) if value : return value [ 'id' ]
Report format uses only the value s id
240,125
def validate_filters_or_records ( filters_or_records ) : if not filters_or_records : raise ValueError ( 'Must provide at least one filter tuples or Records' ) if not isinstance ( filters_or_records [ 0 ] , ( Record , tuple ) ) : raise ValueError ( 'Cannot provide both filter tuples and Records' ) _type = type ( filters...
Validation for filters_or_records variable from bulk_modify and bulk_delete
240,126
def get ( self , key , value ) : if key == 'id' : response = self . _swimlane . request ( 'get' , "app/{0}/record/{1}" . format ( self . _app . id , value ) ) return Record ( self . _app , response . json ( ) ) if key == 'tracking_id' : response = self . _swimlane . request ( 'get' , "app/{0}/record/tracking/{1}" . for...
Get a single record by id
240,127
def search ( self , * filters , ** kwargs ) : report = self . _app . reports . build ( 'search-' + random_string ( 8 ) , keywords = kwargs . pop ( 'keywords' , [ ] ) , limit = kwargs . pop ( 'limit' , Report . default_limit ) ) for filter_tuples in filters : report . filter ( * filter_tuples ) return list ( report )
Shortcut to generate a new temporary search report using provided filters and return the resulting records
240,128
def create ( self , ** fields ) : new_record = record_factory ( self . _app , fields ) new_record . save ( ) return new_record
Create and return a new record in associated app and return the newly created Record instance
240,129
def bulk_create ( self , * records ) : if not records : raise TypeError ( 'Must provide at least one record' ) if any ( not isinstance ( r , dict ) for r in records ) : raise TypeError ( 'New records must be provided as dicts' ) new_records = [ ] for record_data in records : record = record_factory ( self . _app , reco...
Create and validate multiple records in associated app
240,130
def _validate_list ( self , target ) : min_items = self . _field . field_definition . get ( 'minItems' ) max_items = self . _field . field_definition . get ( 'maxItems' ) if min_items is not None : if len ( target ) < min_items : raise ValidationError ( self . _record , "Field '{}' must have a minimum of {} item(s)" . ...
Validate a list against field validation rules
240,131
def set_swimlane ( self , value ) : value = value or [ ] self . _initial_value_to_ids_map = defaultdict ( list ) for item in value : self . _initial_value_to_ids_map [ item [ 'value' ] ] . append ( item [ 'id' ] ) return super ( ListField , self ) . set_swimlane ( [ d [ 'value' ] for d in value ] )
Convert from list of dicts with values to list of values
240,132
def set_python ( self , value ) : if not isinstance ( value , ( list , type ( None ) ) ) : raise ValidationError ( self . record , "Field '{}' must be set to a list, not '{}'" . format ( self . name , value . __class__ ) ) value = value or [ ] self . cursor . _validate_list ( value ) return super ( ListField , self ) ....
Validate using cursor for consistency between direct set of values vs modification of cursor values
240,133
def cast_to_swimlane ( self , value ) : value = super ( ListField , self ) . cast_to_swimlane ( value ) if not value : return None value_ids = deepcopy ( self . _initial_value_to_ids_map ) return [ self . _build_list_item ( item , value_ids [ item ] . pop ( 0 ) if value_ids [ item ] else None ) for item in value ]
Restore swimlane format attempting to keep initial IDs for any previously existing values
240,134
def select ( self , element ) : self . _field . validate_value ( element ) self . _elements . add ( element ) self . _sync_field ( )
Add an element to the set of selected elements Proxy to internal set . add and sync field
240,135
def get_python ( self ) : if self . multiselect : return super ( MultiSelectField , self ) . get_python ( ) return self . _get ( )
Only return cursor instance if configured for multiselect
240,136
def get_swimlane ( self ) : if self . multiselect : value = self . _get ( ) children = [ ] if value : for child in value : children . append ( self . cast_to_swimlane ( child ) ) return children return None return super ( MultiSelectField , self ) . get_swimlane ( )
Handle multi - select and single - select modes
240,137
def set_python ( self , value ) : if self . multiselect : value = value or [ ] elements = [ ] for element in value : self . validate_value ( element ) elements . append ( element ) value = elements else : self . validate_value ( value ) self . _set ( value )
Override to remove key from raw data when empty to work with server 2 . 16 + validation
240,138
def set_swimlane ( self , value ) : if self . multiselect : value = value or [ ] children = [ ] for child in value : children . append ( self . cast_to_python ( child ) ) return self . _set ( children ) return super ( MultiSelectField , self ) . set_swimlane ( value )
Cast all multi - select elements to correct internal type like single - select mode
240,139
def for_json ( self ) : if self . multiselect : return super ( MultiSelectField , self ) . for_json ( ) value = self . get_python ( ) if hasattr ( value , 'for_json' ) : return value . for_json ( ) return value
Handle multi - select vs single - select
240,140
def record_factory ( app , fields = None ) : record = Record ( app , { '$type' : Record . _type , 'isNew' : True , 'applicationId' : app . id , 'comments' : { '$type' : 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.Record.Comments, Core]], mscorlib]],...
Return a temporary Record instance to be used for field validation and value parsing
240,141
def set_python ( self , value ) : if value is not None and not isinstance ( value , self . supported_types ) or isinstance ( value , int ) : value = str ( value ) return super ( TextField , self ) . set_python ( value )
Set field internal value from the python representation of field value
240,142
def compare_versions ( version_a , version_b , zerofill = False ) : a_sections = list ( ( int ( match ) for match in re . findall ( r'\d+' , version_a ) ) ) b_sections = list ( ( int ( match ) for match in re . findall ( r'\d+' , version_b ) ) ) if zerofill : max_sections = max ( [ len ( a_sections ) , len ( b_sections...
Return direction of version relative to provided version sections
240,143
def requires_swimlane_version ( min_version = None , max_version = None ) : if min_version is None and max_version is None : raise ValueError ( 'Must provide either min_version, max_version, or both' ) if min_version and max_version and compare_versions ( min_version , max_version ) < 0 : raise ValueError ( 'min_versio...
Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range
240,144
def get_report ( self , value ) : if self . multiselect : value = value or [ ] children = [ ] for child in value : children . append ( self . cast_to_report ( child ) ) return children return self . cast_to_report ( value )
Return provided field Python value formatted for use in report filter
240,145
def get_bulk_modify ( self , value ) : if self . multiselect : value = value or [ ] return [ self . cast_to_bulk_modify ( child ) for child in value ] return self . cast_to_bulk_modify ( value )
Return value in format for bulk modify
240,146
def validate_value ( self , value ) : if self . readonly : raise ValidationError ( self . record , "Cannot set readonly field '{}'" . format ( self . name ) ) if value not in ( None , self . _unset ) : if self . supported_types and not isinstance ( value , tuple ( self . supported_types ) ) : raise ValidationError ( se...
Validate value is an acceptable type during set_python operation
240,147
def _set ( self , value ) : self . _value = value self . record . _raw [ 'values' ] [ self . id ] = self . get_swimlane ( )
Default setter used for both representations unless overridden
240,148
def resolve_field_class ( field_definition ) : try : return _FIELD_TYPE_MAP [ field_definition [ '$type' ] ] except KeyError as error : error . message = 'No field available to handle Swimlane $type "{}"' . format ( field_definition ) raise
Return field class most fitting of provided Swimlane field definition
240,149
def get_cache_index_key ( resource ) : if isinstance ( resource , APIResource ) : attr , attr_value = list ( resource . get_cache_index_keys ( ) . items ( ) ) [ 0 ] key = ( type ( resource ) , attr , attr_value ) else : key = tuple ( resource ) if len ( key ) != 3 : raise TypeError ( 'Cache key must be tuple of (class,...
Return a usable cache lookup key for an already initialized resource
240,150
def check_cache ( resource_type ) : def decorator ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : try : adapter = args [ 0 ] key , val = list ( kwargs . items ( ) ) [ 0 ] except IndexError : logger . warning ( "Couldn't generate full index key, skipping cache" ) else : index_key = ( resourc...
Decorator for adapter methods to check cache for resource before normally sending requests to retrieve data
240,151
def cache ( self , resource ) : if not isinstance ( resource , APIResource ) : raise TypeError ( 'Cannot cache `{!r}`, can only cache APIResource instances' . format ( resource ) ) if self . __cache_max_size == 0 : return try : cache_internal_key = resource . get_cache_internal_key ( ) cache_index_keys = resource . get...
Insert a resource instance into appropriate resource cache
240,152
def clear ( self , * resource_types ) : resource_types = resource_types or tuple ( self . __caches . keys ( ) ) for cls in resource_types : self . __caches [ cls ] . clear ( ) del self . __caches [ cls ]
Clear cache for each provided APIResource class or all resources if no classes are provided
240,153
def _set ( self , value ) : super ( AttachmentsField , self ) . _set ( value ) self . _cursor = None
Override setter allow clearing cursor
240,154
def verify_otp ( request ) : ctx = { } if request . method == "POST" : verification_code = request . POST . get ( 'verification_code' ) if verification_code is None : ctx [ 'error_message' ] = "Missing verification code." else : otp_ = UserOTP . objects . get ( user = request . user ) totp_ = totp . TOTP ( otp_ . secre...
Verify a OTP request
240,155
def at ( self , for_time , counter_offset = 0 ) : if not isinstance ( for_time , datetime . datetime ) : for_time = datetime . datetime . fromtimestamp ( int ( for_time ) ) return self . generate_otp ( self . timecode ( for_time ) + counter_offset )
Accepts either a Unix timestamp integer or a Time object . Time objects will be adjusted to UTC automatically
240,156
def verify ( self , otp , for_time = None , valid_window = 0 ) : if for_time is None : for_time = datetime . datetime . now ( ) if valid_window : for i in range ( - valid_window , valid_window + 1 ) : if utils . strings_equal ( str ( otp ) , str ( self . at ( for_time , i ) ) ) : return True return False return utils ....
Verifies the OTP passed in against the current time OTP
240,157
def provisioning_uri ( self , name , issuer_name = None ) : return utils . build_uri ( self . secret , name , issuer_name = issuer_name )
Returns the provisioning URI for the OTP This can then be encoded in a QR Code and used to provision the Google Authenticator app
240,158
def build_uri ( secret , name , initial_count = None , issuer_name = None ) : is_initial_count_present = ( initial_count is not None ) otp_type = 'hotp' if is_initial_count_present else 'totp' base = 'otpauth://%s/' % otp_type if issuer_name : issuer_name = quote ( issuer_name ) base += '%s:' % issuer_name uri = '%(bas...
Returns the provisioning URI for the OTP ; works for either TOTP or HOTP .
240,159
def strings_equal ( s1 , s2 ) : try : s1 = unicodedata . normalize ( 'NFKC' , str ( s1 ) ) s2 = unicodedata . normalize ( 'NFKC' , str ( s2 ) ) except : s1 = unicodedata . normalize ( 'NFKC' , unicode ( s1 ) ) s2 = unicodedata . normalize ( 'NFKC' , unicode ( s2 ) ) return compare_digest ( s1 , s2 )
Timing - attack resistant string comparison .
240,160
def GetPythonLibraryDirectoryPath ( ) : path = sysconfig . get_python_lib ( True ) _ , _ , path = path . rpartition ( sysconfig . PREFIX ) if path . startswith ( os . sep ) : path = path [ 1 : ] return path
Retrieves the Python library directory path .
240,161
def run ( self ) : compiler = new_compiler ( compiler = self . compiler ) if compiler . compiler_type == "msvc" : self . define = [ ( "UNICODE" , "" ) , ] else : command = "sh configure --disable-shared-libs" output = self . _RunCommand ( command ) print_line = False for line in output . split ( "\n" ) : line = line . ...
Runs the build extension .
240,162
def _ReadConfigureAc ( self ) : file_object = open ( "configure.ac" , "rb" ) if not file_object : raise IOError ( "Unable to open: configure.ac" ) found_ac_init = False found_library_name = False for line in file_object . readlines ( ) : line = line . strip ( ) if found_library_name : library_version = line [ 1 : - 2 ]...
Reads configure . ac to initialize the project information .
240,163
def _ReadMakefileAm ( self ) : if not self . library_name : raise RuntimeError ( "Missing library name" ) file_object = open ( "Makefile.am" , "rb" ) if not file_object : raise IOError ( "Unable to open: Makefile.am" ) found_subdirs = False for line in file_object . readlines ( ) : line = line . strip ( ) if found_subd...
Reads Makefile . am to initialize the project information .
240,164
def babel_compile ( source , ** kwargs ) : presets = kwargs . get ( 'presets' ) if not presets : kwargs [ 'presets' ] = [ "es2015" ] with open ( BABEL_COMPILER , 'rb' ) as babel_js : return evaljs ( ( babel_js . read ( ) . decode ( 'utf-8' ) , 'var bres, res;' 'bres = Babel.transform(dukpy.es6code, dukpy.babel_options)...
Compiles the given source from ES6 to ES5 using Babeljs
240,165
def coffee_compile ( source ) : with open ( COFFEE_COMPILER , 'rb' ) as coffeescript_js : return evaljs ( ( coffeescript_js . read ( ) . decode ( 'utf-8' ) , 'CoffeeScript.compile(dukpy.coffeecode)' ) , coffeecode = source )
Compiles the given source from CoffeeScript to JavaScript
240,166
def register_path ( self , path ) : self . _paths . insert ( 0 , os . path . abspath ( path ) )
Registers a directory where to look for modules .
240,167
def lookup ( self , module_name ) : for search_path in self . _paths : module_path = os . path . join ( search_path , module_name ) new_module_name , module_file = self . _lookup ( module_path , module_name ) if module_file : return new_module_name , module_file return None , None
Searches for a file providing given module .
240,168
def load ( self , module_name ) : module_name , path = self . lookup ( module_name ) if path : with open ( path , 'rb' ) as f : return module_name , f . read ( ) . decode ( 'utf-8' ) return None , None
Returns source code and normalized module id of the given module .
240,169
def less_compile ( source , options = None ) : options = options or { } res = NodeLikeInterpreter ( ) . evaljs ( ( 'var result = null;' 'var less = require("less/less-node");' , 'less.render(dukpy.lesscode, dukpy.lessoptions, function(error, output) {' ' result = {"error": error, "output": output};' '});' 'result;' ) ...
Compiles the given source from LESS to CSS
240,170
def install_jspackage ( package_name , version , modulesdir ) : if not version : version = '' requirements = _resolve_dependencies ( package_name , version ) print ( 'Packages going to be installed: {0}' . format ( ', ' . join ( '{0}->{1}' . format ( * i ) for i in requirements ) ) ) downloads = { } for dependency_name...
Installs a JavaScript package downloaded from npmjs . org .
240,171
def evaljs ( self , code , ** kwargs ) : jsvars = json . dumps ( kwargs ) jscode = self . _adapt_code ( code ) if not isinstance ( jscode , bytes ) : jscode = jscode . encode ( 'utf-8' ) if not isinstance ( jsvars , bytes ) : jsvars = jsvars . encode ( 'utf-8' ) res = _dukpy . eval_string ( self , jscode , jsvars ) if ...
Runs JavaScript code in the context of the interpreter .
240,172
def typescript_compile ( source ) : with open ( TS_COMPILER , 'r' ) as tsservices_js : return evaljs ( ( tsservices_js . read ( ) , 'ts.transpile(dukpy.tscode, {options});' . format ( options = TSC_OPTIONS ) ) , tscode = source )
Compiles the given source from TypeScript to ES5 using TypescriptServices . js
240,173
def get_private_file ( self ) : return PrivateFile ( request = self . request , storage = self . get_storage ( ) , relative_name = self . get_path ( ) )
Return all relevant data in a single object so this is easy to extend and server implementations can pick what they need .
240,174
def get ( self , request , * args , ** kwargs ) : private_file = self . get_private_file ( ) if not self . can_access_file ( private_file ) : return HttpResponseForbidden ( 'Private storage access denied' ) if not private_file . exists ( ) : return self . serve_file_not_found ( private_file ) else : return self . serve...
Handle incoming GET requests
240,175
def serve_file ( self , private_file ) : response = self . server_class ( ) . serve ( private_file ) if self . content_disposition : filename = self . get_content_disposition_filename ( private_file ) response [ 'Content-Disposition' ] = b'; ' . join ( [ self . content_disposition . encode ( ) , self . _encode_filename...
Serve the file that was retrieved from the storage . The relative path can be found with private_file . relative_name .
240,176
def get_content_disposition_filename ( self , private_file ) : return self . content_disposition_filename or os . path . basename ( private_file . relative_name )
Return the filename in the download header .
240,177
def _encode_filename_header ( self , filename ) : user_agent = self . request . META . get ( 'HTTP_USER_AGENT' , None ) if 'WebKit' in user_agent : return u'filename={}' . format ( filename ) . encode ( "utf-8" ) elif 'MSIE' in user_agent : url_encoded = quote ( filename . encode ( "utf-8" ) ) . replace ( 'attachment' ...
The filename encoded to use in a Content - Disposition header .
240,178
def add_no_cache_headers ( func ) : @ wraps ( func ) def _dec ( * args , ** kwargs ) : response = func ( * args , ** kwargs ) response [ 'Expires' ] = 'Thu, 01 Jan 1970 00:00:00 GMT' response [ 'Cache-Control' ] = 'max-age=0, no-cache, must-revalidate, proxy-revalidate' return response return _dec
Makes sure the retrieved file is not cached on disk or cached by proxy servers in between . This would circumvent any checking whether the user may even access the file .
240,179
def readTrainingData ( file_locations , GROUP_LABEL ) : class Mock ( object ) : pass mock_module = Mock ( ) mock_module . PARENT_LABEL = GROUP_LABEL for location in file_locations : with open ( location ) as f : tree = etree . parse ( f ) xml = tree . getroot ( ) for each in data_prep_utils . TrainingData ( xml , mock_...
Used in downstream tests
240,180
def device ( value ) : browser = None for regex , name in BROWSERS : if regex . search ( value ) : browser = name break device = None for regex , name in DEVICES : if regex . search ( value ) : device = name break if browser and device : return _ ( '%(browser)s on %(device)s' ) % { 'browser' : browser , 'device' : devi...
Transform a User Agent into human readable text .
240,181
def location ( value ) : try : location = geoip ( ) and geoip ( ) . city ( value ) except Exception : try : location = geoip ( ) and geoip ( ) . country ( value ) except Exception as e : warnings . warn ( str ( e ) ) location = None if location and location [ 'country_name' ] : if 'city' in location and location [ 'cit...
Transform an IP address into an approximate location .
240,182
def before ( func ) : class BeforeDecorator ( LambdaDecorator ) : def before ( self , event , context ) : return func ( event , context ) return BeforeDecorator
Run a function before the handler is invoked is passed the event & context and must return an event & context too .
240,183
def after ( func ) : class AfterDecorator ( LambdaDecorator ) : def after ( self , retval ) : return func ( retval ) return AfterDecorator
Run a function after the handler is invoked is passed the response and must return an response too .
240,184
def on_exception ( func ) : class OnExceptionDecorator ( LambdaDecorator ) : def on_exception ( self , exception ) : return func ( exception ) return OnExceptionDecorator
Run a function when a handler thows an exception . It s return value is returned to AWS .
240,185
def async_handler ( handler ) : @ wraps ( handler ) def wrapper ( event , context ) : context . loop = asyncio . get_event_loop ( ) return context . loop . run_until_complete ( handler ( event , context ) ) return wrapper
This decorator allows for use of async handlers by automatically running them in an event loop . The loop is added to the context object for if the handler needs it .
240,186
def dump_json_body ( handler ) : @ wraps ( handler ) def wrapper ( event , context ) : response = handler ( event , context ) if 'body' in response : try : response [ 'body' ] = json . dumps ( response [ 'body' ] ) except Exception as exception : return { 'statusCode' : 500 , 'body' : str ( exception ) } return respons...
Automatically serialize response bodies with json . dumps .
240,187
def json_http_resp ( handler ) : @ wraps ( handler ) def wrapper ( event , context ) : response = handler ( event , context ) try : body = json . dumps ( response ) except Exception as exception : return { 'statusCode' : 500 , 'body' : str ( exception ) } return { 'statusCode' : 200 , 'body' : body } return wrapper
Automatically serialize return value to the body of a successfull HTTP response .
240,188
def load_json_body ( handler ) : @ wraps ( handler ) def wrapper ( event , context ) : if isinstance ( event . get ( 'body' ) , str ) : try : event [ 'body' ] = json . loads ( event [ 'body' ] ) except : return { 'statusCode' : 400 , 'body' : 'BAD REQUEST' } return handler ( event , context ) return wrapper
Automatically deserialize event bodies with json . loads .
240,189
def json_schema_validator ( request_schema = None , response_schema = None ) : def wrapper_wrapper ( handler ) : @ wraps ( handler ) def wrapper ( event , context ) : if request_schema is not None : if jsonschema is None : logger . error ( 'jsonschema is not installed, skipping request validation' ) else : try : jsonsc...
Validate your request & response payloads against a JSONSchema .
240,190
def no_retry_on_failure ( handler ) : seen_request_ids = set ( ) @ wraps ( handler ) def wrapper ( event , context ) : if context . aws_request_id in seen_request_ids : logger . critical ( 'Retry attempt on request id %s detected.' , context . aws_request_id ) return { 'statusCode' : 200 } seen_request_ids . add ( cont...
AWS Lambda retries scheduled lambdas that don t execute succesfully .
240,191
def _wrap_thing ( self , thing , kind ) : thing [ 'created' ] = self . _epoch_utc_to_local ( thing [ 'created_utc' ] ) thing [ 'd_' ] = copy . deepcopy ( thing ) ThingType = namedtuple ( kind , thing . keys ( ) ) thing = ThingType ( ** thing ) return thing
Mimic praw . Submission and praw . Comment API
240,192
def _add_nec_args ( self , payload ) : if self . _limited ( payload ) : return if 'limit' not in payload : payload [ 'limit' ] = self . max_results_per_request if 'sort' not in payload : payload [ 'sort' ] = 'desc' if 'filter' in payload : if not isinstance ( payload [ 'filter' ] , list ) : if isinstance ( payload [ 'f...
Adds limit and created_utc arguments to the payload as necessary .
240,193
def pretty_path ( path ) : path = fmt . to_utf8 ( path ) home_dir = os . path . expanduser ( "~" ) if path . startswith ( home_dir ) : path = "~" + path [ len ( home_dir ) : ] return '"%s"' % ( path , )
Prettify path for logging .
240,194
def guarded ( self , call , * args ) : self . LOG . debug ( '%s(%s)' % ( call . __name__ , ', ' . join ( [ pretty_path ( i ) for i in args ] ) , ) ) if not self . options . dry_run : try : call ( * args ) except ( EnvironmentError , UnicodeError ) as exc : self . fatal ( '%s(%s) failed [%s]' % ( call . __name__ , ', ' ...
Catch exceptions thrown by filesystem calls and don t really execute them in dry - run mode .
240,195
def run ( ) : logging . basicConfig ( level = logging . DEBUG ) load_config . ConfigLoader ( ) . load ( ) config . debug = True print ( repr ( config . engine . item ( sys . argv [ 1 ] ) ) )
Module level test .
240,196
def _make_it_so ( self , command , calls , * args , ** kwargs ) : observer = kwargs . pop ( 'observer' , False ) args = ( self . _fields [ "hash" ] , ) + args try : for call in calls : self . _engine . LOG . debug ( "%s%s torrent #%s (%s)" % ( command [ 0 ] . upper ( ) , command [ 1 : ] , self . _fields [ "hash" ] , ca...
Perform some error - checked XMLRPC calls .
240,197
def fetch ( self , name , engine_name = None ) : try : return self . _fields [ name ] except KeyError : if isinstance ( name , ( int , long ) ) : name = "custom_%d" % name if name == "done" : val = float ( self . fetch ( "completed_chunks" ) ) / self . fetch ( "size_chunks" ) elif name == "files" : val = self . _get_fi...
Get a field on demand .
240,198
def datapath ( self ) : path = self . _fields [ 'path' ] if not path : path = self . fetch ( 'directory' ) if path and not self . _fields [ 'is_multi_file' ] : path = os . path . join ( path , self . _fields [ 'name' ] ) return os . path . expanduser ( fmt . to_unicode ( path ) )
Get an item s data path .
240,199
def announce_urls ( self , default = [ ] ) : try : response = self . _engine . _rpc . t . multicall ( self . _fields [ "hash" ] , 0 , "t.url=" , "t.is_enabled=" ) except xmlrpc . ERRORS as exc : raise error . EngineError ( "While getting announce URLs for #%s: %s" % ( self . _fields [ "hash" ] , exc ) ) if response : r...
Get a list of all announce URLs . Returns default if no trackers are found at all .