idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
247,100
def simplify ( self ) : expr = self . expr self . expr = _cancel_mul ( expr , self . registry ) return self
Return a new equivalent unit object with a simplified unit expression
247,101
def _auto_positive_symbol ( tokens , local_dict , global_dict ) : result = [ ] tokens . append ( ( None , None ) ) for tok , nextTok in zip ( tokens , tokens [ 1 : ] ) : tokNum , tokVal = tok nextTokNum , nextTokVal = nextTok if tokNum == token . NAME : name = tokVal if name in global_dict : obj = global_dict [ name ] ...
Inserts calls to Symbol for undefined variables . Passes in positive = True as a keyword argument . Adapted from sympy . sympy . parsing . sympy_parser . auto_symbol
247,102
def intersection ( self , range ) : if self . worksheet != range . worksheet : return None start = ( max ( self . _start [ 0 ] , range . _start [ 0 ] ) , max ( self . _start [ 1 ] , range . _start [ 1 ] ) ) end = ( min ( self . _end [ 0 ] , range . _end [ 0 ] ) , min ( self . _end [ 1 ] , range . _end [ 1 ] ) ) if end ...
Calculates the intersection with another range object
247,103
def interprocess_locked ( path ) : lock = InterProcessLock ( path ) def decorator ( f ) : @ six . wraps ( f ) def wrapper ( * args , ** kwargs ) : with lock : return f ( * args , ** kwargs ) return wrapper return decorator
Acquires & releases a interprocess lock around call into decorated function .
247,104
def acquire ( self , blocking = True , delay = DELAY_INCREMENT , max_delay = MAX_DELAY , timeout = None ) : if delay < 0 : raise ValueError ( "Delay must be greater than or equal to zero" ) if timeout is not None and timeout < 0 : raise ValueError ( "Timeout must be greater than or equal to zero" ) if delay >= max_dela...
Attempt to acquire the given lock .
247,105
def release ( self ) : if not self . acquired : raise threading . ThreadError ( "Unable to release an unacquired" " lock" ) try : self . unlock ( ) except IOError : self . logger . exception ( "Could not unlock the acquired lock opened" " on `%s`" , self . path ) else : self . acquired = False try : self . _do_close ( ...
Release the previously acquired lock .
247,106
def canonicalize_path ( path ) : if isinstance ( path , six . binary_type ) : return path if isinstance ( path , six . text_type ) : return _fsencode ( path ) else : return canonicalize_path ( str ( path ) )
Canonicalizes a potential path .
247,107
def read_locked ( * args , ** kwargs ) : def decorator ( f ) : attr_name = kwargs . get ( 'lock' , '_lock' ) @ six . wraps ( f ) def wrapper ( self , * args , ** kwargs ) : rw_lock = getattr ( self , attr_name ) with rw_lock . read_lock ( ) : return f ( self , * args , ** kwargs ) return wrapper if kwargs or not args :...
Acquires & releases a read lock around call into decorated method .
247,108
def write_locked ( * args , ** kwargs ) : def decorator ( f ) : attr_name = kwargs . get ( 'lock' , '_lock' ) @ six . wraps ( f ) def wrapper ( self , * args , ** kwargs ) : rw_lock = getattr ( self , attr_name ) with rw_lock . write_lock ( ) : return f ( self , * args , ** kwargs ) return wrapper if kwargs or not args...
Acquires & releases a write lock around call into decorated method .
247,109
def is_writer ( self , check_pending = True ) : me = self . _current_thread ( ) if self . _writer == me : return True if check_pending : return me in self . _pending_writers else : return False
Returns if the caller is the active writer or a pending writer .
247,110
def owner ( self ) : if self . _writer is not None : return self . WRITER if self . _readers : return self . READER return None
Returns whether the lock is locked by a writer or reader .
247,111
def read_lock ( self ) : me = self . _current_thread ( ) if me in self . _pending_writers : raise RuntimeError ( "Writer %s can not acquire a read lock" " while waiting for the write lock" % me ) with self . _cond : while True : if self . _writer is None or self . _writer == me : try : self . _readers [ me ] = self . _...
Context manager that grants a read lock .
247,112
def write_lock ( self ) : me = self . _current_thread ( ) i_am_writer = self . is_writer ( check_pending = False ) if self . is_reader ( ) and not i_am_writer : raise RuntimeError ( "Reader %s to writer privilege" " escalation not allowed" % me ) if i_am_writer : yield self else : with self . _cond : self . _pending_wr...
Context manager that grants a write lock .
247,113
def send_sms ( self , text , ** kw ) : params = { 'user' : self . _user , 'pass' : self . _passwd , 'msg' : text } kw . setdefault ( "verify" , False ) if not kw [ "verify" ] : requests . packages . urllib3 . disable_warnings ( InsecureRequestWarning ) res = requests . get ( FreeClient . BASE_URL , params = params , **...
Send an SMS . Since Free only allows us to send SMSes to ourselves you don t have to provide your phone number .
247,114
def create_filebase_name ( self , group_info , extension = 'gz' , file_name = None ) : dirname = self . filebase . formatted_dirname ( groups = group_info ) if not file_name : file_name = self . filebase . prefix_template + '.' + extension return dirname , file_name
Return tuple of resolved destination folder name and file name
247,115
def write_batch ( self , batch ) : for item in batch : for key in item : self . aggregated_info [ 'occurrences' ] [ key ] += 1 self . increment_written_items ( ) if self . items_limit and self . items_limit == self . get_metadata ( 'items_count' ) : raise ItemsLimitReached ( 'Finishing job after items_limit reached: {}...
Receives the batch and writes it . This method is usually called from a manager .
247,116
def _get_aggregated_info ( self ) : agg_results = { } for key in self . aggregated_info [ 'occurrences' ] : agg_results [ key ] = { 'occurrences' : self . aggregated_info [ 'occurrences' ] . get ( key ) , 'coverage' : ( float ( self . aggregated_info [ 'occurrences' ] . get ( key ) ) / float ( self . get_metadata ( 'it...
Keeps track of aggregated info in a dictionary called self . aggregated_info
247,117
def create_document_batches ( jsonlines , id_field , max_batch_size = CLOUDSEARCH_MAX_BATCH_SIZE ) : batch = [ ] fixed_initial_size = 2 def create_entry ( line ) : try : record = json . loads ( line ) except : raise ValueError ( 'Could not parse JSON from: %s' % line ) key = record [ id_field ] return '{"type":"add","i...
Create batches in expected AWS Cloudsearch format limiting the byte size per batch according to given max_batch_size
247,118
def _post_document_batch ( self , batch ) : target_batch = '/2013-01-01/documents/batch' url = self . endpoint_url + target_batch return requests . post ( url , data = batch , headers = { 'Content-type' : 'application/json' } )
Send a batch to Cloudsearch endpoint
247,119
def _create_path_if_not_exist ( self , path ) : if path and not os . path . exists ( path ) : os . makedirs ( path )
Creates a folders path if it doesn t exist
247,120
def close ( self ) : if self . read_option ( 'save_pointer' ) : self . _update_last_pointer ( ) super ( S3Writer , self ) . close ( )
Called to clean all possible tmp files created during the process .
247,121
def get_boto_connection ( aws_access_key_id , aws_secret_access_key , region = None , bucketname = None , host = None ) : m = _AWS_ACCESS_KEY_ID_RE . match ( aws_access_key_id ) if m is None or m . group ( ) != aws_access_key_id : logging . error ( 'The provided aws_access_key_id is not in the correct format. It must \...
Conection parameters must be different only if bucket name has a period
247,122
def maybe_cast_list ( value , types ) : if not isinstance ( value , list ) : return value if type ( types ) not in ( list , tuple ) : types = ( types , ) for list_type in types : if issubclass ( list_type , list ) : try : return list_type ( value ) except ( TypeError , ValueError ) : pass return value
Try to coerce list values into more specific list subclasses in types .
247,123
def iterate_chunks ( file , chunk_size ) : chunk = file . read ( chunk_size ) while chunk : yield chunk chunk = file . read ( chunk_size )
Iterate chunks of size chunk_size from a file - like object
247,124
def unshift ( self , chunk ) : if chunk : self . _pos -= len ( chunk ) self . _unconsumed . append ( chunk )
Pushes a chunk of data back into the internal buffer . This is useful in certain situations where a stream is being consumed by code that needs to un - consume some amount of data that it has optimistically pulled out of the source so that the data can be passed on to some other party .
247,125
def readline ( self ) : line = "" n_pos = - 1 try : while n_pos < 0 : line += self . next_chunk ( ) n_pos = line . find ( '\n' ) except StopIteration : pass if n_pos >= 0 : line , extra = line [ : n_pos + 1 ] , line [ n_pos + 1 : ] self . unshift ( extra ) return line
Read until a new - line character is encountered
247,126
def close ( self ) : if callable ( getattr ( self . _file , 'close' , None ) ) : self . _iterator . close ( ) self . _iterator = None self . _unconsumed = None self . closed = True
Disable al operations and close the underlying file - like object if any
247,127
def configuration_from_uri ( uri , uri_regex ) : file_path = re . match ( uri_regex , uri ) . groups ( ) [ 0 ] with open ( file_path ) as f : configuration = pickle . load ( f ) [ 'configuration' ] configuration = yaml . safe_load ( configuration ) configuration [ 'exporter_options' ] [ 'resume' ] = True persistence_st...
returns a configuration object .
247,128
def buffer ( self , item ) : key = self . get_key_from_item ( item ) if not self . grouping_info . is_first_file_item ( key ) : self . items_group_files . add_item_separator_to_file ( key ) self . grouping_info . ensure_group_info ( key ) self . items_group_files . add_item_to_file ( item , key )
Receive an item and write it .
247,129
def parse_persistence_uri ( cls , persistence_uri ) : regex = cls . persistence_uri_re match = re . match ( regex , persistence_uri ) if not match : raise ValueError ( "Couldn't parse persistence URI: %s -- regex: %s)" % ( persistence_uri , regex ) ) conn_params = match . groupdict ( ) missing = { 'proto' , 'job_id' , ...
Parse a database URI and the persistence state ID from the given persistence URI
247,130
def configuration_from_uri ( cls , persistence_uri ) : db_uri , persistence_state_id = cls . parse_persistence_uri ( persistence_uri ) engine = create_engine ( db_uri ) Base . metadata . create_all ( engine ) Base . metadata . bind = engine DBSession = sessionmaker ( bind = engine ) session = DBSession ( ) job = sessio...
Return a configuration object .
247,131
def _get_input_files ( cls , input_specification ) : if isinstance ( input_specification , ( basestring , dict ) ) : input_specification = [ input_specification ] elif not isinstance ( input_specification , list ) : raise ConfigurationError ( "Input specification must be string, list or dict." ) out = [ ] for input_uni...
Get list of input files according to input definition .
247,132
def consume_messages ( self , batchsize ) : if not self . _reservoir : self . finished = True return for msg in self . _reservoir [ : batchsize ] : yield msg self . _reservoir = self . _reservoir [ batchsize : ]
Get messages batch from the reservoir
247,133
def decompress_messages ( self , offmsgs ) : for offmsg in offmsgs : yield offmsg . message . key , self . decompress_fun ( offmsg . message . value )
Decompress pre - defined compressed fields for each message . Msgs should be unpacked before this step .
247,134
def filter_batch ( self , batch ) : for item in batch : if self . filter ( item ) : yield item else : self . set_metadata ( 'filtered_out' , self . get_metadata ( 'filtered_out' ) + 1 ) self . total += 1 self . _log_progress ( )
Receives the batch filters it and returns it .
247,135
def write_batch ( self , batch ) : for item in batch : self . write_buffer . buffer ( item ) key = self . write_buffer . get_key_from_item ( item ) if self . write_buffer . should_write_buffer ( key ) : self . _write_current_buffer_for_group_key ( key ) self . increment_written_items ( ) self . _check_items_limit ( )
Buffer a batch of items to be written and update internal counters .
247,136
def _check_items_limit ( self ) : if self . items_limit and self . items_limit == self . get_metadata ( 'items_count' ) : raise ItemsLimitReached ( 'Finishing job after items_limit reached:' ' {} items written.' . format ( self . get_metadata ( 'items_count' ) ) )
Raise ItemsLimitReached if the writer reached the configured items limit .
247,137
def flush ( self ) : for key in self . grouping_info . keys ( ) : if self . _should_flush ( key ) : self . _write_current_buffer_for_group_key ( key )
Ensure all remaining buffers are written .
247,138
def has_manifest ( app , filename = 'manifest.json' ) : try : return pkg_resources . resource_exists ( app , filename ) except ImportError : return os . path . isabs ( filename ) and os . path . exists ( filename )
Verify the existance of a JSON assets manifest
247,139
def register_manifest ( app , filename = 'manifest.json' ) : if current_app . config . get ( 'TESTING' ) : return if not has_manifest ( app , filename ) : msg = '{filename} not found for {app}' . format ( ** locals ( ) ) raise ValueError ( msg ) manifest = _manifests . get ( app , { } ) manifest . update ( load_manifes...
Register an assets json manifest
247,140
def load_manifest ( app , filename = 'manifest.json' ) : if os . path . isabs ( filename ) : path = filename else : path = pkg_resources . resource_filename ( app , filename ) with io . open ( path , mode = 'r' , encoding = 'utf8' ) as stream : data = json . load ( stream ) _registered_manifests [ app ] = path return d...
Load an assets json manifest
247,141
def from_manifest ( app , filename , raw = False , ** kwargs ) : cfg = current_app . config if current_app . config . get ( 'TESTING' ) : return path = _manifests [ app ] [ filename ] if not raw and cfg . get ( 'CDN_DOMAIN' ) and not cfg . get ( 'CDN_DEBUG' ) : scheme = 'https' if cfg . get ( 'CDN_HTTPS' ) else request...
Get the path to a static file for a given app entry of a given type .
247,142
def cdn_for ( endpoint , ** kwargs ) : if current_app . config [ 'CDN_DOMAIN' ] : if not current_app . config . get ( 'CDN_DEBUG' ) : kwargs . pop ( '_external' , None ) return cdn_url_for ( endpoint , ** kwargs ) return url_for ( endpoint , ** kwargs )
Get a CDN URL for a static assets .
247,143
def get_or_create ( self , write_concern = None , auto_save = True , * q_objs , ** query ) : defaults = query . pop ( 'defaults' , { } ) try : doc = self . get ( * q_objs , ** query ) return doc , False except self . _document . DoesNotExist : query . update ( defaults ) doc = self . _document ( ** query ) if auto_save...
Retrieve unique object or create if it doesn t exist .
247,144
def generic_in ( self , ** kwargs ) : query = { } for key , value in kwargs . items ( ) : if not value : continue if isinstance ( value , ( list , tuple ) ) and len ( value ) == 1 : value = value [ 0 ] if isinstance ( value , ( list , tuple ) ) : if all ( isinstance ( v , basestring ) for v in value ) : ids = [ ObjectI...
Bypass buggy GenericReferenceField querying issue
247,145
def issues_notifications ( user ) : notifications = [ ] qs = issues_for ( user ) . only ( 'id' , 'title' , 'created' , 'subject' ) for issue in qs . no_dereference ( ) : notifications . append ( ( issue . created , { 'id' : issue . id , 'title' : issue . title , 'subject' : { 'id' : issue . subject [ '_ref' ] . id , 't...
Notify user about open issues
247,146
def get_config ( key ) : key = 'AVATAR_{0}' . format ( key . upper ( ) ) local_config = current_app . config . get ( key ) return local_config or getattr ( theme . current , key , DEFAULTS [ key ] )
Get an identicon configuration parameter .
247,147
def get_provider ( ) : name = get_config ( 'provider' ) available = entrypoints . get_all ( 'udata.avatars' ) if name not in available : raise ValueError ( 'Unknown avatar provider: {0}' . format ( name ) ) return available [ name ]
Get the current provider from config
247,148
def generate_pydenticon ( identifier , size ) : blocks_size = get_internal_config ( 'size' ) foreground = get_internal_config ( 'foreground' ) background = get_internal_config ( 'background' ) generator = pydenticon . Generator ( blocks_size , blocks_size , digest = hashlib . sha1 , foreground = foreground , background...
Use pydenticon to generate an identicon image . All parameters are extracted from configuration .
247,149
def adorable ( identifier , size ) : url = ADORABLE_AVATARS_URL . format ( identifier = identifier , size = size ) return redirect ( url )
Adorable Avatars provider
247,150
def licenses ( source = DEFAULT_LICENSE_FILE ) : if source . startswith ( 'http' ) : json_licenses = requests . get ( source ) . json ( ) else : with open ( source ) as fp : json_licenses = json . load ( fp ) if len ( json_licenses ) : log . info ( 'Dropping existing licenses' ) License . drop_collection ( ) for json_l...
Feed the licenses from a JSON file
247,151
def fetch_objects ( self , geoids ) : zones = [ ] no_match = [ ] for geoid in geoids : zone = GeoZone . objects . resolve ( geoid ) if zone : zones . append ( zone ) else : no_match . append ( geoid ) if no_match : msg = _ ( 'Unknown geoid(s): {identifiers}' ) . format ( identifiers = ', ' . join ( str ( id ) for id in...
Custom object retrieval .
247,152
def lrun ( command , * args , ** kwargs ) : return run ( 'cd {0} && {1}' . format ( ROOT , command ) , * args , ** kwargs )
Run a local command from project root
247,153
def initialize ( self ) : fmt = guess_format ( self . source . url ) if not fmt : response = requests . head ( self . source . url ) mime_type = response . headers . get ( 'Content-Type' , '' ) . split ( ';' , 1 ) [ 0 ] if not mime_type : msg = 'Unable to detect format from extension or mime type' raise ValueError ( ms...
List all datasets for a given ...
247,154
def get_tasks ( ) : return { name : get_task_queue ( name , cls ) for name , cls in celery . tasks . items ( ) if not name . startswith ( 'celery.' ) and not name . startswith ( 'test-' ) }
Get a list of known tasks with their routing queue
247,155
def tasks ( ) : tasks = get_tasks ( ) longest = max ( tasks . keys ( ) , key = len ) size = len ( longest ) for name , queue in sorted ( tasks . items ( ) ) : print ( '* {0}: {1}' . format ( name . ljust ( size ) , queue ) )
Display registered tasks with their queue
247,156
def status ( queue , munin , munin_config ) : if munin_config : return status_print_config ( queue ) queues = get_queues ( queue ) for queue in queues : status_print_queue ( queue , munin = munin ) if not munin : print ( '-' * 40 )
List queued tasks aggregated by name
247,157
def pre_validate ( self , form ) : for preprocessor in self . _preprocessors : preprocessor ( form , self ) super ( FieldHelper , self ) . pre_validate ( form )
Calls preprocessors before pre_validation
247,158
def process_formdata ( self , valuelist ) : super ( EmptyNone , self ) . process_formdata ( valuelist ) self . data = self . data or None
Replace empty values by None
247,159
def fetch_objects ( self , oids ) : objects = self . model . objects . in_bulk ( oids ) if len ( objects . keys ( ) ) != len ( oids ) : non_existants = set ( oids ) - set ( objects . keys ( ) ) msg = _ ( 'Unknown identifiers: {identifiers}' ) . format ( identifiers = ', ' . join ( str ( ne ) for ne in non_existants ) )...
This methods is used to fetch models from a list of identifiers .
247,160
def validate ( self , form , extra_validators = tuple ( ) ) : if not self . has_data : return True if self . is_list_data : if not isinstance ( self . _formdata [ self . name ] , ( list , tuple ) ) : return False return super ( NestedModelList , self ) . validate ( form , extra_validators )
Perform validation only if data has been submitted
247,161
def _add_entry ( self , formdata = None , data = unset_value , index = None ) : if formdata : prefix = '-' . join ( ( self . name , str ( index ) ) ) basekey = '-' . join ( ( prefix , '{0}' ) ) idkey = basekey . format ( 'id' ) if prefix in formdata : formdata [ idkey ] = formdata . pop ( prefix ) if hasattr ( self . n...
Fill the form with previous data if necessary to handle partial update
247,162
def parse ( self , data ) : self . field_errors = { } return dict ( ( k , self . _parse_value ( k , v ) ) for k , v in data . items ( ) )
Parse fields and store individual errors
247,163
def update ( site = False , organizations = False , users = False , datasets = False , reuses = False ) : do_all = not any ( ( site , organizations , users , datasets , reuses ) ) if do_all or site : log . info ( 'Update site metrics' ) update_site_metrics ( ) if do_all or datasets : log . info ( 'Update datasets metri...
Update all metrics for the current date
247,164
def list ( ) : for cls , metrics in metric_catalog . items ( ) : echo ( white ( cls . __name__ ) ) for metric in metrics . keys ( ) : echo ( '> {0}' . format ( metric ) )
List all known metrics
247,165
def json_to_file ( data , filename , pretty = False ) : kwargs = dict ( indent = 4 ) if pretty else { } dirname = os . path . dirname ( filename ) if not os . path . exists ( dirname ) : os . makedirs ( dirname ) dump = json . dumps ( api . __schema__ , ** kwargs ) with open ( filename , 'wb' ) as f : f . write ( dump ...
Dump JSON data to a file
247,166
def postman ( filename , pretty , urlvars , swagger ) : data = api . as_postman ( urlvars = urlvars , swagger = swagger ) json_to_file ( data , filename , pretty )
Dump the API as a Postman collection
247,167
def notify_badge_added_certified ( sender , kind = '' ) : if kind == CERTIFIED and isinstance ( sender , Organization ) : recipients = [ member . user for member in sender . members ] subject = _ ( 'Your organization "%(name)s" has been certified' , name = sender . name ) mail . send ( subject , recipients , 'badge_add...
Send an email when a CERTIFIED badge is added to an Organization
247,168
def discussions_notifications ( user ) : notifications = [ ] qs = discussions_for ( user ) . only ( 'id' , 'created' , 'title' , 'subject' ) for discussion in qs . no_dereference ( ) : notifications . append ( ( discussion . created , { 'id' : discussion . id , 'title' : discussion . title , 'subject' : { 'id' : discus...
Notify user about open discussions
247,169
def send_signal ( signal , request , user , ** kwargs ) : params = { 'user_ip' : request . remote_addr } params . update ( kwargs ) if user . is_authenticated : params [ 'uid' ] = user . id signal . send ( request . url , ** params )
Generic method to send signals to Piwik
247,170
def membership_request_notifications ( user ) : orgs = [ o for o in user . organizations if o . is_admin ( user ) ] notifications = [ ] for org in orgs : for request in org . pending_requests : notifications . append ( ( request . created , { 'id' : request . id , 'organization' : org . id , 'user' : { 'id' : request ....
Notify user about pending membership requests
247,171
def validate ( identifier ) : source = actions . validate_source ( identifier ) log . info ( 'Source %s (%s) has been validated' , source . slug , str ( source . id ) )
Validate a source given its identifier
247,172
def delete ( identifier ) : log . info ( 'Deleting source "%s"' , identifier ) actions . delete_source ( identifier ) log . info ( 'Deleted source "%s"' , identifier )
Delete a harvest source
247,173
def sources ( scheduled = False ) : sources = actions . list_sources ( ) if scheduled : sources = [ s for s in sources if s . periodic_task ] if sources : for source in sources : msg = '{source.name} ({source.backend}): {cron}' if source . periodic_task : cron = source . periodic_task . schedule_display else : cron = '...
List all harvest sources
247,174
def backends ( ) : log . info ( 'Available backends:' ) for backend in actions . list_backends ( ) : log . info ( '%s (%s)' , backend . name , backend . display_name or backend . name )
List available backends
247,175
def schedule ( identifier , ** kwargs ) : source = actions . schedule ( identifier , ** kwargs ) msg = 'Scheduled {source.name} with the following crontab: {cron}' log . info ( msg . format ( source = source , cron = source . periodic_task . crontab ) )
Schedule a harvest job to run periodically
247,176
def unschedule ( identifier ) : source = actions . unschedule ( identifier ) log . info ( 'Unscheduled harvest source "%s"' , source . name )
Unschedule a periodical harvest job
247,177
def attach ( domain , filename ) : log . info ( 'Attaching datasets for domain %s' , domain ) result = actions . attach ( domain , filename ) log . info ( 'Attached %s datasets to %s' , result . success , domain )
Attach existing datasets to their harvest remote id
247,178
def request_transfer ( subject , recipient , comment ) : TransferPermission ( subject ) . test ( ) if recipient == ( subject . organization or subject . owner ) : raise ValueError ( 'Recipient should be different than the current owner' ) transfer = Transfer . objects . create ( owner = subject . organization or subjec...
Initiate a transfer request
247,179
def accept_transfer ( transfer , comment = None ) : TransferResponsePermission ( transfer ) . test ( ) transfer . responded = datetime . now ( ) transfer . responder = current_user . _get_current_object ( ) transfer . status = 'accepted' transfer . response_comment = comment transfer . save ( ) subject = transfer . sub...
Accept an incoming a transfer request
247,180
def refuse_transfer ( transfer , comment = None ) : TransferResponsePermission ( transfer ) . test ( ) transfer . responded = datetime . now ( ) transfer . responder = current_user . _get_current_object ( ) transfer . status = 'refused' transfer . response_comment = comment transfer . save ( ) return transfer
Refuse an incoming a transfer request
247,181
def clean ( self ) : if not self . metrics : self . metrics = dict ( ( name , spec . default ) for name , spec in ( metric_catalog . get ( self . __class__ , { } ) . items ( ) ) ) return super ( WithMetrics , self ) . clean ( )
Fill metrics with defaults on create
247,182
def build_catalog ( site , datasets , format = None ) : site_url = url_for ( 'site.home_redirect' , _external = True ) catalog_url = url_for ( 'site.rdf_catalog' , _external = True ) graph = Graph ( namespace_manager = namespace_manager ) catalog = graph . resource ( URIRef ( catalog_url ) ) catalog . set ( RDF . type ...
Build the DCAT catalog for this site
247,183
def sendmail_proxy ( subject , email , template , ** context ) : sendmail . delay ( subject . value , email , template , ** context )
Cast the lazy_gettext ed subject to string before passing to Celery
247,184
def collect ( path , no_input ) : if exists ( path ) : msg = '"%s" directory already exists and will be erased' log . warning ( msg , path ) if not no_input : click . confirm ( 'Are you sure?' , abort = True ) log . info ( 'Deleting static directory "%s"' , path ) shutil . rmtree ( path ) prefix = current_app . static_...
Collect static files
247,185
def validate_harvester_notifications ( user ) : if not user . sysadmin : return [ ] notifications = [ ] qs = HarvestSource . objects ( validation__state = VALIDATION_PENDING ) qs = qs . only ( 'id' , 'created_at' , 'name' ) for source in qs : notifications . append ( ( source . created_at , { 'id' : source . id , 'name...
Notify admins about pending harvester validation
247,186
def get ( app , name ) : backend = get_all ( app ) . get ( name ) if not backend : msg = 'Harvest backend "{0}" is not registered' . format ( name ) raise EntrypointError ( msg ) return backend
Get a backend given its name
247,187
def search ( self ) : s = super ( TopicSearchMixin , self ) . search ( ) s = s . filter ( 'bool' , should = [ Q ( 'term' , tags = tag ) for tag in self . topic . tags ] ) return s
Override search to match on topic tags
247,188
def clean ( self ) : if not self . urlhash or 'url' in self . _get_changed_fields ( ) : self . urlhash = hash_url ( self . url ) super ( Reuse , self ) . clean ( )
Auto populate urlhash from url
247,189
def serve ( info , host , port , reload , debugger , eager_loading , with_threads ) : logger = logging . getLogger ( 'werkzeug' ) logger . setLevel ( logging . INFO ) logger . handlers = [ ] debug = current_app . config [ 'DEBUG' ] if reload is None : reload = bool ( debug ) if debugger is None : debugger = bool ( debu...
Runs a local udata development server .
247,190
def enforce_filetype_file ( form , field ) : if form . _fields . get ( 'filetype' ) . data != RESOURCE_FILETYPE_FILE : return domain = urlparse ( field . data ) . netloc allowed_domains = current_app . config [ 'RESOURCES_FILE_ALLOWED_DOMAINS' ] allowed_domains += [ current_app . config . get ( 'SERVER_NAME' ) ] if cur...
Only allowed domains in resource . url when filetype is file
247,191
def map_legacy_frequencies ( form , field ) : if field . data in LEGACY_FREQUENCIES : field . data = LEGACY_FREQUENCIES [ field . data ]
Map legacy frequencies to new ones
247,192
def resources_availability ( self ) : availabilities = list ( chain ( * [ org . check_availability ( ) for org in self . organizations ] ) ) availabilities = [ a for a in availabilities if type ( a ) is bool ] if availabilities : return round ( 100. * sum ( availabilities ) / len ( availabilities ) , 2 ) return 100
Return the percentage of availability for resources .
247,193
def datasets_org_count ( self ) : from udata . models import Dataset return sum ( Dataset . objects ( organization = org ) . visible ( ) . count ( ) for org in self . organizations )
Return the number of datasets of user s organizations .
247,194
def followers_org_count ( self ) : from udata . models import Follow return sum ( Follow . objects ( following = org ) . count ( ) for org in self . organizations )
Return the number of followers of user s organizations .
247,195
def get_badge ( self , kind ) : candidates = [ b for b in self . badges if b . kind == kind ] return candidates [ 0 ] if candidates else None
Get a badge given its kind if present
247,196
def add_badge ( self , kind ) : badge = self . get_badge ( kind ) if badge : return badge if kind not in getattr ( self , '__badges__' , { } ) : msg = 'Unknown badge type for {model}: {kind}' raise db . ValidationError ( msg . format ( model = self . __class__ . __name__ , kind = kind ) ) badge = Badge ( kind = kind ) ...
Perform an atomic prepend for a new badge
247,197
def remove_badge ( self , kind ) : self . update ( __raw__ = { '$pull' : { 'badges' : { 'kind' : kind } } } ) self . reload ( ) on_badge_removed . send ( self , kind = kind ) post_save . send ( self . __class__ , document = self )
Perform an atomic removal for a given badge
247,198
def toggle_badge ( self , kind ) : badge = self . get_badge ( kind ) if badge : return self . remove_badge ( kind ) else : return self . add_badge ( kind )
Toggle a bdage given its kind
247,199
def badge_label ( self , badge ) : kind = badge . kind if isinstance ( badge , Badge ) else badge return self . __badges__ [ kind ]
Display the badge label for a given kind