idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
246,100
def is_code_unit ( self ) : for atom in self . expr . atoms ( ) : if not ( str ( atom ) . startswith ( "code" ) or atom . is_Number ) : return False return True
Is this a code unit?
49
6
246,101
def list_equivalencies ( self ) : from unyt . equivalencies import equivalence_registry for k , v in equivalence_registry . items ( ) : if self . has_equivalent ( k ) : print ( v ( ) )
Lists the possible equivalencies associated with this unit object
54
11
246,102
def get_base_equivalent ( self , unit_system = None ) : from unyt . unit_registry import _sanitize_unit_system unit_system = _sanitize_unit_system ( unit_system , self ) try : conv_data = _check_em_conversion ( self . units , registry = self . registry , unit_system = unit_system ) except MKSCGSConversionError : raise UnitsNotReducible ( self . units , unit_system ) if any ( conv_data ) : new_units , _ = _em_conversion ( self , conv_data , unit_system = unit_system ) else : try : new_units = unit_system [ self . dimensions ] except MissingMKSCurrent : raise UnitsNotReducible ( self . units , unit_system ) return Unit ( new_units , registry = self . registry )
Create and return dimensionally - equivalent units in a specified base .
192
13
246,103
def as_coeff_unit ( self ) : coeff , mul = self . expr . as_coeff_Mul ( ) coeff = float ( coeff ) ret = Unit ( mul , self . base_value / coeff , self . base_offset , self . dimensions , self . registry , ) return coeff , ret
Factor the coefficient multiplying a unit
72
6
246,104
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
30
11
246,105
def _auto_positive_symbol ( tokens , local_dict , global_dict ) : result = [ ] tokens . append ( ( None , None ) ) # so zip traverses all tokens 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 ] if isinstance ( obj , ( Basic , type ) ) or callable ( obj ) : result . append ( ( token . NAME , name ) ) continue # try to resolve known alternative unit name try : used_name = inv_name_alternatives [ str ( name ) ] except KeyError : # if we don't know this name it's a user-defined unit name # so we should create a new symbol for it used_name = str ( name ) result . extend ( [ ( token . NAME , "Symbol" ) , ( token . OP , "(" ) , ( token . NAME , repr ( used_name ) ) , ( token . OP , "," ) , ( token . NAME , "positive" ) , ( token . OP , "=" ) , ( token . NAME , "True" ) , ( token . OP , ")" ) , ] ) else : result . append ( ( tokNum , tokVal ) ) return result
Inserts calls to Symbol for undefined variables . Passes in positive = True as a keyword argument . Adapted from sympy . sympy . parsing . sympy_parser . auto_symbol
309
40
246,106
def intersection ( self , range ) : if self . worksheet != range . worksheet : # Different 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 [ 0 ] < start [ 0 ] or end [ 1 ] < start [ 1 ] : return None return Range ( start , end , self . worksheet , validate = False )
Calculates the intersection with another range object
146
9
246,107
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 .
64
15
246,108
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_delay : max_delay = delay self . _do_open ( ) watch = _utils . StopWatch ( duration = timeout ) r = _utils . Retry ( delay , max_delay , sleep_func = self . sleep_func , watch = watch ) with watch : gotten = r ( self . _try_acquire , blocking , watch ) if not gotten : self . acquired = False return False else : self . acquired = True self . logger . log ( _utils . BLATHER , "Acquired file lock `%s` after waiting %0.3fs [%s" " attempts were required]" , self . path , watch . elapsed ( ) , r . attempts ) return True
Attempt to acquire the given lock .
233
7
246,109
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 ( ) except IOError : self . logger . exception ( "Could not close the file handle" " opened on `%s`" , self . path ) else : self . logger . log ( _utils . BLATHER , "Unlocked and closed file lock open on" " `%s`" , self . path )
Release the previously acquired lock .
154
6
246,110
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 .
58
8
246,111
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 # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args : return decorator else : if len ( args ) == 1 : return decorator ( args [ 0 ] ) else : return decorator
Acquires & releases a read lock around call into decorated method .
170
14
246,112
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 # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args : return decorator else : if len ( args ) == 1 : return decorator ( args [ 0 ] ) else : return decorator
Acquires & releases a write lock around call into decorated method .
170
14
246,113
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 .
55
13
246,114
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 .
35
12
246,115
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 : # No active writer, or we are the writer; # we are good to become a reader. if self . _writer is None or self . _writer == me : try : self . _readers [ me ] = self . _readers [ me ] + 1 except KeyError : self . _readers [ me ] = 1 break # An active writer; guess we have to wait. self . _cond . wait ( ) try : yield self finally : # I am no longer a reader, remove *one* occurrence of myself. # If the current thread acquired two read locks, then it will # still have to remove that other read lock; this allows for # basic reentrancy to be possible. with self . _cond : try : me_instances = self . _readers [ me ] if me_instances > 1 : self . _readers [ me ] = me_instances - 1 else : self . _readers . pop ( me ) except KeyError : pass self . _cond . notify_all ( )
Context manager that grants a read lock .
283
8
246,116
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 : # Already the writer; this allows for basic reentrancy. yield self else : with self . _cond : self . _pending_writers . append ( me ) while True : # No readers, and no active writer, am I next?? if len ( self . _readers ) == 0 and self . _writer is None : if self . _pending_writers [ 0 ] == me : self . _writer = self . _pending_writers . popleft ( ) break self . _cond . wait ( ) try : yield self finally : with self . _cond : self . _writer = None self . _cond . notify_all ( )
Context manager that grants a write lock .
220
8
246,117
def send_sms ( self , text , * * kw ) : params = { 'user' : self . _user , 'pass' : self . _passwd , 'msg' : text } kw . setdefault ( "verify" , False ) if not kw [ "verify" ] : # remove SSL warning requests . packages . urllib3 . disable_warnings ( InsecureRequestWarning ) res = requests . get ( FreeClient . BASE_URL , params = params , * * kw ) return FreeResponse ( res . status_code )
Send an SMS . Since Free only allows us to send SMSes to ourselves you don t have to provide your phone number .
123
25
246,118
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
76
10
246,119
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: {} items written.' . format ( self . get_metadata ( 'items_count' ) ) ) self . logger . debug ( 'Wrote items' )
Receives the batch and writes it . This method is usually called from a manager .
122
18
246,120
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 ( 'items_count' ) ) ) * 100 } return agg_results
Keeps track of aggregated info in a dictionary called self . aggregated_info
120
17
246,121
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","id":%s,"fields":%s}' % ( json . dumps ( key ) , line ) current_size = fixed_initial_size for line in jsonlines : entry = create_entry ( line ) entry_size = len ( entry ) + 1 if max_batch_size > ( current_size + entry_size ) : current_size += entry_size batch . append ( entry ) else : yield '[' + ',' . join ( batch ) + ']' batch = [ entry ] current_size = fixed_initial_size + entry_size if batch : yield '[' + ',' . join ( batch ) + ']'
Create batches in expected AWS Cloudsearch format limiting the byte size per batch according to given max_batch_size
234
22
246,122
def _post_document_batch ( self , batch ) : # noqa 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
70
7
246,123
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
38
10
246,124
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 .
42
13
246,125
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 \ be alphanumeric and contain between 16 and 32 characters.' ) if len ( aws_access_key_id ) > len ( aws_secret_access_key ) : logging . warn ( "The AWS credential keys aren't in the usual size," " are you using the correct ones?" ) import boto from boto . s3 . connection import OrdinaryCallingFormat extra_args = { } if host is not None : extra_args [ 'host' ] = host if bucketname is not None and '.' in bucketname : extra_args [ 'calling_format' ] = OrdinaryCallingFormat ( ) if region is None : return boto . connect_s3 ( aws_access_key_id , aws_secret_access_key , * * extra_args ) return boto . s3 . connect_to_region ( region , aws_access_key_id = aws_access_key_id , aws_secret_access_key = aws_secret_access_key , * * extra_args )
Conection parameters must be different only if bucket name has a period
337
13
246,126
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 .
83
15
246,127
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
39
14
246,128
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 .
32
59
246,129
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
93
9
246,130
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
53
13
246,131
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_state_id = file_path . split ( os . path . sep ) [ - 1 ] configuration [ 'exporter_options' ] [ 'persistence_state_id' ] = persistence_state_id return configuration
returns a configuration object .
143
6
246,132
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 .
96
8
246,133
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' , 'database' } - set ( conn_params ) if missing : raise ValueError ( 'Missing required parameters: %s (given params: %s)' % ( tuple ( missing ) , conn_params ) ) persistence_state_id = int ( conn_params . pop ( 'job_id' ) ) db_uri = cls . build_db_conn_uri ( * * conn_params ) return db_uri , persistence_state_id
Parse a database URI and the persistence state ID from the given persistence URI
191
15
246,134
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 = session . query ( Job ) . filter ( Job . id == persistence_state_id ) . first ( ) configuration = job . configuration configuration = yaml . safe_load ( configuration ) configuration [ 'exporter_options' ] [ 'resume' ] = True configuration [ 'exporter_options' ] [ 'persistence_state_id' ] = persistence_state_id return configuration
Return a configuration object .
169
5
246,135
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_unit in input_specification : if isinstance ( input_unit , basestring ) : out . append ( input_unit ) elif isinstance ( input_unit , dict ) : missing = object ( ) directory = input_unit . get ( 'dir' , missing ) dir_pointer = input_unit . get ( 'dir_pointer' , missing ) if directory is missing and dir_pointer is missing : raise ConfigurationError ( 'Input directory dict must contain' ' "dir" or "dir_pointer" element (but not both)' ) if directory is not missing and dir_pointer is not missing : raise ConfigurationError ( 'Input directory dict must not contain' ' both "dir" and "dir_pointer" elements' ) if dir_pointer is not missing : directory = cls . _get_pointer ( dir_pointer ) out . extend ( cls . _get_directory_files ( directory = directory , pattern = input_unit . get ( 'pattern' ) , include_dot_files = input_unit . get ( 'include_dot_files' , False ) ) ) else : raise ConfigurationError ( 'Input must only contain strings or dicts' ) return out
Get list of input files according to input definition .
334
10
246,136
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
62
6
246,137
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 .
44
22
246,138
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 .
69
11
246,139
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 .
95
13
246,140
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 .
75
15
246,141
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 .
47
8
246,142
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
58
10
246,143
def register_manifest ( app , filename = 'manifest.json' ) : if current_app . config . get ( 'TESTING' ) : return # Do not spend time here when testing if not has_manifest ( app , filename ) : msg = '{filename} not found for {app}' . format ( * * locals ( ) ) raise ValueError ( msg ) manifest = _manifests . get ( app , { } ) manifest . update ( load_manifest ( app , filename ) ) _manifests [ app ] = manifest
Register an assets json manifest
120
5
246,144
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 data
Load an assets json manifest
93
5
246,145
def from_manifest ( app , filename , raw = False , * * kwargs ) : cfg = current_app . config if current_app . config . get ( 'TESTING' ) : return # Do not spend time here when testing 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 . scheme prefix = '{}://' . format ( scheme ) if not path . startswith ( '/' ) : # CDN_DOMAIN has no trailing slash path = '/' + path return '' . join ( ( prefix , cfg [ 'CDN_DOMAIN' ] , path ) ) elif not raw and kwargs . get ( 'external' , False ) : if path . startswith ( '/' ) : # request.host_url has a trailing slash path = path [ 1 : ] return '' . join ( ( request . host_url , path ) ) return path
Get the path to a static file for a given app entry of a given type .
247
17
246,146
def cdn_for ( endpoint , * * kwargs ) : if current_app . config [ 'CDN_DOMAIN' ] : if not current_app . config . get ( 'CDN_DEBUG' ) : kwargs . pop ( '_external' , None ) # Avoid the _external parameter in URL return cdn_url_for ( endpoint , * * kwargs ) return url_for ( endpoint , * * kwargs )
Get a CDN URL for a static assets .
99
10
246,147
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 : doc . save ( write_concern = write_concern ) return doc , True
Retrieve unique object or create if it doesn t exist .
120
12
246,148
def generic_in ( self , * * kwargs ) : query = { } for key , value in kwargs . items ( ) : if not value : continue # Optimize query for when there is only one value 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 = [ ObjectId ( v ) for v in value ] query [ '{0}._ref.$id' . format ( key ) ] = { '$in' : ids } elif all ( isinstance ( v , DBRef ) for v in value ) : query [ '{0}._ref' . format ( key ) ] = { '$in' : value } elif all ( isinstance ( v , ObjectId ) for v in value ) : query [ '{0}._ref.$id' . format ( key ) ] = { '$in' : value } elif isinstance ( value , ObjectId ) : query [ '{0}._ref.$id' . format ( key ) ] = value elif isinstance ( value , basestring ) : query [ '{0}._ref.$id' . format ( key ) ] = ObjectId ( value ) else : self . error ( 'expect a list of string, ObjectId or DBRef' ) return self ( __raw__ = query )
Bypass buggy GenericReferenceField querying issue
326
9
246,149
def issues_notifications ( user ) : notifications = [ ] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = issues_for ( user ) . only ( 'id' , 'title' , 'created' , 'subject' ) # Do not dereference subject (so it's a DBRef) # Also improve performances and memory usage for issue in qs . no_dereference ( ) : notifications . append ( ( issue . created , { 'id' : issue . id , 'title' : issue . title , 'subject' : { 'id' : issue . subject [ '_ref' ] . id , 'type' : issue . subject [ '_cls' ] . lower ( ) , } } ) ) return notifications
Notify user about open issues
165
6
246,150
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 .
62
7
246,151
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
66
6
246,152
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 = background ) # Pydenticon adds padding to the size and as a consequence # we need to compute the size without the padding padding = int ( round ( get_internal_config ( 'padding' ) * size / 100. ) ) size = size - 2 * padding padding = ( padding , ) * 4 return generator . generate ( identifier , size , size , padding = padding , output_format = 'png' )
Use pydenticon to generate an identicon image . All parameters are extracted from configuration .
171
19
246,153
def adorable ( identifier , size ) : url = ADORABLE_AVATARS_URL . format ( identifier = identifier , size = size ) return redirect ( url )
Adorable Avatars provider
35
5
246,154
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_license in json_licenses : flags = [ ] for field , flag in FLAGS_MAP . items ( ) : if json_license . get ( field , False ) : flags . append ( flag ) license = License . objects . create ( id = json_license [ 'id' ] , title = json_license [ 'title' ] , url = json_license [ 'url' ] or None , maintainer = json_license [ 'maintainer' ] or None , flags = flags , active = json_license . get ( 'active' , False ) , alternate_urls = json_license . get ( 'alternate_urls' , [ ] ) , alternate_titles = json_license . get ( 'alternate_titles' , [ ] ) , ) log . info ( 'Added license "%s"' , license . title ) try : License . objects . get ( id = DEFAULT_LICENSE [ 'id' ] ) except License . DoesNotExist : License . objects . create ( * * DEFAULT_LICENSE ) log . info ( 'Added license "%s"' , DEFAULT_LICENSE [ 'title' ] ) success ( 'Done' )
Feed the licenses from a JSON file
353
7
246,155
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 no_match ) ) raise validators . ValidationError ( msg ) return zones
Custom object retrieval .
116
4
246,156
def lrun ( command , * args , * * kwargs ) : return run ( 'cd {0} && {1}' . format ( ROOT , command ) , * args , * * kwargs )
Run a local command from project root
47
7
246,157
def initialize ( self ) : fmt = guess_format ( self . source . url ) # if format can't be guessed from the url # we fallback on the declared Content-Type 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 ( msg ) fmt = guess_format ( mime_type ) if not fmt : msg = 'Unsupported mime type "{0}"' . format ( mime_type ) raise ValueError ( msg ) graph = self . parse_graph ( self . source . url , fmt ) self . job . data = { 'graph' : graph . serialize ( format = 'json-ld' , indent = None ) }
List all datasets for a given ...
199
7
246,158
def get_tasks ( ) : return { name : get_task_queue ( name , cls ) for name , cls in celery . tasks . items ( ) # Exclude celery internal tasks if not name . startswith ( 'celery.' ) # Exclude udata test tasks and not name . startswith ( 'test-' ) }
Get a list of known tasks with their routing queue
77
10
246,159
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
72
6
246,160
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
69
8
246,161
def pre_validate ( self , form ) : for preprocessor in self . _preprocessors : preprocessor ( form , self ) super ( FieldHelper , self ) . pre_validate ( form )
Calls preprocessors before pre_validation
44
10
246,162
def process_formdata ( self , valuelist ) : super ( EmptyNone , self ) . process_formdata ( valuelist ) self . data = self . data or None
Replace empty values by None
39
6
246,163
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 ) ) raise validators . ValidationError ( msg ) return [ objects [ id ] for id in oids ]
This methods is used to fetch models from a list of identifiers .
121
13
246,164
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
81
9
246,165
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 . nested_model , 'id' ) and idkey in formdata : id = self . nested_model . id . to_python ( formdata [ idkey ] ) data = get_by ( self . initial_data , 'id' , id ) initial = flatten_json ( self . nested_form , data . to_mongo ( ) , prefix ) for key , value in initial . items ( ) : if key not in formdata : formdata [ key ] = value else : data = None return super ( NestedModelList , self ) . _add_entry ( formdata , data , index )
Fill the form with previous data if necessary to handle partial update
234
12
246,166
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
45
7
246,167
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 metrics' ) for dataset in Dataset . objects . timeout ( False ) : update_metrics_for ( dataset ) if do_all or reuses : log . info ( 'Update reuses metrics' ) for reuse in Reuse . objects . timeout ( False ) : update_metrics_for ( reuse ) if do_all or organizations : log . info ( 'Update organizations metrics' ) for organization in Organization . objects . timeout ( False ) : update_metrics_for ( organization ) if do_all or users : log . info ( 'Update user metrics' ) for user in User . objects . timeout ( False ) : update_metrics_for ( user ) success ( 'All metrics have been updated' )
Update all metrics for the current date
237
7
246,168
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
55
4
246,169
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 . encode ( 'utf-8' ) )
Dump JSON data to a file
110
7
246,170
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
51
9
246,171
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_added_certified' , organization = sender , badge = sender . get_badge ( kind ) )
Send an email when a CERTIFIED badge is added to an Organization
104
14
246,172
def discussions_notifications ( user ) : notifications = [ ] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = discussions_for ( user ) . only ( 'id' , 'created' , 'title' , 'subject' ) # Do not dereference subject (so it's a DBRef) # Also improve performances and memory usage for discussion in qs . no_dereference ( ) : notifications . append ( ( discussion . created , { 'id' : discussion . id , 'title' : discussion . title , 'subject' : { 'id' : discussion . subject [ '_ref' ] . id , 'type' : discussion . subject [ '_cls' ] . lower ( ) , } } ) ) return notifications
Notify user about open discussions
165
6
246,173
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
72
8
246,174
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 . user . id , 'fullname' : request . user . fullname , 'avatar' : str ( request . user . avatar ) } } ) ) return notifications
Notify user about pending membership requests
125
7
246,175
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
43
7
246,176
def delete ( identifier ) : log . info ( 'Deleting source "%s"' , identifier ) actions . delete_source ( identifier ) log . info ( 'Deleted source "%s"' , identifier )
Delete a harvest source
43
4
246,177
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 = 'not scheduled' log . info ( msg . format ( source = source , cron = cron ) ) elif scheduled : log . info ( 'No sources scheduled yet' ) else : log . info ( 'No sources defined yet' )
List all harvest sources
139
4
246,178
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
53
4
246,179
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
75
8
246,180
def unschedule ( identifier ) : source = actions . unschedule ( identifier ) log . info ( 'Unscheduled harvest source "%s"' , source . name )
Unschedule a periodical harvest job
37
8
246,181
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
55
8
246,182
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 subject . owner , recipient = recipient , subject = subject , comment = comment ) return transfer
Initiate a transfer request
83
6
246,183
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 . subject recipient = transfer . recipient if isinstance ( recipient , Organization ) : subject . organization = recipient elif isinstance ( recipient , User ) : subject . owner = recipient subject . save ( ) return transfer
Accept an incoming a transfer request
116
6
246,184
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
72
7
246,185
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
66
6
246,186
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 , DCAT . Catalog ) catalog . set ( DCT . title , Literal ( site . title ) ) catalog . set ( DCT . language , Literal ( current_app . config [ 'DEFAULT_LANGUAGE' ] ) ) catalog . set ( FOAF . homepage , URIRef ( site_url ) ) publisher = graph . resource ( BNode ( ) ) publisher . set ( RDF . type , FOAF . Organization ) publisher . set ( FOAF . name , Literal ( current_app . config [ 'SITE_AUTHOR' ] ) ) catalog . set ( DCT . publisher , publisher ) for dataset in datasets : catalog . add ( DCAT . dataset , dataset_to_rdf ( dataset , graph ) ) if isinstance ( datasets , Paginable ) : if not format : raise ValueError ( 'Pagination requires format' ) catalog . add ( RDF . type , HYDRA . Collection ) catalog . set ( HYDRA . totalItems , Literal ( datasets . total ) ) kwargs = { 'format' : format , 'page_size' : datasets . page_size , '_external' : True , } first_url = url_for ( 'site.rdf_catalog_format' , page = 1 , * * kwargs ) page_url = url_for ( 'site.rdf_catalog_format' , page = datasets . page , * * kwargs ) last_url = url_for ( 'site.rdf_catalog_format' , page = datasets . pages , * * kwargs ) pagination = graph . resource ( URIRef ( page_url ) ) pagination . set ( RDF . type , HYDRA . PartialCollectionView ) pagination . set ( HYDRA . first , URIRef ( first_url ) ) pagination . set ( HYDRA . last , URIRef ( last_url ) ) if datasets . has_next : next_url = url_for ( 'site.rdf_catalog_format' , page = datasets . page + 1 , * * kwargs ) pagination . set ( HYDRA . next , URIRef ( next_url ) ) if datasets . has_prev : prev_url = url_for ( 'site.rdf_catalog_format' , page = datasets . page - 1 , * * kwargs ) pagination . set ( HYDRA . previous , URIRef ( prev_url ) ) catalog . set ( HYDRA . view , pagination ) return catalog
Build the DCAT catalog for this site
654
8
246,187
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
34
15
246,188
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_url_path or current_app . static_folder if prefix . startswith ( '/' ) : prefix = prefix [ 1 : ] destination = join ( path , prefix ) log . info ( 'Copying application assets into "%s"' , destination ) shutil . copytree ( current_app . static_folder , destination ) for blueprint in current_app . blueprints . values ( ) : if blueprint . has_static_folder : prefix = current_app . static_prefixes . get ( blueprint . name ) prefix = prefix or blueprint . url_prefix or '' prefix += blueprint . static_url_path or '' if prefix . startswith ( '/' ) : prefix = prefix [ 1 : ] log . info ( 'Copying %s assets to %s' , blueprint . name , prefix ) destination = join ( path , prefix ) copy_recursive ( blueprint . static_folder , destination ) for prefix , source in current_app . config [ 'STATIC_DIRS' ] : log . info ( 'Copying %s to %s' , source , prefix ) destination = join ( path , prefix ) copy_recursive ( source , destination ) log . info ( 'Done' )
Collect static files
346
3
246,189
def validate_harvester_notifications ( user ) : if not user . sysadmin : return [ ] notifications = [ ] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage 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' : source . name , } ) ) return notifications
Notify admins about pending harvester validation
125
9
246,190
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
52
6
246,191
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
56
7
246,192
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
52
6
246,193
def serve ( info , host , port , reload , debugger , eager_loading , with_threads ) : # Werkzeug logger is special and is required # with this configuration for development server 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 ( debug ) if eager_loading is None : eager_loading = not reload app = DispatchingApp ( info . load_app , use_eager_loading = eager_loading ) settings = os . environ . get ( 'UDATA_SETTINGS' , os . path . join ( os . getcwd ( ) , 'udata.cfg' ) ) extra_files = [ settings ] if reload : extra_files . extend ( assets . manifests_paths ( ) ) run_simple ( host , port , app , use_reloader = reload , use_debugger = debugger , threaded = with_threads , extra_files = extra_files )
Runs a local udata development server .
245
9
246,194
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 current_app . config . get ( 'CDN_DOMAIN' ) : allowed_domains . append ( current_app . config [ 'CDN_DOMAIN' ] ) if '*' in allowed_domains : return if domain and domain not in allowed_domains : message = _ ( 'Domain "{domain}" not allowed for filetype "{filetype}"' ) raise validators . ValidationError ( message . format ( domain = domain , filetype = RESOURCE_FILETYPE_FILE ) )
Only allowed domains in resource . url when filetype is file
210
12
246,195
def map_legacy_frequencies ( form , field ) : if field . data in LEGACY_FREQUENCIES : field . data = LEGACY_FREQUENCIES [ field . data ]
Map legacy frequencies to new ones
46
6
246,196
def resources_availability ( self ) : # Flatten the list. availabilities = list ( chain ( * [ org . check_availability ( ) for org in self . organizations ] ) ) # Filter out the unknown availabilities = [ a for a in availabilities if type ( a ) is bool ] if availabilities : # Trick will work because it's a sum() of booleans. return round ( 100. * sum ( availabilities ) / len ( availabilities ) , 2 ) # if nothing is unavailable, everything is considered OK return 100
Return the percentage of availability for resources .
113
8
246,197
def datasets_org_count ( self ) : from udata . models import Dataset # Circular imports. return sum ( Dataset . objects ( organization = org ) . visible ( ) . count ( ) for org in self . organizations )
Return the number of datasets of user s organizations .
52
10
246,198
def followers_org_count ( self ) : from udata . models import Follow # Circular imports. return sum ( Follow . objects ( following = org ) . count ( ) for org in self . organizations )
Return the number of followers of user s organizations .
44
10
246,199
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
37
8