idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
45,200 | def terminate ( self ) : logger . info ( __ ( "Terminating Resolwe listener on channel '{}'." , state . MANAGER_EXECUTOR_CHANNELS . queue ) ) self . _should_stop = True | Stop the standalone manager . |
45,201 | def _queue_response_channel ( self , obj ) : return '{}.{}' . format ( state . MANAGER_EXECUTOR_CHANNELS . queue_response , obj [ ExecutorProtocol . DATA_ID ] ) | Generate the feedback channel name from the object s id . |
45,202 | async def _send_reply ( self , obj , reply ) : reply . update ( { ExecutorProtocol . DATA_ID : obj [ ExecutorProtocol . DATA_ID ] , } ) await self . _call_redis ( aioredis . Redis . rpush , self . _queue_response_channel ( obj ) , json . dumps ( reply ) ) | Send a reply with added standard fields back to executor . |
45,203 | def hydrate_spawned_files ( self , exported_files_mapper , filename , data_id ) : data_id = str ( data_id ) if filename not in exported_files_mapper [ data_id ] : raise KeyError ( "Use 're-export' to prepare the file for spawned process: {}" . format ( filename ) ) export_fn = exported_files_mapper [ data_id ] . pop ( ... | Pop the given file s map from the exported files mapping . |
45,204 | def handle_abort ( self , obj ) : async_to_sync ( consumer . send_event ) ( { WorkerProtocol . COMMAND : WorkerProtocol . ABORT , WorkerProtocol . DATA_ID : obj [ ExecutorProtocol . DATA_ID ] , WorkerProtocol . FINISH_COMMUNICATE_EXTRA : { 'executor' : getattr ( settings , 'FLOW_EXECUTOR' , { } ) . get ( 'NAME' , 'reso... | Handle an incoming Data abort processing request . |
45,205 | def handle_log ( self , obj ) : record_dict = json . loads ( obj [ ExecutorProtocol . LOG_MESSAGE ] ) record_dict [ 'msg' ] = record_dict [ 'msg' ] executors_dir = os . path . join ( os . path . dirname ( os . path . dirname ( __file__ ) ) , 'executors' ) record_dict [ 'pathname' ] = os . path . join ( executors_dir , ... | Handle an incoming log processing request . |
45,206 | async def push_stats ( self ) : snapshot = self . _make_stats ( ) try : serialized = json . dumps ( snapshot ) await self . _call_redis ( aioredis . Redis . set , state . MANAGER_LISTENER_STATS , serialized ) await self . _call_redis ( aioredis . Redis . expire , state . MANAGER_LISTENER_STATS , 3600 ) except TypeError... | Push current stats to Redis . |
45,207 | def check_critical_load ( self ) : if self . load_avg . intervals [ '1m' ] . value > 1 : if self . last_load_level == 1 and time . time ( ) - self . last_load_log < 30 : return self . last_load_log = time . time ( ) self . last_load_level = 1 logger . error ( "Listener load limit exceeded, the system can't handle this!... | Check for critical load and log an error if necessary . |
45,208 | async def run ( self ) : logger . info ( __ ( "Starting Resolwe listener on channel '{}'." , state . MANAGER_EXECUTOR_CHANNELS . queue ) ) while not self . _should_stop : await self . push_stats ( ) ret = await self . _call_redis ( aioredis . Redis . blpop , state . MANAGER_EXECUTOR_CHANNELS . queue , timeout = 1 ) if ... | Run the main listener run loop . |
45,209 | def dokanMain ( self , dokanOptions , dokanOperations ) : return int ( self . dokanDLL . DokanMain ( PDOKAN_OPTIONS ( dokanOptions ) , PDOKAN_OPERATIONS ( dokanOperations ) ) ) | Issue callback to start dokan drive . |
45,210 | def findFilesWithPattern ( self , fileName , searchPattern , fillFindData , dokanFileInfo ) : try : ret = self . operations ( 'findFilesWithPattern' , fileName , searchPattern ) if ret is None : return d1_onedrive . impl . drivers . dokan . const . DOKAN_ERROR for r in ret : create_ft = self . python_timestamp_to_win32... | Find files in a certain path that match the search pattern . |
45,211 | def setFileTime ( self , fileName , creationTime , lastAccessTime , lastWriteTime , dokanFileInfo ) : return self . operations ( 'setFileTime' , fileName ) | Set time values for a file . |
45,212 | def lockFile ( self , fileName , byteOffset , length , dokanFileInfo ) : return self . operations ( 'lockFile' , fileName , byteOffset , length ) | Lock a file . |
45,213 | def unlockFile ( self , fileName , byteOffset , length , dokanFileInfo ) : return self . operations ( 'unlockFile' , fileName , byteOffset , length ) | Unlock a file . |
45,214 | def getDiskFreeSpace ( self , freeBytesAvailable , totalNumberOfBytes , totalNumberOfFreeBytes , dokanFileInfo , ) : ret = self . operations ( 'getDiskFreeSpace' ) ctypes . memmove ( freeBytesAvailable , ctypes . byref ( ctypes . c_longlong ( ret [ 'freeBytesAvailable' ] ) ) , ctypes . sizeof ( ctypes . c_longlong ) , ... | Get the amount of free space on this volume . |
45,215 | def getVolumeInformation ( self , volumeNameBuffer , volumeNameSize , volumeSerialNumber , maximumComponentLength , fileSystemFlags , fileSystemNameBuffer , fileSystemNameSize , dokanFileInfo , ) : ret = self . operations ( 'getVolumeInformation' ) ctypes . memmove ( volumeNameBuffer , ret [ 'volumeNameBuffer' ] , min ... | Get information about the volume . |
45,216 | def getFileSecurity ( self , fileName , securityInformation , securityDescriptor , lengthSecurityDescriptorBuffer , lengthNeeded , dokanFileInfo , ) : return self . operations ( 'getFileSecurity' , fileName ) | Get security attributes of a file . |
45,217 | def setFileSecurity ( self , fileName , securityInformation , securityDescriptor , lengthSecurityDescriptorBuffer , dokanFileInfo , ) : return self . operations ( 'setFileSecurity' , fileName ) | Set security attributes of a file . |
45,218 | def createSimpleResourceMap ( ore_pid , sci_meta_pid , data_pids ) : ore = ResourceMap ( ) ore . initialize ( ore_pid ) ore . addMetadataDocument ( sci_meta_pid ) ore . addDataDocuments ( data_pids , sci_meta_pid ) return ore | Create a simple resource map with one metadata document and n data objects . |
45,219 | def pids2ore ( in_stream , fmt = 'xml' , base_url = 'https://cn.dataone.org/cn' ) : pids = [ ] for line in in_stream : pid = line . strip ( ) if len ( pid ) > 0 : if not pid . startswith ( "# " ) : pids . append ( pid ) if ( len ( pids ) ) < 2 : raise ValueError ( "Insufficient identifiers provided." ) logging . info (... | read pids from in_stream and generate a resource map . |
45,220 | def submit ( self , data , runtime_dir , argv ) : queue = 'ordinary' if data . process . scheduling_class == Process . SCHEDULING_CLASS_INTERACTIVE : queue = 'hipri' logger . debug ( __ ( "Connector '{}' running for Data with id {} ({}) in celery queue {}, EAGER is {}." , self . __class__ . __module__ , data . id , rep... | Run process . |
45,221 | def refresh ( self ) : if self . _source_tree . cache_is_stale ( ) : self . _source_tree . refresh ( ) logging . info ( 'Refreshing object tree' ) self . _init_cache ( ) self . sync_cache_with_source_tree ( ) | Synchronize the local tree of Solr records for DataONE identifiers and queries with the reference tree . |
45,222 | def get_object_record ( self , pid ) : try : return self . _cache [ 'records' ] [ pid ] except KeyError : raise d1_onedrive . impl . onedrive_exceptions . ONEDriveException ( 'Unknown PID' ) | Get an object that has already been cached in the object tree . |
45,223 | def get_object_record_with_sync ( self , pid ) : try : return self . _cache [ 'records' ] [ pid ] except KeyError : return self . _get_uncached_object_record ( pid ) | Get an object that may not currently be in the cache . |
45,224 | def dependency_status ( data ) : parents_statuses = set ( DataDependency . objects . filter ( child = data , kind = DataDependency . KIND_IO ) . distinct ( 'parent__status' ) . values_list ( 'parent__status' , flat = True ) ) if not parents_statuses : return Data . STATUS_DONE if None in parents_statuses : return Data ... | Return abstracted status of dependencies . |
45,225 | def discover_engines ( self , executor = None ) : if executor is None : executor = getattr ( settings , 'FLOW_EXECUTOR' , { } ) . get ( 'NAME' , 'resolwe.flow.executors.local' ) self . executor = self . load_executor ( executor ) logger . info ( __ ( "Loaded '{}' executor." , str ( self . executor . __class__ . __modul... | Discover configured engines . |
45,226 | def reset ( self , keep_state = False ) : if not keep_state : self . state = state . ManagerState ( state . MANAGER_STATE_PREFIX ) self . state . reset ( ) async_to_sync ( consumer . run_consumer ) ( timeout = 1 ) async_to_sync ( self . sync_counter . reset ) ( ) | Reset the shared state and drain Django Channels . |
45,227 | def _marshal_settings ( self ) : result = { } for key in dir ( settings ) : if any ( map ( key . startswith , [ 'FLOW_' , 'RESOLWE_' , 'CELERY_' ] ) ) : result [ key ] = getattr ( settings , key ) return result | Marshal Django settings into a serializable object . |
45,228 | def _include_environment_variables ( self , program , executor_vars ) : env_vars = { 'RESOLWE_HOST_URL' : self . settings_actual . get ( 'RESOLWE_HOST_URL' , 'localhost' ) , } set_env = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( 'SET_ENV' , { } ) env_vars . update ( executor_vars ) env_vars . update... | Define environment variables . |
45,229 | def run ( self , data , runtime_dir , argv ) : process_scheduling = self . scheduling_class_map [ data . process . scheduling_class ] if 'DISPATCHER_MAPPING' in getattr ( settings , 'FLOW_MANAGER' , { } ) : class_name = settings . FLOW_MANAGER [ 'DISPATCHER_MAPPING' ] [ process_scheduling ] else : class_name = getattr ... | Select a concrete connector and run the process through it . |
45,230 | def _get_per_data_dir ( self , dir_base , subpath ) : result = self . settings_actual . get ( 'FLOW_EXECUTOR' , { } ) . get ( dir_base , '' ) return os . path . join ( result , subpath ) | Extend the given base directory with a per - data component . |
45,231 | def _prepare_data_dir ( self , data ) : logger . debug ( __ ( "Preparing data directory for Data with id {}." , data . id ) ) with transaction . atomic ( ) : temporary_location_string = uuid . uuid4 ( ) . hex [ : 10 ] data_location = DataLocation . objects . create ( subpath = temporary_location_string ) data_location ... | Prepare destination directory where the data will live . |
45,232 | def _prepare_context ( self , data_id , data_dir , runtime_dir , ** kwargs ) : files = { } secrets = { } settings_dict = { } settings_dict [ 'DATA_DIR' ] = data_dir settings_dict [ 'REDIS_CHANNEL_PAIR' ] = state . MANAGER_EXECUTOR_CHANNELS files [ ExecutorFiles . EXECUTOR_SETTINGS ] = settings_dict django_settings = { ... | Prepare settings and constants JSONs for the executor . |
45,233 | def _prepare_executor ( self , data , executor ) : logger . debug ( __ ( "Preparing executor for Data with id {}" , data . id ) ) import resolwe . flow . executors as executor_package exec_dir = os . path . dirname ( inspect . getsourcefile ( executor_package ) ) dest_dir = self . _get_per_data_dir ( 'RUNTIME_DIR' , da... | Copy executor sources into the destination directory . |
45,234 | def _prepare_script ( self , dest_dir , program ) : script_name = ExecutorFiles . PROCESS_SCRIPT dest_file = os . path . join ( dest_dir , script_name ) with open ( dest_file , 'wt' ) as dest_file_obj : dest_file_obj . write ( program ) os . chmod ( dest_file , 0o700 ) return script_name | Copy the script into the destination directory . |
45,235 | async def handle_control_event ( self , message ) : cmd = message [ WorkerProtocol . COMMAND ] logger . debug ( __ ( "Manager worker got channel command '{}'." , cmd ) ) immediates = { } if cmd == WorkerProtocol . COMMUNICATE : immediates = message . get ( WorkerProtocol . COMMUNICATE_SETTINGS , { } ) or { } override =... | Handle an event from the Channels layer . |
45,236 | def _ensure_counter ( self ) : if not isinstance ( self . sync_counter , self . _SynchronizationManager ) : self . sync_counter = self . _SynchronizationManager ( ) | Ensure the sync counter is a valid non - dummy object . |
45,237 | async def execution_barrier ( self ) : async def _barrier ( ) : async with self . sync_counter : pass await consumer . exit_consumer ( ) self . _ensure_counter ( ) await asyncio . wait ( [ _barrier ( ) , consumer . run_consumer ( ) , ] ) self . sync_counter = self . _SynchronizationManagerDummy ( ) | Wait for executors to finish . |
45,238 | async def communicate ( self , data_id = None , run_sync = False , save_settings = True ) : executor = getattr ( settings , 'FLOW_EXECUTOR' , { } ) . get ( 'NAME' , 'resolwe.flow.executors.local' ) logger . debug ( __ ( "Manager sending communicate command on '{}' triggered by Data with id {}." , state . MANAGER_CONTRO... | Scan database for resolving Data objects and process them . |
45,239 | def _data_execute ( self , data , program , executor ) : if not program : return logger . debug ( __ ( "Manager preparing Data with id {} for processing." , data . id ) ) try : executor_env_vars = self . get_executor ( ) . get_environment_variables ( ) program = self . _include_environment_variables ( program , executo... | Execute the Data object . |
45,240 | def get_expression_engine ( self , name ) : try : return self . expression_engines [ name ] except KeyError : raise InvalidEngineError ( "Unsupported expression engine: {}" . format ( name ) ) | Return an expression engine instance . |
45,241 | def get_execution_engine ( self , name ) : try : return self . execution_engines [ name ] except KeyError : raise InvalidEngineError ( "Unsupported execution engine: {}" . format ( name ) ) | Return an execution engine instance . |
45,242 | def load_executor ( self , executor_name ) : executor_name = executor_name + '.prepare' module = import_module ( executor_name ) return module . FlowExecutorPreparer ( ) | Load process executor . |
45,243 | def get_queryset ( self ) : if self . request and self . request . query_params . get ( 'hydrate_data' , False ) : return self . queryset . prefetch_related ( 'data__entity_set' ) return self . queryset | Return queryset . |
45,244 | def _get_collection_for_user ( self , collection_id , user ) : collection_query = Collection . objects . filter ( pk = collection_id ) if not collection_query . exists ( ) : raise exceptions . ValidationError ( 'Collection id does not exist' ) collection = collection_query . first ( ) if not user . has_perm ( 'add_coll... | Check that collection exists and user has add permission . |
45,245 | def _get_entities ( self , user , ids ) : queryset = get_objects_for_user ( user , 'view_entity' , Entity . objects . filter ( id__in = ids ) ) actual_ids = queryset . values_list ( 'id' , flat = True ) missing_ids = list ( set ( ids ) - set ( actual_ids ) ) if missing_ids : raise exceptions . ParseError ( "Entities wi... | Return entities queryset based on provided entity ids . |
45,246 | def set_content_permissions ( self , user , obj , payload ) : payload = remove_permission ( payload , 'add' ) for data in obj . data . all ( ) : if user . has_perm ( 'share_data' , data ) : update_permission ( data , payload ) | Apply permissions to data objects in Entity . |
45,247 | def add_to_collection ( self , request , pk = None ) : entity = self . get_object ( ) if 'ids' not in request . data : return Response ( { "error" : "`ids` parameter is required" } , status = status . HTTP_400_BAD_REQUEST ) for collection_id in request . data [ 'ids' ] : self . _get_collection_for_user ( collection_id ... | Add Entity to a collection . |
45,248 | def add_data ( self , request , pk = None ) : resp = super ( ) . add_data ( request , pk ) entity = self . get_object ( ) for collection in entity . collections . all ( ) : collection . data . add ( * request . data [ 'ids' ] ) return resp | Add data to Entity and it s collection . |
45,249 | def move_to_collection ( self , request , * args , ** kwargs ) : ids = self . get_ids ( request . data ) src_collection_id = self . get_id ( request . data , 'source_collection' ) dst_collection_id = self . get_id ( request . data , 'destination_collection' ) src_collection = self . _get_collection_for_user ( src_colle... | Move samples from source to destination collection . |
45,250 | def update ( self , request , * args , ** kwargs ) : orig_get_queryset = self . get_queryset def patched_get_queryset ( ) : entity_ids = orig_get_queryset ( ) . values_list ( 'id' , flat = True ) return Entity . objects . filter ( id__in = entity_ids ) self . get_queryset = patched_get_queryset resp = super ( ) . updat... | Update an entity . |
45,251 | async def end ( self ) : try : await self . proc . wait ( ) finally : for temporary_file in self . temporary_files : temporary_file . close ( ) self . temporary_files = [ ] return self . proc . returncode | End process execution . |
45,252 | def iterjson ( text ) : decoder = json . JSONDecoder ( ) while text : obj , ndx = decoder . raw_decode ( text ) if not isinstance ( obj , dict ) : raise ValueError ( ) text = text [ ndx : ] . lstrip ( '\r\n' ) yield obj | Decode JSON stream . |
45,253 | async def _send_manager_command ( self , * args , ** kwargs ) : resp = await send_manager_command ( * args , ** kwargs ) if resp is False : await self . terminate ( ) | Send an update to manager and terminate the process if it fails . |
45,254 | def _create_file ( self , filename ) : file_descriptor = os . open ( filename , os . O_WRONLY | os . O_CREAT | os . O_EXCL ) return os . fdopen ( file_descriptor , 'w' ) | Ensure a new file is created and opened for writing . |
45,255 | def get_total_size_of_queued_replicas ( ) : return ( d1_gmn . app . models . ReplicationQueue . objects . filter ( local_replica__info__status__status = 'queued' ) . aggregate ( Sum ( 'size' ) ) [ 'size__sum' ] or 0 ) | Return the total number of bytes of requested unprocessed replicas . |
45,256 | def add_to_replication_queue ( source_node_urn , sysmeta_pyxb ) : replica_info_model = d1_gmn . app . models . replica_info ( status_str = 'queued' , source_node_urn = source_node_urn ) local_replica_model = d1_gmn . app . models . local_replica ( pid = d1_common . xml . get_req_val ( sysmeta_pyxb . identifier ) , repl... | Add a replication request issued by a CN to a queue that is processed asynchronously . |
45,257 | def add_arguments ( parser , doc_str , add_base_url = True ) : parser . description = doc_str parser . formatter_class = argparse . RawDescriptionHelpFormatter parser . add_argument ( "--debug" , action = "store_true" , help = "Debug level logging" ) parser . add_argument ( "--cert-pub" , dest = "cert_pem_path" , actio... | Add standard arguments for DataONE utilities to a command line parser . |
45,258 | def get_resource_map_members ( pid ) : if d1_gmn . app . did . is_resource_map_db ( pid ) : return get_resource_map_members_by_map ( pid ) elif d1_gmn . app . did . is_resource_map_member ( pid ) : return get_resource_map_members_by_member ( pid ) else : raise d1_common . types . exceptions . InvalidRequest ( 0 , 'Not ... | pid is the PID of a Resource Map or the PID of a member of a Resource Map . |
45,259 | def set_with_conversion ( self , variable , value_string ) : self . _assert_valid_variable ( variable ) try : v = ast . literal_eval ( value_string ) except ( ValueError , SyntaxError ) : v = value_string if v is None or v == "none" : self . _variables [ variable ] = None else : try : type_converter = variable_type_map... | Convert user supplied string to Python type . |
45,260 | def log_setup ( is_debug = False , is_multiprocess = False ) : format_str = ( '%(asctime)s %(name)s %(module)s:%(lineno)d %(process)4d %(levelname)-8s %(message)s' if is_multiprocess else '%(asctime)s %(name)s %(module)s:%(lineno)d %(levelname)-8s %(message)s' ) formatter = logging . Formatter ( format_str , '%Y-%m-%d ... | Set up a standardized log format for the DataONE Python stack . All Python components should use this function . If is_multiprocess is True include process ID in the log so that logs can be separated for each process . |
45,261 | def get_content_type ( content_type ) : m = email . message . Message ( ) m [ 'Content-Type' ] = content_type return m . get_content_type ( ) | Extract the MIME type value from a content type string . |
45,262 | def nested_update ( d , u ) : for k , v in list ( u . items ( ) ) : if isinstance ( v , collections . Mapping ) : r = nested_update ( d . get ( k , { } ) , v ) d [ k ] = r else : d [ k ] = u [ k ] return d | Merge two nested dicts . |
45,263 | def print_logging ( ) : root_logger = logging . getLogger ( ) old_level_list = [ h . level for h in root_logger . handlers ] for h in root_logger . handlers : h . setLevel ( logging . WARN ) log_format = logging . Formatter ( '%(message)s' ) stream_handler = logging . StreamHandler ( sys . stdout ) stream_handler . set... | Context manager to temporarily suppress additional information such as timestamps when writing to loggers . |
45,264 | def save_json ( py_obj , json_path ) : with open ( json_path , 'w' , encoding = 'utf-8' ) as f : f . write ( serialize_to_normalized_pretty_json ( py_obj ) ) | Serialize a native object to JSON and save it normalized pretty printed to a file . |
45,265 | def serialize_to_normalized_pretty_json ( py_obj ) : return json . dumps ( py_obj , sort_keys = True , indent = 2 , cls = ToJsonCompatibleTypes ) | Serialize a native object to normalized pretty printed JSON . |
45,266 | def serialize_to_normalized_compact_json ( py_obj ) : return json . dumps ( py_obj , sort_keys = True , separators = ( ',' , ':' ) , cls = ToJsonCompatibleTypes ) | Serialize a native object to normalized compact JSON . |
45,267 | def format_sec_to_dhm ( sec ) : rem_int , s_int = divmod ( int ( sec ) , 60 ) rem_int , m_int , = divmod ( rem_int , 60 ) d_int , h_int , = divmod ( rem_int , 24 ) return '{}d{:02d}h{:02d}m' . format ( d_int , h_int , m_int ) | Format seconds to days hours minutes . |
45,268 | def count ( self , event_str , inc_int = 1 ) : self . _event_dict . setdefault ( event_str , 0 ) self . _event_dict [ event_str ] += inc_int | Count an event . |
45,269 | def log_and_count ( self , event_str , msg_str = None , inc_int = None ) : logger . info ( ' - ' . join ( map ( str , [ v for v in ( event_str , msg_str , inc_int ) if v ] ) ) ) self . count ( event_str , inc_int or 1 ) | Count an event and write a message to a logger . |
45,270 | def dump_to_log ( self ) : if self . _event_dict : logger . info ( 'Events:' ) for event_str , count_int in sorted ( self . _event_dict . items ( ) ) : logger . info ( ' {}: {}' . format ( event_str , count_int ) ) else : logger . info ( 'No Events' ) | Write summary to logger with the name and number of times each event has been counted . |
45,271 | def delete_all_from_db ( ) : for model in django . apps . apps . get_models ( ) : model . objects . all ( ) . delete ( ) | Clear the database . |
45,272 | def get_limit ( self , request ) : if self . limit_query_param : try : return _positive_int ( get_query_param ( request , self . limit_query_param ) , strict = True , cutoff = self . max_limit ) except ( KeyError , ValueError ) : pass return self . default_limit | Return limit parameter . |
45,273 | def get_offset ( self , request ) : try : return _positive_int ( get_query_param ( request , self . offset_query_param ) , ) except ( KeyError , ValueError ) : return 0 | Return offset parameter . |
45,274 | def futurize_module ( module_path , show_diff , write_update ) : logging . info ( 'Futurizing module... path="{}"' . format ( module_path ) ) ast_tree = back_to_the_futurize ( module_path ) return d1_dev . util . update_module_file_ast ( ast_tree , module_path , show_diff , write_update ) | 2to3 uses AST not Baron . |
45,275 | def _remove_single_line_import_comments ( r ) : logging . info ( 'Removing single line import comments' ) import_r , remaining_r = split_by_last_import ( r ) new_import_r = redbaron . NodeList ( ) for i , v in enumerate ( import_r ) : if 1 < i < len ( import_r ) - 2 : if not ( import_r [ i - 2 ] . type != 'comment' and... | We previously used more groups for the import statements and named each group . |
45,276 | def configure_logging ( emit_list ) : if 'sphinx' in sys . modules : module_base = 'resolwe.flow.executors' else : module_base = 'executors' logging_config = dict ( version = 1 , formatters = { 'json_formatter' : { '()' : JSONFormatter } , } , handlers = { 'redis' : { 'class' : module_base + '.logger.RedisHandler' , 'f... | Configure logging to send log records to the master . |
45,277 | def format ( self , record ) : data = record . __dict__ . copy ( ) data [ 'data_id' ] = DATA [ 'id' ] data [ 'data_location_id' ] = DATA_LOCATION [ 'id' ] data [ 'hostname' ] = socket . gethostname ( ) data [ 'pathname' ] = os . path . relpath ( data [ 'pathname' ] , os . path . dirname ( __file__ ) ) data [ 'exc_info'... | Dump the record to JSON . |
45,278 | def emit ( self , record ) : future = asyncio . ensure_future ( send_manager_command ( ExecutorProtocol . LOG , extra_fields = { ExecutorProtocol . LOG_MESSAGE : self . format ( record ) , } , expect_reply = False ) ) self . emit_list . append ( future ) | Send log message to the listener . |
45,279 | def create_secret ( self , value , contributor , metadata = None , expires = None ) : if metadata is None : metadata = { } secret = self . create ( value = value , contributor = contributor , metadata = metadata , expires = expires , ) return str ( secret . handle ) | Create a new secret returning its handle . |
45,280 | def get_secret ( self , handle , contributor ) : queryset = self . all ( ) if contributor is not None : queryset = queryset . filter ( contributor = contributor ) secret = queryset . get ( handle = handle ) return secret . value | Retrieve an existing secret s value . |
45,281 | def validation_schema ( name ) : schemas = { 'processor' : 'processSchema.json' , 'descriptor' : 'descriptorSchema.json' , 'field' : 'fieldSchema.json' , 'type' : 'typeSchema.json' , } if name not in schemas : raise ValueError ( ) field_schema_file = finders . find ( 'flow/{}' . format ( schemas [ 'field' ] ) , all = T... | Return json schema for json validation . |
45,282 | def hydrate_input_references ( input_ , input_schema , hydrate_values = True ) : from . data import Data for field_schema , fields in iterate_fields ( input_ , input_schema ) : name = field_schema [ 'name' ] value = fields [ name ] if 'type' in field_schema : if field_schema [ 'type' ] . startswith ( 'data:' ) : if val... | Hydrate input_ with linked data . |
45,283 | def hydrate_size ( data , force = False ) : from . data import Data def get_dir_size ( path ) : total_size = 0 for dirpath , _ , filenames in os . walk ( path ) : for file_name in filenames : file_path = os . path . join ( dirpath , file_name ) if not os . path . isfile ( file_path ) : continue total_size += os . path ... | Add file and dir sizes . |
45,284 | def render_descriptor ( data ) : if not data . descriptor_schema : return for field_schema , field , path in iterate_schema ( data . descriptor , data . descriptor_schema . schema , 'descriptor' ) : if 'default' in field_schema and field_schema [ 'name' ] not in field : dict_dot ( data , path , field_schema [ 'default'... | Render data descriptor . |
45,285 | def render_template ( process , template_string , context ) : from resolwe . flow . managers import manager expression_engine = process . requirements . get ( 'expression-engine' , None ) if not expression_engine : return template_string return manager . get_expression_engine ( expression_engine ) . evaluate_block ( te... | Render template using the specified expression engine . |
45,286 | def json_path_components ( path ) : if isinstance ( path , str ) : path = path . split ( '.' ) return list ( path ) | Convert JSON path to individual path components . |
45,287 | def validate_process_subtype ( supertype_name , supertype , subtype_name , subtype ) : errors = [ ] for item in supertype : for subitem in subtype : if item [ 'name' ] != subitem [ 'name' ] : continue for key in set ( item . keys ( ) ) | set ( subitem . keys ( ) ) : if key in ( 'label' , 'description' ) : continue elif... | Perform process subtype validation . |
45,288 | def validate_process_types ( queryset = None ) : if not queryset : from . process import Process queryset = Process . objects . all ( ) processes = { } for process in queryset : dict_dot ( processes , process . type . replace ( ':' , '.' ) + '__schema__' , process . output_schema ) errors = [ ] for path , key , value i... | Perform process type validation . |
45,289 | def fill_with_defaults ( process_input , input_schema ) : for field_schema , fields , path in iterate_schema ( process_input , input_schema ) : if 'default' in field_schema and field_schema [ 'name' ] not in fields : dict_dot ( process_input , path , field_schema [ 'default' ] ) | Fill empty optional fields in input with default values . |
45,290 | def to_internal_value ( self , data ) : if isinstance ( data , dict ) and isinstance ( data . get ( 'id' , None ) , int ) : data = data [ 'id' ] elif isinstance ( data , int ) : pass else : raise ValidationError ( "Contributor must be an integer or a dictionary with key 'id'" ) return self . Meta . model . objects . ge... | Format the internal value . |
45,291 | def extract_descriptor ( self , obj ) : descriptor = [ ] def flatten ( current ) : if isinstance ( current , dict ) : for key in current : flatten ( current [ key ] ) elif isinstance ( current , list ) : for val in current : flatten ( val ) elif isinstance ( current , ( int , bool , float , str ) ) : descriptor . appen... | Extract data from the descriptor . |
45,292 | def _serialize_items ( self , serializer , kind , items ) : if self . request and self . request . query_params . get ( 'hydrate_{}' . format ( kind ) , False ) : serializer = serializer ( items , many = True , read_only = True ) serializer . bind ( kind , self ) return serializer . data else : return [ item . id for i... | Return serialized items or list of ids depending on hydrate_XXX query param . |
45,293 | def get_entity_names ( self , data ) : entities = self . _filter_queryset ( 'view_entity' , data . entity_set . all ( ) ) return list ( entities . values_list ( 'name' , flat = True ) ) | Return serialized list of entity names on data that user has view permission on . |
45,294 | def get_collections ( self , data ) : collections = self . _filter_queryset ( 'view_collection' , data . collection_set . all ( ) ) from . collection import CollectionSerializer class CollectionWithoutDataSerializer ( WithoutDataSerializerMixin , CollectionSerializer ) : return self . _serialize_items ( CollectionWitho... | Return serialized list of collection objects on data that user has view permission on . |
45,295 | def get_entities ( self , data ) : entities = self . _filter_queryset ( 'view_entity' , data . entity_set . all ( ) ) from . entity import EntitySerializer class EntityWithoutDataSerializer ( WithoutDataSerializerMixin , EntitySerializer ) : return self . _serialize_items ( EntityWithoutDataSerializer , 'entities' , en... | Return serialized list of entity objects on data that user has view permission on . |
45,296 | def handle ( self , * args , ** options ) : verbosity = int ( options . get ( 'verbosity' ) ) if options [ 'format' ] != 'plain' and options [ 'format' ] != 'yaml' : raise CommandError ( "Unknown output format: %s" % options [ 'format' ] ) unique_docker_images = set ( p . requirements [ 'executor' ] [ 'docker' ] [ 'ima... | Handle command list_docker_images . |
45,297 | def get_or_create ( self , request , * args , ** kwargs ) : kwargs [ 'get_or_create' ] = True return self . create ( request , * args , ** kwargs ) | Get Data object if similar already exists otherwise create it . |
45,298 | def perform_get_or_create ( self , request , * args , ** kwargs ) : serializer = self . get_serializer ( data = request . data ) serializer . is_valid ( raise_exception = True ) process = serializer . validated_data . get ( 'process' ) process_input = request . data . get ( 'input' , { } ) fill_with_defaults ( process_... | Perform get_or_create - return existing object if found . |
45,299 | def ready ( self ) : self . _assert_readable_file_if_set ( 'CLIENT_CERT_PATH' ) self . _assert_readable_file_if_set ( 'CLIENT_CERT_PRIVATE_KEY_PATH' ) self . _assert_dirs_exist ( 'OBJECT_FORMAT_CACHE_PATH' ) self . _assert_is_type ( 'SCIMETA_VALIDATION_ENABLED' , bool ) self . _assert_is_type ( 'SCIMETA_VALIDATION_MAX_... | Called once per Django process instance . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.